{*************************************************************************}
{ TMS ToolBars component                                                  }
{ for Delphi & C++Builder                                                 }
{                                                                         }
{ written by TMS Software                                                 }
{           copyright © 2006 - 2008                                       }
{           Email : info@tmssoftware.com                                  }
{           Web : http://www.tmssoftware.com                              }
{                                                                         }
{ The source code is given as is. The author is not responsible           }
{ for any possible damage done due to the use of this code.               }
{ The component can be freely used in any application. The complete       }
{ source code remains property of the author and may not be distributed,  }
{ published, given or sold in any form as such. No parts of the source    }
{ code can be included in any other component or application without      }
{ written authorization of the author.                                    }
{*************************************************************************}

unit AdvToolBar;

{$R ADVTOOLBAR.RES}
{$R ADVTOOLBARDB.RES}

{$I TMSDEFS.INC}
{$T-}

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Math, Registry,
  Menus, AdvMenus, Dialogs, Forms, ImgList, CommCtrl, ExtCtrls, ActnList,
  IniFiles, AdvGlowButton, AdvGDIP, GDIPicture, AdvHintInfo, TypInfo, AdvStyleIF
  {$IFNDEF TMS_STD}
  , DB
  {$ENDIF}
  {$IFNDEF TMSDOTNET}
  , AxCtrls
  {$ENDIF};

const
  CN_DROPDOWNCLOSED = WM_USER + $1000;

  DEFAULT_TOOLBARHEIGHT = 26;
  DEFAULT_MINLENGTH = 60;
  MINDOCKPANELHEIGHT = 3;
  DEFAULT_CAPTIONHEIGHT = 16;
  DEFAULT_ITEMHEIGHT = 20;
  DEFAULT_SEPARATORWIDTH = 10;
  IMG_SPACE = 2;
  MIN_BUTTONSIZE = 15;
  DEFAULT_POPUPINDICATORWIDTH = 14;
  MIN_POPUPWINDOWSIZE = 70;
  TOOLBAR_SECTION = 'UnDockedAdvToolBars';
  SCROLLER_SIZE = 32;
  DEFAULT_PAGERCAPTIONHEIGHT = 27;
  DEFAULT_TABHEIGHT = 26;
  ADVPAGE_OFFSET = 4;
  MIN_SPACING = 3;

  MDIBTNSIZE = 18; // 20
  SCROLLBTN_WIDTH = 12;
  TOOLBAR_ROWS = 3;

  MAJ_VER = 3; // Major version nr.
  MIN_VER = 1; // Minor version nr.
  REL_VER = 4; // Release nr.
  BLD_VER = 0; // Build nr.

  // version history
  // 1.0.0.0 : first release
  // 1.0.1.0 : Added properties TextAutoOptionMenu, TextOptionMenu to TAdvToolBar
  //         : Fix for autosizing rootitems in Delphi 5 / C++Builder 5
  // 1.0.1.1 : Fix with menustyler for TAdvDockPanel popupmenu
  // 1.0.2.0 : Extension to better handle shortcuts
  //         : Improved menu handling on multimonitor machines
  //         : Improved handling of tasCheck button type with Down property set in Object Inspector
  // 1.1.0.0 : Property AutoArrangeButtons property added to control auto-arrange of hidden buttons
  //         : TDBAdvToolbarButton added
  //         : Support to add a DB navigator to a toolbar added
  // 1.1.0.1 : Fix for appearance of auto option menu in Delphi 2005
  // 1.1.1.0 : Fix for resizing of toolbar
  //         : Fix for color issue with stylers
  //         : New bsCustom style in OfficeStyler & bsUser in FantasyStyler available
  //         : Fix for ParentStyler property setting
  // 1.2.0.0 : New Whidbey appearance
  //         : Stylers .LoadFromFile, SaveToFile support added
  //         : Improved styler setup & support to use stylers in datamodules
  // 1.2.0.1 : Improved AdvToolBarMenuButton with ShowCaption property
  //         : RichFormat action support enhanced
  // 1.2.0.2 : Fixed issue with visible parent window
  //         : Fixed issue with toolbar button shortcuts
  //         : Fixed issue with custom & user stylers
  // 1.3.0.0 : Dockpanel height lock capability added
  //         : DisabledImages support added
  //         : Fix for destroy of toolbarbutton for use in frames
  //         : New methods: MoveToolBarControl, InsertToolBarControl, AddToolBarControl, IndexOfToolbarControl
  //         : New public property ToolBarControls[index]: TControl
  //         : New public property ToolBarControlCount: integer;
  //         : New property TAdvDockPanel.UseRunTimeHeight
  //         : Support for MDI menu merging with MergeMenu, UnMergeMenu methods
  // 1.3.0.1 : Messages & hints for DB navigator toolbar based on VDBConsts
  //         : Improvements in Office 2003 style appearance
  //         : Fix in ToolBarControls[] access
  // 1.4.0.0 : New TAdvToolBarCustomizer component
  // 1.4.5.0 : TAdvToolBar.Visible added
  //         : TAdvToolBar.AutoDockOnClose added
  //         : Fixed issue with AdvToolBar control hide/unhide during resize
  // 1.4.6.0 : Added property DropDownButton to TAdvToolBarMenuButton
  // 1.4.6.1 : Fixed: issue with DockColor gradient direction persistence
  // 2.0.0.0 : Office 2007 style toolbar support
  // 2.0.0.1 : Fixed issue with removing toolbar at design time
  //         : Fixed issue with shortcut key on AdvToolBarMenuButton
  //         : Fixed issue with event handling on AdvToolBarMenuButton
  //         : Fixed issue with invoking modal forms from compact toolbar
  //         : Readonly property IsCompact:boolean exposed for toolbar
  // 2.0.0.2 : Fixed issue with removing ToolBar.DisabledImages imagelist at designtime
  //           Fixed issue with removing ToolBar.Menu at designtime
  // 2.0.0.3 : Improved: automatic imagelist assignment on AdvGlowButton insert at designtime
  //         : Improved Office 2007 styles for floating toolbars
  // 2.0.0.4 : Fixed AdvGlowButton's not added in Add/Remove button list
  // 2.0.0.5 : Fixed issue with painting / handling AdvPage.TabEnabled false
  //         : Property Compact added to programmatically control toolbar compact mode
  //         : Fixed issue with AdvGlowButton painting directly on TAdvPage
  // 2.0.0.6 : Improved minimizing with TAdvToolBarPager
  // 2.1.0.0 : PageIndex property added on TAdvPage
  //         : TabStop added for TAdvToolbarPager
  //         : Keyboard events added on TAdvToolBarPager
  //         : Keyboard support added on TAdvToolBarPager, TAdvToolBar
  //         : Several smaller fixes and code improvements
  // 2.2.0.0 : New: Keyboard shortcuthint support added
  //         : New: PageLeftMargin, PageRightMargin added
  //         : New: TabSettings.EndMargin property exposed
  //         : New: Central TAdvToolBarPager OptionPicture support added
  //         : New: AdvToolBar.ParentOptionPicture property added
  //         : Fixed issue with programmatic Compact mode handling
  //         : Fixed issue with separator size with Compact mode handling
  // 2.2.0.1 : Fixed issue with resizing/compact mode
  //         : Fixed issue with PagerCaption runtime color settings update
  // 2.2.0.2 : Fixed issue with auto hotkey handling on menu update
  // 2.2.5.0 : Fixed issue with setting button image through customizer
  //         : Fixed issue with deleting button through customizer and Reset
  //         : Fixed issue with AutoPositionControls with tsfixed state
  //         : New: added support for using TMS Advanced Office selectors
  //         : New: added support for design time positioning of controls on Office2003 toolbar
  // 2.2.5.1 : Fixed issue with sizing toolbar & compact buttons
  // 2.2.6.0 : New: exposed ToolBarIndex property
  // 2.5.0.0 : New: OnResize event added
  //         : New: support for MDI built-in in TAdvToolBarPager
  //         : New: TAdvPreviewMenu & TAdvShapeButton added
  //         : New: TAdvToolBar.AdvDockPanel property added
  //         : New: Office 2007 silver style added
  // 2.5.1.0 : New: double click on caption changes window state between maximized & normal
  // 2.5.1.1 : Fixed : issue with floating toolbar size persistence
  // 2.5.1.2 : Fixed : issue with disabled/hidden toolbar controls and shortcut hints
  // 2.6.0.0 : New : Methods Expand/Collaps added in TAdvToolBarPager
  //         : New : Action support in TAdvPreviewMenu
  //         : New : Visible property added for Menuitems & SubMenuItems in TAdvPreviewMenu
  //         : New : OnClick events added for Menuitems & SubMenuItems in TAdvPreviewMenu
  // 2.6.0.1 : Fixed : GDI resource leak issue on Win98 in TAdvToolBarPager
  // 2.6.1.0 : Fixed : support for customize dialog for TAdvGlowButton
  //         : New : delay for showing shortcut hints
  // 2.6.1.1 : Improved : Office 2003 color schemes
  
  // 2.7.0.0 : Added Unicode support for TAdvToolBar captions
  //           Added Unicode support for TAdvPage tab captions
  //           Added Unicode support for TTabGroup captions
  //           Added Unicode support for TAdvToolBarPager caption
  //           Added Unicode support for TAdvGlowButton caption
  //           Added Unicode support for OfficeHint title & notes
  //           New : TAdvQuickAccessToolBar
  //           Improved : Tab sizing in TAdvToolBarPager
  //           New : OnCanShow event for customizer dialog
  // 2.7.0.1 : Fixed : focus handling for compact toolbutton dropdown
  //         : Fixed : issue with QAT height
  // 2.7.0.2 : Fixed : issue with QAT dropdown menu position
  // 2.7.0.3 : Improved : QAT drawing
  //         : Fixed : issue with design time toolbar delete
  // 2.7.0.4 : New : Display of shortcut hints on QAT
  //         : Improved : handling of shortcut hint display on toolbar
  //         : Improved : design time right-click menu for QAT controls
  // 2.7.0.5 : Fixed : issue with shortcut key handling on QAT
  // 2.7.5.0 : New : Wizard to create apps or add forms with TAdvToolBarPager
  
  // 2.8.0.0 : New : DockMode property added in TAdvToolBar
  //         : New : Office 2007 style toolbar button sizing control
  //         : Improved : transparent drawing of TAdvOfficeButton controls on TAdvToolBar
  // 2.8.0.1 : Fixed : issue with runtime toolbar create & destroy
  //         : Fixed : painting issue with toolbar container
  // 2.8.0.2 : Fixed : issue with compact TAdvPage display
  // 2.8.0.3 : Fixed : issue with TAdvToolBarPager caption centered drawing
  // 2.8.0.4 : Fixed : issue with dragging form through TAdvToolBarPager caption
  //         : Fixed : issue with alignment of min,max,close button in TAdvToolBarPager caption
  // 2.8.1.0 : New : TAdvPageCaption.MinWidth property added
  // 2.8.1.1 : Fixed : handling style changes for compact toolbars
  // 2.8.2.0 : New : exposed DoDropDown method for TAdvCustomToolBarButton
  //         : New : method MoveUpInRUList added in TAdvToolBar

  // 2.9.0.0 : New : AdvPreviewMenu designtime editor
  //         : New : TAdvToolBarForm
  //         : New : TAdvOfficeStatusBar
  //         : New : automatic system font selection support, uses Segoe UI font on Windows Vista
  // 2.9.0.1 : Fixed : small issue with tab font color setting
  // 2.9.1.0 : New : submenu selector in TAdvPreviewMenu designer
  //         : Improved : wizard
  // 2.9.1.1 : Fixed issue with toolbar size update

  // 3.0.0.0 : New : Notes text with NotesFont in TAdvGlowButton
  //         : New : Notes text with NotesFont in TAdvMainMenu, TAdvPopupMenu
  //         : New : Windows Vista color style for TAdvMainMenu, TAdvPopupMenu
  //         : New : Antialiased menu text drawing
  //         : Improved : multimonitor support for TAdvToolBarForm
  //         : Improved : maximize state handling of TAdvToolBarForm
  //         : Improved : painting of TAdvGlowButton, TAdvContainer
  //         : Improved : statusbar painting
  //         : Improved : Windows system menu handling on TAdvToolBarPager Caption

  // 3.0.1.1 : Fixed : issues in AdvMenus & AdvGlowButton
  // 3.0.1.2 : Fixed : issue with form inheritance and menus
  // 3.0.5.0 : New : tab handling to TAdvPreviewMenu
  //         : New : wizard creates Quick Access Toolbar (QAT)
  //         : Fixed : issue with deleting styler at design time
  //         : Fixed : issues with actions on TAdvGlowButton
  //         : Improved : various smaller painting improvements in TAdvGlowButton
  //         : Improved : TAdvPreviewMenu design time editor
  //         : Improved : tab key handling in previewmenu
  // 3.0.6.0 : New : public event OnCompactCloseQuery added in TAdvToolBar
  // 3.0.6.1 : Fixed : issue with loading position & invisible toolbar controls
  // 3.0.6.2 : Fixed : issue with toolbar menu positioning with shortcuts on form right-side
  // 3.0.6.3 : Fixed : small issue with selection of menus on toolbars
  // 3.0.7.0 : New : mousewheel support to change active toolbar page
  // 3.0.7.1 : New : toolbar menu supports menu disabled images
  // 3.0.7.2 : Fixed : issue with optionmenu imagelist images
  //         : Fixed : repainting issue with TAdvShapeButton
  //         : Fixed : issue with using TAdvOfficePager on a frame
  //         : New : exposed the toolbar displayed menu as TAdvToolBar.ActiveMenu
  // 3.0.8.0 : New : property EnableWheel added in TAdvToolBarPager
  // 3.0.8.1 : Fixed : issue when using font not installed on system
  // 3.0.8.2 : Improved : tasCheck style TAdvToolBarButton can have dropdown menu
  //         : Improved : toolbar & toolbar control persistence
  // 3.0.8.3 : Fixed : issue with TAdvToolBarForm background painting
  //         : Fixed : issue with not visible toolbar buttons at design time
  // 3.0.8.4 : Fixed : issue with toolbar variable size and specific button sizes
  // 3.0.9.0 : New : method ArrangeToolBars added in TAdvDockPanel
  // 3.0.9.1 : Fixed : TAdvToolBarContainer transparency issue
  //         : Improved : AddAdvToolBar function assigns styler automatically
  // 3.0.9.2 : Fixed : issue with changing Images size in undocked state
  // 3.0.10.0: New : TAdvToolbarPager.OnTabClick, OnTabDblClick event added
  //         : New : OnCustomizeClick event added
  //         : New : ShortCutHintPos shpCenter type added
  //         : Improved : TAdvToolBarPager auto expands when a tab is clicked in collapsed mode
  //         : Improved : minor visual details to comply with Microsoft UI guidelines
  //         : Improved : auto control positioning
  // 3.0.10.1: Fixed : issue with Window activation after option menu modal dialog use
  // 3.0.10.2: Fixed : issue with AutoSize = true & AutoPositionControls = true, AutoSize gets priority
  // 3.1.0.0 : Improved : automatic collaps/expand of the ribbon from double click on page tab
  //         : Improved : Ctrl-F1 will automatically expand/collaps the ribbon
  //         : New : property TAdvToolBarPager.Expanded exposed to get minimized/normal state of ribbon
  //         : New : built-in persistence of ribbon minimized/normal state
  //         : New : autohide of the ribbon when the ribbon width is below 300 pixels
  //         : New : automatic tooltips for tabs with truncated caption text
  //         : New : method exposed to programmatically hide & show shortcut hints
  //         : New : property CompactShortCutHint to set a separate shortcut hint for a toolbar in compact state
  //         : New : event OnTabGroupClick
  //         : Improved : tab scrolling disabled when ribbon is minimized
  //         : Improved : display of wordwrapped text in TAdvGlowButton
  //         : Improved : QAT painting
  //         : Improved : shadow, highlight, gradient painting improvements in ribbon
  //         : Improved : ribbon can float over form during temporary unhide
  //         : Improved : ESC key handling
  //         : Improved : Office 2003 toolbar customizer dialog
  //         : Improved : automatic sizing and handling of Office 2007 style hints

  // 3.1.0.1 : Improved : multi monitor support
  //         : Fixed : issue with using two instances of a TAdvToolBarPager on a form

  // 3.1.0.2 : Fixed : issue with toolbar height during minimize with QAT position change
  //         : Improved : AdvtoolBarButton appearances for Office2007 styles
  //         : New : osWhidbey style in TAdvMenuOfficeStyler for compatibility with whidbey toolbar style

  // 3.1.0.3 : Improved : display of compact toolbars
  // 3.1.0.4 : Fixed : Alt key required for switching pages with prefix char
  //         : Improved : multimonitor support
  // 3.1.1.0 : New : HidePagesOnDblClick property added
  // 3.1.1.1 : Fixed : issue with using toolbars on inherited forms at design time
  // 3.1.2.0 : New : ribbon toolbar option picture by default initialized
  //         : Improved : menu positioning on right edge of screen
  // 3.1.3.0 : New : method toolbar.UpdateControlsVisibility added
  // 3.1.3.1 : Fixed : transparency issue in popup menu on Windows Vista
  // 3.1.3.2 : Improved : toolbar background bitmap drawing
  // 3.1.3.3 : Improved : hint display on compact buttons
  // 3.1.4.0 : New : event OnDblClick exposed on TAdvPage
  //         : Fixed : issue with destroying styler 

          
var
  WM_TBCOMPACTWINHIDE: Word;

type
  {$IFDEF DELPHI_UNICODE}
  THintInfo = Controls.THintInfo;
  PHintInfo = Controls.PHintInfo;
  {$ENDIF}

  TAdvCustomToolBar = class;
  TAdvDockPanel = class;
  TFloatingWindow = class;
  TOptionSelectorPanel = class;
  TOptionSelectorWindow = class;
  TControlSelectorPanel = class;
  TATBPopupWindow = class;
  TATBCustomPopupPanel = class;
  TATBPopupPanel = class;
  TATBMenuItem = class;
  TAdvToolBarCustomizer = class;
  TAdvToolBarContainer = class;
  TAdvPage = class;
  TAdvToolBarPager = class;
  TCustomTabAppearance = class;
  TTabAppearance = class;
  TVistaBackground = class;
  TVistaPageBackground = class;
  TQATAppearance = class;
  TVistaTextBackground = class;
  TGroupAppearance = class;
  TCompactWindow = class;
  TAdvPageScrollButton = class;
  TAdvQuickAccessToolBar = class;
  TMinimizedRibbonWindow = class;

  TGradientDirection = (gdHorizontal, gdVertical);
  TDockAlign = (daLeft, daTop, daRight, daBottom);
  TBackGroundDisplay = (bdTile, bdCenter, bdStretch);
  TDragGripStyle = (dsDots, dsSingleLine, dsDoubleLine, dsFlatDots, dsNone);

  TToolBarState = (tsDocked, tsFloating, tsFixed);
  TItemChangeAction = (icRefresh, isResize);
  TButtomItemStyle = (bisButton, bisCheck);
  TGlyphPosition = (gpLeft, gpTop, gpRight, gpBottom);
  TCaptionPosition = (cpTop, cpBottom);
  TCaptionButton = (cbClose, cbMinimize, cbMaximize);
  TCaptionButtons = set of TCaptionButton;
  //TTabGlowState = (gsHover, gsPush, gsNone);
  TScrollArrow = (saLeft, saTop, saRight, saBottom, saNone);
  TArrowStyle = (asSingle, asDouble, asWithLine);
  TDockMode = (dmAll, dmAllParentDockPanels, dmParentDockPanelOnly);

  TDockableTo = set of TDockAlign;

  TAdvCustomToolBarButton = class;

  TProForm = class(TCustomForm);

  TProWinControl = class(TWinControl);

  TProCustomGlowButton = class(TAdvCustomGlowButton);

  TProControl = class(TControl);

  TDbgList = class(TList)
  private
    function GetItemsEx(Index: Integer): Pointer;
    procedure SetItemsEx(Index: Integer; const Value: Pointer);
  public
    procedure AssignList(ListA: TList);
    property Items[Index: Integer]: Pointer read GetItemsEx write SetItemsEx; default;
  end;

  TButtonAppearance = class(TPersistent)
  private
    FOnChange: TNotifyEvent;
    FColorHot: TColor;
    FColorTo: TColor;
    FColor: TColor;
    FColorHotTo: TColor;
    FColorDownTo: TColor;
    FColorDown: TColor;
    FBorderDownColor: TColor;
    FBorderColor: TColor;
    FBorderHotColor: TColor;
    FGradientDirection: TGradientDirection;
    FColorChecked: TColor;
    FColorCheckedTo: TColor;
    FCaptionTextColorChecked: TColor;
    FCaptionTextColor: TColor;
    FCaptionTextColorHot: TColor;
    FCaptionTextColorDown: TColor;
    FBorderCheckedColor: TColor;
    FCaptionFont: TFont;
    FGlyphPosition: TGlyphPosition;
    FGradientDirectionDown: TGradientDirection;
    FGradientDirectionHot: TGradientDirection;
    FGradientDirectionChecked: TGradientDirection;
    FSystemFont: Boolean;
    procedure Change;
    procedure SetBorderColor(const Value: TColor);
    procedure SetColor(const Value: TColor);
    procedure SetColorDown(const Value: TColor);
    procedure SetColorDownTo(const Value: TColor);
    procedure SetColorHot(const Value: TColor);
    procedure SetColorHotTo(const Value: TColor);
    procedure SetColorTo(const Value: TColor);
    procedure SetGradientDirection(const Value: TGradientDirection);
    procedure SetColorChecked(const Value: TColor);
    procedure SetColorCheckedTo(const Value: TColor);
    procedure SetCaptionTextColor(const Value: TColor);
    procedure SetCaptionTextColorDown(const Value: TColor);
    procedure SetCaptionTextColorHot(const Value: TColor);
    procedure SetCaptionTextColorChecked(const Value: TColor);
    procedure SetBorderCheckedColor(const Value: TColor);
    procedure SetCaptionFont(const Value: TFont);
    procedure SetGlyphPosition(const Value: TGlyphPosition);
    procedure SetGradientDirectionChecked(const Value: TGradientDirection);
    procedure SetGradientDirectionDown(const Value: TGradientDirection);
    procedure SetGradientDirectionHot(const Value: TGradientDirection);
    procedure SetSystemFont(const Value: Boolean);
  protected
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property GlyphPosition: TGlyphPosition read FGlyphPosition write SetGlyphPosition default gpLeft;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property Color: TColor read FColor write SetColor default clNone;
    property ColorTo: TColor read FColorTo write SetColorTo default clNone;
    property ColorChecked: TColor read FColorChecked write SetColorChecked default $00D8D5D4;
    property ColorCheckedTo: TColor read FColorCheckedTo write SetColorCheckedTo default clNone;
    property ColorDown: TColor read FColorDown write SetColorDown default $00B59285;
    property ColorDownTo: TColor read FColorDownTo write SetColorDownTo default clNone;
    property ColorHot: TColor read FColorHot write SetColorHot default $00D2BDB6;
    property ColorHotTo: TColor read FColorHotTo write SetColorHotTo default clNone;
    property CaptionTextColor: TColor read FCaptionTextColor write SetCaptionTextColor default clBlack;
    property CaptionTextColorHot: TColor read FCaptionTextColorHot write SetCaptionTextColorHot default clBlack;
    property CaptionTextColorDown: TColor read FCaptionTextColorDown write SetCaptionTextColorDown default clBlack;
    property CaptionTextColorChecked: TColor read FCaptionTextColorChecked write SetCaptionTextColorChecked default clBlack;
    property GradientDirection: TGradientDirection read FGradientDirection write SetGradientDirection default gdVertical;
    property GradientDirectionHot: TGradientDirection read FGradientDirectionHot write SetGradientDirectionHot default gdVertical;
    property GradientDirectionDown: TGradientDirection read FGradientDirectionDown write SetGradientDirectionDown default gdVertical;
    property GradientDirectionChecked: TGradientDirection read FGradientDirectionChecked write SetGradientDirectionChecked default gdVertical;
    property BorderColor: TColor read FBorderColor write SetBorderColor default clNone;
    property BorderDownColor: TColor read FBorderDownColor write FBorderDownColor default $006A240A;
    property BorderHotColor: TColor read FBorderHotColor write FBorderHotColor default $006A240A;
    property BorderCheckedColor: TColor read FBorderCheckedColor write SetBorderCheckedColor default $006A240A;
    property CaptionFont: TFont read FCaptionFont write SetCaptionFont;
    property SystemFont: Boolean read FSystemFont write SetSystemFont default true;
    //property GlyphPosition: TGlyphPosition read FGlyphPosition write SetGlyphPosition default gpLeft;
  end;

  TGradientBackground = class(TPersistent)
  private
    FSteps: Integer;
    FColor: TColor;
    FColorTo: TColor;
    FDirection: TGradientDirection;
    FOnChange: TNotifyEvent;
    procedure SetColor(const Value: TColor);
    procedure SetColorTo(const Value: TColor);
    procedure SetDirection(const Value: TGradientDirection);
    procedure SetSteps(const Value: Integer);
    procedure Changed;
  protected
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
  published
    property Color: TColor read FColor write SetColor;
    property ColorTo: TColor read FColorTo write SetColorTo;
    property Direction: TGradientDirection read FDirection write SetDirection;
    property Steps: Integer read FSteps write SetSteps default 64;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;


  TMirrorGradient = class(TPersistent)
  private
    FColorTo: TColor;
    FColor: TColor;
    FOnChange: TNotifyEvent;
    FColorMirrorTo: TColor;
    FColorMirror: TColor;
    procedure SetColor(const Value: TColor);
    procedure SetColorTo(const Value: TColor);
    procedure SetColorMirror(const Value: TColor);
    procedure SetColorMirrorTo(const Value: TColor);
  protected
    procedure Changed;
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
  published
    property Color: TColor read FColor write SetColor;
    property ColorTo: TColor read FColorTo write SetColorTo;
    property ColorMirror: TColor read FColorMirror write SetColorMirror;
    property ColorMirrorTo: TColor read FColorMirrorTo write SetColorMirrorTo;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;

  TVistaGradientBackground = class(TGradientBackground)
  private
    FMirror: TMirrorGradient;
    procedure SetMirror(const Value: TMirrorGradient);
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property Mirror: TMirrorGradient read FMirror write SetMirror;
  end;

  TContainerAppearance = class(TPersistent)
  private
    FOnChange: TNotifyEvent;
    FLine3D: Boolean;
    FLineColor: TColor;
    procedure SetLine3D(const Value: Boolean);
    procedure SetLineColor(const Value: TColor);
  protected
    procedure Changed;
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
  published
    property LineColor: TColor read FLineColor write SetLineColor;
    property Line3D: Boolean read FLine3D write SetLine3D;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;

  TCaptionAppearance = class(TPersistent)
  private
    FOnChange: TNotifyEvent;
    FCaptionTextColorHot: TColor;
    FCaptionTextColor: TColor;
    FCaptionBorderColorHot: TColor;
    FCaptionColorHot: TColor;
    FCaptionColorTo: TColor;
    FCaptionColor: TColor;
    FCaptionColorHotTo: TColor;
    FCaptionBorderColor: TColor;
    procedure SetCaptionBorderColor(const Value: TColor);
    procedure SetCaptionBorderColorHot(const Value: TColor);
    procedure SetCaptionColor(const Value: TColor);
    procedure SetCaptionColorHot(const Value: TColor);
    procedure SetCaptionColorHotTo(const Value: TColor);
    procedure SetCaptionColorTo(const Value: TColor);
    procedure SetCaptionTextColor(const Value: TColor);
    procedure SetCaptionTextColorHot(const Value: TColor);
  protected
    procedure Changed;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
  published
    property CaptionColor: TColor read FCaptionColor write SetCaptionColor;
    property CaptionColorTo: TColor read FCaptionColorTo write SetCaptionColorTo default clNone;
    property CaptionTextColor: TColor read FCaptionTextColor write SetCaptionTextColor default clWhite;
    property CaptionBorderColor: TColor read FCaptionBorderColor write SetCaptionBorderColor default clNone;
    property CaptionColorHot: TColor read FCaptionColorHot write SetCaptionColorHot default clNone;
    property CaptionColorHotTo: TColor read FCaptionColorHotTo write SetCaptionColorHotTo default clNone;
    property CaptionTextColorHot: TColor read FCaptionTextColorHot write SetCaptionTextColorHot default clWhite;
    property CaptionBorderColorHot: TColor read FCaptionBorderColorHot write SetCaptionBorderColorHot default clNone;
  end;

  //PropID: 4 for AdvContainer
  //PropID: 5 for update Positioning
  //PropID: 6 for AdvMenuStyler Change
  //PropID: 7 for AdvGlowButton Appearance
  //PropID: 10 for AdvToolBarPager
  //PropID: 11 for PagerCaption
  //PropID: 12 for Quick access ToolBar (QAT)
  
  TCustomAdvToolBarStyler = class(TComponent)
  private
    FBackGroundTransparent: Boolean;
    FBackGroundDisplay: TBackGroundDisplay;
    FBackGround: TBitMap;
    FColor: TVistaGradientBackground;
    FDockColor: TGradientBackground;
    FInternalAdvMenuStyler: TCustomAdvMenuStyler;
    FAdvMenuStyler: TCustomAdvMenuStyler;
    FCurrentAdvMenuStyler: TCustomAdvMenuStyler;
    FDragGripStyle: TDragGripStyle;
    FDragGripImage: TBitMap;
    //FPopupIndicatorStyle: TPopupIndicatorStyle;
    FRightHandleImage: TBitmap;
    FFont: TFont;
    FTransparent: Boolean;
    FControlList: TDbgList;
    FRoundEdges: boolean;
    FRightHandleColor: TColor;
    FRightHandleColorHot: TColor;
    FRightHandleColorTo: TColor;
    FRightHandleColorHotTo: TColor;
    FFloatingWindowBorderWidth: integer;
    FFloatingWindowBorderColor: TColor;
    FButtonAppearance: TButtonAppearance;
    FAutoThemeAdapt: boolean;
    FRightHandleColorDownTo: TColor;
    FRightHandleColorDown: TColor;
    FBevel: TPanelBevel;
    FUseBevel: Boolean;
    FBorderColorHot: TColor;
    FBorderColor: TColor;
    FColorHot: TVistaGradientBackground;
    FCaptionFont: TFont;
    FTMSStyle: TTMSStyle;
    FContainerAppearance: TContainerAppearance;
    FGlowButtonAppearance: TGlowButtonAppearance;
    FPagerCaption: TVistaTextBackground;
    FTabAppearance: TTabAppearance;
    FPageAppearance: TVistaPageBackground;
    FCaptionAppearance: TCaptionAppearance;
    FGroupAppearance: TGroupAppearance;
    FCompactGlowButtonAppearance: TGlowButtonAppearance;
    FQATAppearance: TQATAppearance;
    FSystemFont: boolean;
    FQatSharpCurve: boolean;
    procedure OnPagerCaptionChanged(Sender: TObject);
    procedure OnTabAppearanceChanged(Sender: TObject);
    procedure OnPageAppearanceChanged(Sender: TObject);
    procedure OnGroupAppearanceChanged(Sender: TObject);
    procedure OnContainerAppearanceChanged(Sender: TObject);
    procedure OnGlowButtonAppearanceChanged(Sender: TObject);
    procedure OnCaptionAppearanceChanged(Sender: TObject);
    procedure OnQATAppearanceChanged(Sender: TObject);
    procedure SetBackGround(const Value: TBitMap);
    procedure SetBackGroundDisplay(const Value: TBackGroundDisplay);
    procedure SetBackGroundTransparent(const Value: Boolean);
    procedure SetColor(const Value: TVistaGradientBackground);
    procedure SetAdvMenuStyler(const Value: TCustomAdvMenuStyler);
    procedure SetDragGripStyle(const Value: TDragGripStyle);
    procedure SetDragGripImage(const Value: TBitMap);
    procedure SetRightHandleImage(const Value: TBitmap);
    procedure SetFont(const Value: TFont);
    procedure SetTransparent(const Value: Boolean);
    procedure SetRoundEdges(const Value: boolean);
    procedure SetRightHandleColor(const Value: TColor);
    procedure SetRightHandleColorHot(const Value: TColor);
    procedure SetFloatingWindowBorderColor(const Value: TColor);
    procedure SetFloatingWindowBorderWidth(const Value: integer);
    procedure SetTButtonAppearance(const Value: TButtonAppearance);
    procedure SetDockColor(const Value: TGradientBackground);
    procedure SetRightHandleColorTo(const Value: TColor);
    procedure SetRightHandleColorHotTo(const Value: TColor);
    procedure SetRightHandleColorDown(const Value: TColor);
    procedure SetRightHandleColorDownTo(const Value: TColor);
    procedure SetBevel(const Value: TPanelBevel);
    procedure SetUseBevel(const Value: Boolean);
    procedure SetBorderColor(const Value: TColor);
    procedure SetBorderColorHot(const Value: TColor);
    procedure SetColorHot(const Value: TVistaGradientBackground);
    procedure SetCaptionFont(const Value: TFont);
    procedure SetContainerAppearance(const Value: TContainerAppearance);
    procedure SetGlowButtonAppearance(const Value: TGlowButtonAppearance);
    procedure SetPagerCaption(const Value: TVistaTextBackground);
    procedure SetTabAppearance(const Value: TTabAppearance);
    procedure SetPageAppearance(const Value: TVistaPageBackground);
    procedure SetGroupAppearance(const Value: TGroupAppearance);
    procedure SetCaptionAppearance(const Value: TCaptionAppearance);
    procedure SetCompactGlowButtonAppearance(const Value: TGlowButtonAppearance);
    procedure SetQATAppearance(const Value: TQATAppearance);
    procedure SetSystemFont(const Value: boolean);
  protected
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure BackgroundChanged(Sender: TObject);

    property CurrentAdvMenuStyler: TCustomAdvMenuStyler read FCurrentAdvMenuStyler;

    property AutoThemeAdapt: boolean read FAutoThemeAdapt write FAutoThemeAdapt default False;

    property ButtonAppearance: TButtonAppearance read FButtonAppearance write SetTButtonAppearance; // PropID 3

    property Color: TVistaGradientBackground read FColor write SetColor;
    property DockColor: TGradientBackground read FDockColor write SetDockColor;

    property BackGround: TBitMap read FBackGround write SetBackGround;
    property BackGroundTransparent: Boolean read FBackGroundTransparent write SetBackGroundTransparent default true;
    property BackGroundDisplay: TBackGroundDisplay read FBackGroundDisplay write SetBackGroundDisplay default bdTile;

    property Font: TFont read FFont write SetFont;

    property QATSharpCurve: Boolean read FQATSharpCurve write FQATSharpCurve;
    {===== AdvToolBar Properties -PropID: 2- =====}
    property DragGripStyle: TDragGripStyle read FDragGripStyle write SetDragGripStyle default dsDots;
    property DragGripImage: TBitMap read FDragGripImage write SetDragGripImage;

    //property PopupIndicatorStyle: TPopupIndicatorStyle read FPopupIndicatorStyle write SetPopupIndicatorStyle default psOffice2003;
    property RightHandleImage: TBitmap read FRightHandleImage write SetRightHandleImage;
    property RightHandleColor: TColor read FRightHandleColor write SetRightHandleColor default clGray;
    property RightHandleColorHot: TColor read FRightHandleColorHot write SetRightHandleColorHot;
    property RightHandleColorTo: TColor read FRightHandleColorTo write SetRightHandleColorTo default clGray;
    property RightHandleColorHotTo: TColor read FRightHandleColorHotTo write SetRightHandleColorHotTo;
    property RightHandleColorDown: TColor read FRightHandleColorDown write SetRightHandleColorDown;
    property RightHandleColorDownTo: TColor read FRightHandleColorDownTo write SetRightHandleColorDownTo;

    property FloatingWindowBorderColor: TColor read FFloatingWindowBorderColor write SetFloatingWindowBorderColor;
    property FloatingWindowBorderWidth: integer read FFloatingWindowBorderWidth write SetFloatingWindowBorderWidth default 2;
    property Bevel: TPanelBevel read FBevel write SetBevel default bvNone;
    property RoundEdges: boolean read FRoundEdges write SetRoundEdges default True;
    property Transparent: Boolean read FTransparent write SetTransparent default false;
    property UseBevel: Boolean read FUseBevel write SetUseBevel default False;

    property BorderColor: TColor read FBorderColor write SetBorderColor default clNone;
    property BorderColorHot: TColor read FBorderColorHot write SetBorderColorHot default clNone;
    property ColorHot: TVistaGradientBackground read FColorHot write SetColorHot;
    property CaptionFont: TFont read FCaptionFont write SetCaptionFont;
    {========== AdvContainer ==========}
    property ContainerAppearance: TContainerAppearance read FContainerAppearance write SetContainerAppearance;  // PropID 4
    {========== AdvToolBarPager ===========}
    property PagerCaption: TVistaTextBackground read FPagerCaption write SetPagerCaption;
    property TabAppearance: TTabAppearance read FTabAppearance write SetTabAppearance;
    property PageAppearance: TVistaPageBackground read FPageAppearance write SetPageAppearance;
    property GroupAppearance: TGroupAppearance read FGroupAppearance write SetGroupAppearance;
    property QATAppearance: TQATAppearance read FQATAppearance write SetQATAppearance;
    property TMSStyle: TTMSStyle read FTMSStyle write FTMSStyle;
  protected
    procedure Change(PropID: integer);
    procedure LoadPropFromFile(var F: TextFile);
    procedure SavePropToFile(var F: TextFile);
    procedure ReleaseAllControls;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Loaded; override;
    procedure UpdateStyle;
    procedure AddControl(AControl: TCustomControl);
    procedure RemoveControl(AControl: TCustomControl);
    procedure Assign(Source: TPersistent); override;
    property AdvMenuStyler: TCustomAdvMenuStyler read FAdvMenuStyler write SetAdvMenuStyler; // PropID: 0
    {========== AdvGlowButton ===========}
    property GlowButtonAppearance: TGlowButtonAppearance read FGlowButtonAppearance write SetGlowButtonAppearance; // PropID 7
    property CompactGlowButtonAppearance: TGlowButtonAppearance read FCompactGlowButtonAppearance write SetCompactGlowButtonAppearance; //propID 7
    property CaptionAppearance: TCaptionAppearance read FCaptionAppearance write SetCaptionAppearance;
    property SystemFont: boolean read FSystemFont write SetSystemFont default true;
  end;

  TOnDeleteItemEvent = procedure(Sender: TObject; Index: integer) of object;

  TRowCollectionItem = class(TCollectionItem)
  private
    //FHeight: integer;
    FToolBarList: TDbgList;
    FRowRect: TRect;
    function GetHeight: integer;
    function GetRowRect: TRect;
  protected
    function GetSpace(FirstAdvToolBar, SecondAdvToolBar: TAdvCustomToolBar): integer; // return space other than offset
    procedure SetRowRect(R: TRect);
    property ToolBarList: TDbgList read FToolBarList;
  public
    constructor Create(Collection: TCollection); override;
    destructor Destroy; override;
    procedure ArrangeToolBars;

    function IsAllowed(aAdvToolBar: TAdvCustomToolBar): Boolean;
    function AddToolBar(aAdvToolBar: TAdvCustomToolBar): integer;
    procedure RemoveToolBar(aAdvToolBar: TAdvCustomToolBar; DeleteIfEmpty: Boolean = True);
    procedure SetToolBarLeftAndWidth(aAdvToolBar: TAdvCustomToolBar; var ALeft, AWidth: integer);
    procedure SetToolBarTopAndHeight(aAdvToolBar: TAdvCustomToolBar; var ATop, AHeight: integer);
    property Height: integer read GetHeight;
    property RowRect: TRect read GetRowRect;
  end;

  TRowCollection = class(TCollection)
  private
    FOwner: TAdvDockPanel;
    {$IFNDEF DELPHI6_LVL}
    FMyOwner: TPersistent;
    {$ENDIF}
    FOnChange: TNotifyEvent;
    FOnDeleteItem: TOnDeleteItemEvent;
    FOffSetY: Integer;
    FOffSetX: Integer;
    procedure SetParentSize;
    function GetItem(Index: Integer): TRowCollectionItem;
    procedure SetItem(Index: Integer; const Value: TRowCollectionItem);
  protected
    procedure DeleteMeIfEmpty(AItem: TRowCollectionItem);
    procedure SetRowsPosition;
    procedure SetToolBarFullSize(aAdvToolBar: TAdvCustomToolBar);
    procedure UpdateToolBarVisibility(aAdvToolBar: TAdvCustomToolBar);
    procedure ReArrangeAllToolBars; // Simple remove space between Toolbars
    property OffSetX: integer read FOffSetX default 2;
    property OffSetY: integer read FOffSetY default 1;
  public
    constructor Create(AOwner: TAdvDockPanel);
    property Items[Index: Integer]: TRowCollectionItem read GetItem write SetItem; default;
    function Add: TRowCollectionItem;
    function Insert(Index: Integer): TRowCollectionItem;
    function GetOwner: TPersistent; override;
    {$IFNDEF DELPHI6_LVL}
    property Owner: TPersistent read FMyOwner;
    {$ENDIF}
    function IsToolBarAlreadyAdded(aAdvToolBar: TAdvCustomToolBar): Integer;
    procedure SetToolBarTopAndHeight(aAdvToolBar: TAdvCustomToolBar; var ATop, AHeight: integer);
    procedure SetToolBarLeftAndWidth(aAdvToolBar: TAdvCustomToolBar; var ALeft, AWidth: integer);
    procedure MoveToolBarToRow(aAdvToolBar: TAdvCustomToolBar; ARowIndex: integer);
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property OnDeleteItem: TOnDeleteItemEvent read FOnDeleteItem write FOnDeleteItem;
  end;

  TPersistenceLocation = (plRegistry, plIniFile);
  
  TPersistence = class(TPersistent)
  private
    FOwner: TComponent;
    FKey : string;
    FSection : string;
    FLocation: TPersistenceLocation;
    FEnabled: Boolean;
    FOnChange: TNotifyEvent;
    procedure SetEnabled(const Value: Boolean);
    procedure SetKey(const Value: string);
    procedure SetLocation(const Value: TPersistenceLocation);
    procedure SetSection(const Value: string);
  protected
    procedure Change;
  public
    constructor Create(AOwner:TComponent);
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property Location: TPersistenceLocation read FLocation write SetLocation;
    property Key: string read FKey write SetKey;
    property Section: string read FSection write SetSection;
    property Enabled: Boolean read FEnabled write SetEnabled;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;

  TAdvDockPanel = class(TCustomControl)
  private
    FInternalToolBarStyler: {TAdvToolBarStyler;//} TCustomAdvToolBarStyler;
    FToolBarStyler: TCustomAdvToolBarStyler;
    FCurrentToolBarStyler: TCustomAdvToolBarStyler;
    FDockAlign: TDockAlign;
    FRows: TRowCollection;
    FOffSetY: integer;
    FOffSetX: integer;
    FToolBars: TDbgList;
    FHiddenToolBars: TDbgList;
    FMyImage: TBitMap;
    FPersistence: TPersistence;
    FMinimumSize: Integer;
    FLockHeight: Boolean;
    FPropertiesLoaded: Boolean;
    FUseRunTimeHeight: Boolean;
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
    procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED;
    procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED;
    procedure OnPersistenceChange(Sender: TObject);
    procedure SetToolBarStyler(const Value: TCustomAdvToolBarStyler);
    function GetAlign: TDockAlign;
    procedure SetAlign(const Value: TDockAlign);
    function GetAdvToolBarCount: integer;
    function GetAdvToolBars(index: integer): TAdvCustomToolBar;
    function GetRowCount: integer;
    procedure SetPersistence(const Value: TPersistence);
    function GetVersion: string;
    procedure SetVersion(const Value: string);
    procedure SetMinimumSize(const Value: Integer);
    function GetPopupMenuEx: TPopupMenu;
    procedure SetPopupMenuEx(const Value: TPopupMenu);
    procedure SetLockHeight(const Value: Boolean);
    procedure SetUseRunTimeHeight(const Value: Boolean);
  protected
    procedure UpdateMe(PropID: integer);
    procedure AlignControls(AControl: TControl; var ARect: TRect); override;
    procedure CreateWnd; override;
    procedure Loaded; override;
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure SetParent(AParent: TWinControl); override;
    procedure Paint; override;
    function GetMyImage: TBitMap;

    function IsAllowedInAnyRow(aAdvToolBar: TAdvCustomToolBar): Integer;

    function AddToolBar(aAdvToolBar: TAdvCustomToolBar): integer;
    procedure RemoveToolBar(aAdvToolBar: TAdvCustomToolBar);
    procedure UpdateToolBarVisibility(aAdvToolBar: TAdvCustomToolBar);
    procedure SetToolBarFullSize(aAdvToolBar: TAdvCustomToolBar);
    procedure SetToolBarBounds(aAdvToolBar: TAdvCustomToolBar; var ALeft, ATop, AWidth, AHeight: Integer);

    property Rows: TRowCollection read FRows;
    property OffSetX: integer read FOffSetX default 1;
    property OffSetY: integer read FOffSetY default 0;

    property ToolBars: TDbgList read FToolBars;
  public
    constructor Create(AOwner: TComponent); override;
    procedure CreateParams(var Params: TCreateParams); override;
    destructor Destroy; override;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;

    procedure SaveToolBarsPosition;
    procedure LoadToolBarsPosition;

    function GetVersionNr: integer;

    procedure ArrangeToolBars;
    property RowCount: integer read GetRowCount;
    property AdvToolBarCount: integer read GetAdvToolBarCount;
    property AdvToolBars[index: integer]: TAdvCustomToolBar read GetAdvToolBars;
  published
    property Align: TDockAlign read GetAlign write SetAlign default daTop;
    property MinimumSize: Integer read FMinimumSize write SetMinimumSize;
    property LockHeight: Boolean read FLockHeight write SetLockHeight;
    property Persistence: TPersistence read FPersistence write SetPersistence;
    //property PopupMenu;
    property PopupMenu: TPopupMenu read GetPopupMenuEx write SetPopupMenuEx;
    property ToolBarStyler: TCustomAdvToolBarStyler read FToolBarStyler write SetToolBarStyler;
    property UseRunTimeHeight: Boolean read FUseRunTimeHeight write SetUseRunTimeHeight;
    property Version: string read GetVersion write SetVersion;
    property Visible;
  end;

  TAdvCustomToolBarControl = class(TGraphicControl)
  private
    FAdvToolBar: TAdvCustomToolBar;
    FPosition: TDockAlign;
    FAdvQuickAccessToolBar: TAdvQuickAccessToolBar;
    procedure SetPosition(const Value: TDockAlign);
    procedure SetAdvQuickAccessToolBar(const Value: TAdvQuickAccessToolBar);
  protected
    procedure ReadState(Reader: TReader); override;
    procedure SetAdvToolBar(const Value: TAdvCustomToolBar); virtual;

    property Position: TDockAlign read FPosition write SetPosition;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    property AdvToolBar: TAdvCustomToolBar read FAdvToolBar write SetAdvToolBar;
    property AdvQuickAccessToolBar: TAdvQuickAccessToolBar read FAdvQuickAccessToolBar write SetAdvQuickAccessToolBar;
  end;

  TAdvToolButtonStyle = (tasButton, tasCheck);
  TAdvButtonState = (absUp, absDisabled, absDown, absDropDown, absExclusive);

{$IFDEF DELPHI6_LVL}
  TAdvToolBarButtonActionLink = class(TControlActionLink)
  protected
    FClient: TAdvCustomToolBarButton;
    procedure AssignClient(AClient: TObject); override;
    function IsCheckedLinked: Boolean; override;
    function IsGroupIndexLinked: Boolean; override;
    procedure SetGroupIndex(Value: Integer); override;
    procedure SetChecked(Value: Boolean); override;
  end;
{$ENDIF}

  TAdvToolBarButtonDrawPosition = class(TPersistent)
  private
    FEnabled: Boolean;
    FTextX: Integer;
    FTextY: Integer;
    FImageX: Integer;
    FImageY: Integer;
    FOnChange: TNotifyEvent;
    procedure SetEnabled(const Value: Boolean);
    procedure SetImageX(const Value: integer);
    procedure SetImageY(const Value: Integer);
    procedure SetTextX(const Value: integer);
    procedure SetTextY(const Value: integer);
  protected
    procedure Changed;
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
  published
    property Enabled: Boolean read FEnabled write SetEnabled default False;
    property TextX: integer read FTextX write SetTextX default 0;
    property TextY: integer read FTextY write SetTextY default 0;
    property ImageX: integer read FImageX write SetImageX default 0;
    property ImageY: Integer read FImageY write SetImageY default 0;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;


  TAdvCustomToolBarButton = class(TAdvCustomToolBarControl)
  private
    FGroupIndex: Integer;
    FGlyph: TBitmap;
    FDown: Boolean;
    //FDragging: Boolean;
    FAllowAllUp: Boolean;
    //FLayout: TButtonLayout;
    FSpacing: Integer;
    FTransparent: Boolean;
    //FMargin: Integer;
    FOffSet: integer;
    FFlat: Boolean;
    FMouseInControl: Boolean;
    FHot: Boolean;
    FMenuSel: Boolean;
    FGlyphDisabled: TBitmap;
    FGlyphHot: TBitmap;
    FGlyphDown: TBitmap;
    FGlyphChecked: TBitmap;
    FGlyphShade: TBitmap;
    FShaded: Boolean;
    FOnMouseLeave: TNotifyEvent;
    FOnMouseEnter: TNotifyEvent;
    FStyle: TAdvToolButtonStyle;
    //FLook: Integer;
    //FRounded: Boolean;
    FDropDownButton: Boolean;
    FAutoThemeAdapt: Boolean;
    FOnDropDown: TNotifyEvent;
    FDropDownMenu: TAdvPopupMenu;
    FRounded: Boolean;
    FParentStyler: Boolean;
    FState: TAdvButtonState;
    FGlyphPosition: TGlyphPosition;
    FMouseDownInControl: Boolean;
    FDropDownSectWidth: integer;
    FGrouped: Boolean;
    FMenuItem: TMenuItem;
    FImageIndex: integer;
    FShadedForGlyph: Boolean;
    FDragging: Boolean;
    FAppearance: TButtonAppearance;
    FShowCaption: Boolean;
    FPropHot: Boolean;
    FPicture: TPicture;
    FPictureDisabled: TPicture;
    FUnHotTimer: TTimer;
    FDrawPosition: TAdvToolBarButtonDrawPosition;
    FInitialDown: Boolean;
    FInternalTag: Integer;   // 1: MergedMenu
    FOfficeHint: TAdvHintInfo;
    FDropDownSplit: boolean;
    FForceImageIndex: Boolean;
    FInternalClick: Boolean;
    FMenuBeingClosed: Boolean;
    FMenuDisplayed: Boolean;
{$IFNDEF DELPHI6_LVL}
    FAutoSize: Boolean;
{$ENDIF}
    procedure UnHotTimerOnTime(Sender: TObject);
    procedure GlyphChanged(Sender: TObject);
    procedure UpdateExclusive;
    //procedure SetLayout(Value: TButtonLayout);
    procedure SetSpacing(Value: Integer);
    //procedure SetMargin(Value: Integer);
    procedure UpdateTracking;

    procedure PopupBtnDown;
    procedure ButtonDown;

    procedure WMLButtonDblClk(var Message: TWMLButtonDown); message WM_LBUTTONDBLCLK;
    procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
    procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
    procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
    procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
    procedure CMSysColorChange(var Message: TMessage); message CM_SYSCOLORCHANGE;
    procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
{$IFNDEF TMSDOTNET}
    procedure CMButtonPressed(var Message: TMessage); message CM_BUTTONPRESSED;
{$ENDIF}
    procedure SetGlyph(Value: TBitmap);
    procedure SetGlyphDisabled(const Value: TBitmap);
    procedure SetGlyphDown(const Value: TBitmap);
    procedure SetGlyphHot(const Value: TBitmap);
    procedure GenerateShade;
    procedure SetShaded(const Value: Boolean);
    procedure SetFlat(Value: Boolean);
    procedure SetDown(Value: Boolean);
    procedure SetAllowAllUp(Value: Boolean);
    procedure SetGroupIndex(Value: Integer);
    procedure SetStyle(const Value: TAdvToolButtonStyle);
    procedure SetDropDownButton(const Value: Boolean);
    procedure SetGlyphPosition(const Value: TGlyphPosition);
    procedure SetParentStyler(const Value: Boolean);
    //procedure SetRounded(const Value: Boolean);
    procedure SetState(const Value: TAdvButtonState);
    procedure SetTransparent(const Value: Boolean);
    procedure SetRounded(const Value: Boolean);
    //procedure SetAdvToolBar(aAdvToolBar: TAdvCustomToolBar);
    procedure SetGlyphChecked(const Value: TBitmap);
    function GetIndex: Integer;
    procedure SetGrouped(const Value: Boolean);
    procedure SetMenuItem(const Value: TMenuItem);
    procedure SetImageIndex(const Value: integer);
    procedure SetAppearance(const Value: TButtonAppearance);
    procedure SetShowCaption(const Value: Boolean);
    function GetAutoSize: Boolean;
    function GetVersion: string;
    procedure SetVersion(const Value: string);
    function GetHot: Boolean;
    procedure SetHot(const Value: Boolean);
    procedure SetPicture(const Value: TPicture);
    procedure SetPictureDisabled(const Value: TPicture);
    procedure SetDrawPosition(const Value: TAdvToolBarButtonDrawPosition);
    procedure PositionChanged(Sender: TObject);
    procedure SetOfficeHint(const Value: TAdvHintInfo);
    procedure SetForceImageIndex(const Value: Boolean);
    //procedure SetLook(const Value: Integer);
  protected
    FToolBarCreated: Boolean;
    FCommandID: Integer;
    FCustomizerCreated: Boolean;
    procedure SetParent(AParent: TWinControl); override;
{$IFDEF DELPHI6_LVL}
    function GetActionLinkClass: TControlActionLinkClass; override;
    procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override;
{$ENDIF}
    procedure Loaded; override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure DrawGlyphAndCaption(ACanvas: TCanvas; R: TRect; TxtClr: TColor; aGlyph: TBitMap); virtual;
    procedure DrawButton(ACanvas: TCanvas); virtual;
    procedure Paint; override;
    property MouseInControl: Boolean read FMouseInControl;
    procedure WndProc(var Message: TMessage); override;
    procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
{$IFNDEF DELPHI6_LVL}
    procedure SetAutoSize(Value: Boolean);
{$ELSE}
    procedure SetAutoSize(Value: Boolean); override;
{$ENDIF}
    procedure AdjustSize; override;
    procedure OnAppearanceChange(Sender: TObject);
    procedure ThemeAdapt;
    procedure SetAutoThemeAdapt(const Value: Boolean);

    procedure InvalidateMe;
    procedure OnDropDownHide;
    function IsMenuButton: Boolean; virtual;
    //procedure SetAdvToolBar(aAdvToolBar: TAdvCustomToolBar);
    property State: TAdvButtonState read FState write SetState;
    //property AdvToolBar: TAdvCustomToolBar read FAdvToolBar write SetAdvToolBar;
    property ForceImageIndex: Boolean read FForceImageIndex write SetForceImageIndex;

    // published
    property Action;
    property AllowAllUp: Boolean read FAllowAllUp write SetAllowAllUp default False;
    property Anchors;
    property AutoSize: Boolean read GetAutoSize write SetAutoSize default True;
    property AutoThemeAdapt: Boolean read FAutoThemeAdapt write SetAutoThemeAdapt;
    property BiDiMode;

    property Appearance: TButtonAppearance read FAppearance write SetAppearance;
    property GlyphPosition: TGlyphPosition read FGlyphPosition write SetGlyphPosition default gpLeft;

    property Constraints;
    property DrawPosition: TAdvToolBarButtonDrawPosition read FDrawPosition write SetDrawPosition;
    property Grouped: Boolean read FGrouped write SetGrouped default False;
    property GroupIndex: Integer read FGroupIndex write SetGroupIndex default 0;
    property Down: Boolean read FDown write SetDown default False;
    property DropDownSplit: boolean read FDropDownSplit write FDropDownSplit default true;
    property DropDownButton: Boolean read FDropDownButton write SetDropDownButton default False;
    property DropDownMenu: TAdvPopupMenu read FDropDownMenu write FDropDownMenu;
    property Caption;
    property Enabled;
    property Flat: Boolean read FFlat write SetFlat default True;
    property Font;
    property Glyph: TBitmap read FGlyph write SetGlyph;
    property GlyphHot: TBitmap read FGlyphHot write SetGlyphHot;
    property GlyphDown: TBitmap read FGlyphDown write SetGlyphDown;
    property GlyphDisabled: TBitmap read FGlyphDisabled write SetGlyphDisabled;
    property GlyphChecked: TBitmap read FGlyphChecked write SetGlyphChecked;
    property Hot: Boolean read GetHot write SetHot default false;

    property ImageIndex: integer read FImageIndex write SetImageIndex default -1;
    //property Layout: TButtonLayout read FLayout write SetLayout default blGlyphLeft;
    //property Margin: Integer read FMargin write SetMargin default -1;
    property MenuItem: TMenuItem read FMenuItem write SetMenuItem;
    property Picture: TPicture read FPicture write SetPicture;
    property PictureDisabled: TPicture read FPictureDisabled write SetPictureDisabled;

    property ParentFont;
    property ParentShowHint;
    property ParentBiDiMode;
    property PopupMenu;
    property ParentStyler: Boolean read FParentStyler write SetParentStyler default True;
    property Rounded: Boolean read FRounded write SetRounded default False;
    property Shaded: Boolean read FShaded write SetShaded default True;
    property ShowCaption: Boolean read FShowCaption write SetShowCaption default False;
    property ShowHint;
    property OfficeHint: TAdvHintInfo read FOfficeHint write SetOfficeHint;
    property Spacing: Integer read FSpacing write SetSpacing default 4;
    property Style: TAdvToolButtonStyle read FStyle write SetStyle default tasButton;
    property Transparent: Boolean read FTransparent write SetTransparent;
    property Version: string read GetVersion write SetVersion;
    property Visible;
    property OnClick;
    property OnDblClick;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
    property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
    property OnDropDown: TNotifyEvent read FOnDropDown write FOnDropDown;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Click; override;
    procedure DoDropDown; // State Change to DropDown
    
{$IFDEF TMSDOTNET}
    procedure ButtonPressed(Group: Integer; Button: TAdvCustomToolBarButton);
{$ENDIF}
    function CheckMenuDropdown: Boolean; dynamic;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
    property Index: Integer read GetIndex;
    function GetVersionNr: Integer; virtual;
  published
  end;

  TAdvToolBarButton = class(TAdvCustomToolBarButton)
  public
  published
    property Action;
    property AllowAllUp;
    //property Anchors;
    property AutoSize;
    //property BiDiMode;
    property Appearance;
    property GlyphPosition;

    property Constraints;
    property GroupIndex;
    property Down;
    property DropDownButton;
    property DropDownMenu;
    property DropDownSplit;
    property Caption;
    property Enabled;
    property DrawPosition;
    //property Flat: Boolean read FFlat write SetFlat default True;
    property Font;
    property Glyph;
    property GlyphHot;
    property GlyphDown;
    property GlyphDisabled;
    property GlyphChecked;
    property ImageIndex;
    property Picture;
    property PictureDisabled;
    property ParentFont;
    property ParentShowHint;
    property ParentBiDiMode;
    property PopupMenu;
    property ParentStyler;
    property Position;
    //property Rounded: Boolean read FRounded write SetRounded default False;
    property Shaded;
    property ShowCaption;
    property ShowHint;
    property OfficeHint;
    //property Spacing: Integer read FSpacing write SetSpacing default 4;
    property Style;
    //property Transparent: Boolean read FTransparent write SetTransparent;
    property Version;
    property Visible;
    property OnClick;
    property OnDblClick;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnMouseEnter;
    property OnMouseLeave;
    property OnDropDown;
  end;

  TAdvToolBarMenuButton = class(TAdvCustomToolBarButton)
  private
  protected
    function IsMenuButton: Boolean; override;
    procedure DrawButton(aCanvas: TCanvas); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    property Hot;
  published
    property Action;
    //property AllowAllUp: Boolean read FAllowAllUp write SetAllowAllUp default False;
    //property Anchors;
    //property BiDiMode;
    property Appearance;
    property GlyphPosition;

    property Constraints;
    //property GroupIndex: Integer read FGroupIndex write SetGroupIndex default 0;
    //property Down: Boolean read FDown write SetDown default False;
    property DropDownButton;
    property DropDownMenu;
    property DropDownSplit;
    property Caption;
    property Enabled;
    //property Flat: Boolean read FFlat write SetFlat default True;
    property Font;
    property Glyph;
    property GlyphHot;
    property GlyphDown;
    property GlyphDisabled;
    property GlyphChecked;
    property ImageIndex;
    property Picture;
    //property ParentFont;
    //property ParentShowHint;
    //property ParentBiDiMode;
    //property PopupMenu;
    property ParentStyler;
    property Position;
    //property Rounded: Boolean read FRounded write SetRounded default False;
    property Shaded;
    property ShowHint;
    property OfficeHint;
    property ShowCaption;    
    //property Spacing: Integer read FSpacing write SetSpacing default 4;
    //property Transparent: Boolean read FTransparent write SetTransparent;
    property Version;
    property Visible;
    property OnClick;
    //property OnDblClick;
    //property OnMouseDown;
    //property OnMouseMove;
    //property OnMouseUp;
    property OnMouseEnter;
    property OnMouseLeave;
    property OnDropDown;
  end;

  TAdvSeparatorStyle = (ssOffice2003, ssBlank);
  TAdvToolBarSeparator = class(TAdvCustomToolBarControl)
  private
    FSeparatorStyle: TAdvSeparatorStyle;
    FLineColor: TColor;
    procedure SetSeparatorStyle(const Value: TAdvSeparatorStyle);
    procedure SetLineColor(const Value: TColor);
  protected
    procedure Paint; override;
    procedure AdjustSize; override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property SeparatorStyle: TAdvSeparatorStyle read FSeparatorStyle write SetSeparatorStyle default ssOffice2003;
    property LineColor: TColor read FLineColor write SetLineColor;
  end;

  //---- DB aware version
  TDBButtonType = (dbtCustom, dbtFirst, dbtPrior, dbtNext, dbtLast, dbtInsert, dbtAppend,
                   dbtDelete, dbtEdit, dbtPost, dbtCancel, dbtRefresh);

  TDBBDisableControl = (drBOF, drEOF, drReadonly, drNotEditing, drEditing, drEmpty, drEvent);
  TDBBDisableControls = set of TDBBDisableControl;

  TBeforeActionEvent = procedure (Sender: TObject; var DoAction: Boolean) of object;
  TAfterActionEvent = procedure (Sender: TObject; var ShowException: Boolean) of object;
  TGetConfirmEvent = procedure (Sender: TObject; var Question: string; var Buttons: TMsgDlgButtons; var HelpCtx: Longint) of object;
  TGetEnabledEvent = procedure (Sender: TObject; var Enabled: Boolean) of object;

  {$IFNDEF TMS_STD}
  TDBATBButtonDataLink = class(TDataLink)
  private
    FOnEditingChanged: TNotifyEvent;
    FOnDataSetChanged: TNotifyEvent;
    FOnActiveChanged: TNotifyEvent;
  protected
    procedure EditingChanged; override;
    procedure DataSetChanged; override;
    procedure ActiveChanged; override;
  public
    constructor Create;
    property OnEditingChanged: TNotifyEvent
      read FOnEditingChanged write FOnEditingChanged;
    property OnDataSetChanged: TNotifyEvent
      read FOnDataSetChanged write FOnDataSetChanged;
    property OnActiveChanged: TNotifyEvent
      read FOnActiveChanged write FOnActiveChanged;
  end;

  TDBAdvToolBarButton = class(TAdvCustomToolBarButton)
  private
    FDataLink: TDBATBButtonDataLink;
    FAutoDisable: Boolean;
    FDisableControls: TDBBDisableControls;
    FOnAfterAction: TAfterActionEvent;
    FOnBeforeAction: TBeforeActionEvent;
    FDBButtonType: TDBButtonType;
    FOnGetConfirm: TGetConfirmEvent;
    FOnGetEnabled: TGetEnabledEvent;
    FOnEnabledChanged: TNotifyEvent;
    FConfirmAction: Boolean;
    FConfirmActionString: String;
    FInProcUpdateEnabled: Boolean;

    procedure CMEnabledChanged(var Message: TMessage);  message CM_ENABLEDCHANGED;
    procedure OnDataSetEvents(Sender: TObject);

    function GetDataSource: TDataSource;
    procedure SetDataSource(const Value: TDataSource);
    procedure SetDBButtonType(const Value: TDBButtonType);
    procedure SetConfirmActionString(const Value: String);
  protected
    procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
    procedure Loaded; override;
    procedure CalcDisableReasons;
    procedure DoBeforeAction(var DoAction: Boolean); virtual;
    procedure DoGetQuestion(var Question: string; var Buttons: TMsgDlgButtons; var HelpCtx: Longint); virtual;
    function DoConfirmAction: Boolean; virtual;
    procedure DoAction; virtual;
    procedure UpdateEnabled; virtual;
    procedure LoadGlyph; virtual;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Click; override;
  published
    property Action;
  //  property AllowAllUp;
    //property Anchors;
    property AutoSize;
    //property BiDiMode;
    property Appearance;
    property GlyphPosition;

    property Constraints;
  //  property GroupIndex;
  //  property Down;
  //  property DropDownButton;
  //  property DropDownMenu;

    property AutoDisable: Boolean read FAutoDisable write FAutoDisable;
    property ConfirmAction: Boolean read FConfirmAction write FConfirmAction;
    property ConfirmActionString: String read FConfirmActionString write SetConfirmActionString;
    property DataSource: TDataSource read GetDataSource write SetDataSource;
    property DBButtonType: TDBButtonType read FDBButtonType write SetDBButtonType;
    property DisableControl: TDBBDisableControls read FDisableControls write FDisableControls;

    property Caption;
    property Enabled;
    property DrawPosition;
    //property Flat: Boolean read FFlat write SetFlat default True;
    property Font;
    property Glyph;
    property GlyphHot;
    property GlyphDown;
    property GlyphDisabled;
    //property GlyphChecked;
    property ImageIndex;
    property Picture;
    property PictureDisabled;
    property ParentFont;
    property ParentShowHint;
    property ParentBiDiMode;
    property PopupMenu;
    property ParentStyler;
    property Position;
    //property Rounded: Boolean read FRounded write SetRounded default False;
    property Shaded;
    property ShowCaption;
    property ShowHint;
    property OfficeHint;
    //property Spacing: Integer read FSpacing write SetSpacing default 4;
    //property Style;
    //property Transparent: Boolean read FTransparent write SetTransparent;
    property Version;
    property Visible;
    property OnClick;
    property OnDblClick;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnMouseEnter;
    property OnMouseLeave;
  //  property OnDropDown;

    property OnBeforeAction: TBeforeActionEvent read FOnBeforeAction write FOnBeforeAction;
    property OnAfterAction: TAfterActionEvent read FOnAfterAction write FOnAfterAction;
    property OnGetConfirm: TGetConfirmEvent read FOnGetConfirm write FOnGetConfirm;
    property OnGetEnabled: TGetEnabledEvent read FOnGetEnabled write FOnGetEnabled;
    property OnEnabledChanged: TNotifyEvent read FOnEnabledChanged write FOnEnabledChanged;
  end;
  {$ENDIF}


  TDockedEvent = procedure(Sender: TObject; AdvDockPanel: TAdvDockPanel) of object;

  TOptionEvent = procedure(Sender: TObject; ClientPoint, ScreenPoint: TPoint) of object;


  TAdvCustomToolBar = class(TCustomControl)
  private
    FAntiAlias: TAntiAlias;
    FATBControls: TDbgList;
    FRUControls: TDbgList;
    FLUHidedControls: TDbgList;
    FInternalToolBarStyler: TCustomAdvToolBarStyler;
    FToolBarStyler: TCustomAdvToolBarStyler;
    FCurrentToolBarStyler: TCustomAdvToolBarStyler;
    FParentStyler: Boolean;
    FDragGripWidth: integer;
    FPopupIndicatorWidth: integer;
    FCurrentDock: TAdvDockPanel;
    FLastDock: TAdvDockPanel;
    FPosition: TDockAlign;
    FOldCursor: TCursor;
    FDraging: Boolean;
    FOldMouseX: integer;
    FOldMouseY: integer;
    FHotPopupIndicator: Boolean;
    FDownPopupIndicator: Boolean;
    FRow: integer;
    FToolBarState: TToolBarState;
    FAllowBoundChange: boolean;
    FFullSize: Boolean;
    FDockableTo: TDockableTo;
    FDockList: TDbgList;
    FFloatingWindow: TFloatingWindow;
    FOwner: TComponent;
    FCaption: string;
    FWideCaption: widestring;
    FCaptionFont: TFont;
    FShowOptionIndicator: Boolean;
    FShowPopupIndicator: Boolean;
    FShowClose: Boolean;
    FCaptionHeight: integer;
    FHotCustomizedBtn: Boolean;
    FDownCustomizedBtn: Boolean;
    FHotCloseBtn: Boolean;
    FDownCloseBtn: Boolean;
    FImages: TCustomImageList;
    FMenu: TMainMenu;
    FMergedMenu: TMainMenu;
    FTimerID: integer;
    FTempMenu: TAdvPopupMenu;
    FInMenuLoop: Boolean;
    FMenuResult: Boolean;
    FCaptureChangeCancels: Boolean;
    FMenuDropped: Boolean;
    FMenuButton: TAdvCustomToolBarButton;
    FLastMenuButton: TAdvCustomToolBarButton;
    FButtonMenu: TMenuItem;
    FInternalControlPositioning: Boolean;
    FAutoRUL: Boolean;
    FFloatingRows: integer;
    FSizeAtDock: integer;
    FMinLength: integer;
    FMaxLength: integer;
    FOldState: TToolBarState;
    FShowRightHandle: Boolean;
    FOnClose: TNotifyEvent;
    FOnOptionClick: TOptionEvent;
    FOnDocked: TDockedEvent;
    FOnUnDocked: TNotifyEvent;
    FPersistence: TPersistence;
    FPersistSettingLoaded: Boolean;
    FMenuImages: TCustomImageList;
    FTempMenuItemCount: integer;
    FHotButton: TAdvCustomToolBarButton;
    FMenuFocused: Boolean;
    FOptionMenu: TPopupMenu;
    FAllowFloating: Boolean;
    FLocked: Boolean;
    FOptionWindow: TOptionSelectorWindow;
    FOptionWindowPanel: TControlSelectorPanel;
    FInternalControlUpdation: Boolean;
    FAutoOptionMenu: Boolean;
    FHintOptionButton: string;
    FHintCloseButton: string;
    FTextAutoOptionMenu: String;
    FTextOptionMenu: String;
    FAutoArrangeButtons: Boolean;
    FParentForm: TCustomForm;
    FAutoHiding: Boolean;
    FDisabledImages: TCustomImageList;
    FAutoMDIButtons: Boolean;
    FMDIButtonsVisible: Boolean;
    FMDIDownCloseBtn: Boolean;
    FMDIHotCloseBtn: Boolean;
    FMDIDownMaxBtn: Boolean;
    FMDIHotMaxBtn: Boolean;
    FMDIDownMinBtn: Boolean;
    FMDIHotMinBtn: Boolean;
    FMDIChildForm: TCustomForm;
    FMenuItemTimer: TTimer;
    FNextMenuHotButton: TAdvCustomToolBarButton;
    FUpdatingControls: Boolean;
    FCustomizer: TAdvToolBarCustomizer;
    FAutoDockOnClose: Boolean;
    FShowCaption: Boolean;
    FCaptionPosition: TCaptionPosition;
    FCaptionAlignment: TAlignment;
    FMDIChildMenuSL: TStringList;
    FMDIChildMenuList: TList;
    FTimer: TTimer;
    FHot: Boolean;
    FTimeInc: Integer;
    FStepHover: Integer;
    FGlowState: TGlowState;
    FAutoSize: Boolean;
    FCapOptIndicatorHot: Boolean;
    FCapOptIndicatorDown: Boolean;
    FIOptionDisabledPicture: TGDIPPicture;
    FIOptionPicture: TGDIPPicture;
    FAutoPositionControls: Boolean;
    FOptionTimer: TTimer;
    FOptionStepHover: Integer;
    FOptionStepPush: Integer;
    FOptionTimeInc: Integer;
    FOptionGlowState: TGlowState;
    FCompactCaption: string;
    FICompactPicture: TGDIPPicture;
    FCompact: Boolean;
    FCompactMode: Boolean;
    FSelfClone: TAdvCustomToolBar;
    FCompactWindow: TCompactWindow;
    FCompactMinWidth: Integer;
    FCompactBtn: TAdvGlowButton;
    FOldAutoPosition: Boolean;
    FOldAutoArrangeButtons: Boolean;
    FOldAutoSize: Boolean;
    FOfficeHint: TAdvHintInfo;
    FActive: Boolean;
    FPropertiesLoaded: Boolean;
    FParentOptionPicture: Boolean;
    FCompactImageIndex: Integer;
    FUpdateCount: Integer;
    FSeqControlList: TDbgList;
    FCompactSmallest: Boolean;
    FWideCompactCaption: widestring;
    FDockMode: TDockMode;
    FOnCompactCloseQuery: TCloseQueryEvent;
    FDoCheckBoundChange: Boolean;
    FCompactShortCutHint: string;
    FCompactShortCutHintShowing: Boolean;
    FButtonRows: array[1..3] of Integer;   // Only for Run time OfficeRibbon, carries rows top
    FCompactChanging: Boolean;
    procedure TimerProc(Sender: TObject);
    procedure OptionTimerProc(Sender: TObject);
    procedure InvalidateCapOptionBtn;
    procedure InvalidateCaption;

    procedure MenuItemTimerOnTime(Sender: TObject);

    procedure InitializeOptionWindow;
    procedure ShowOptionWindow(X, Y: Integer; ForcePoint: Boolean=True);
    procedure HideOptionWindow;
    procedure OnOptionWindowHide(Sender: TObject);

    procedure DrawDragGrip;
    procedure DrawPopupIndicator;
    procedure DrawCustomizedBtn;
    procedure DrawCloseBtn;

    procedure DrawMDIButtons;
    function GetMDIMinBtnRect: TRect;
    function GetMDIMaxBtnRect: TRect;
    function GetMDICloseBtnRect: TRect;
    function PtOnMDIMin(P: TPoint): Boolean;
    function PtOnMDIMax(P: TPoint): Boolean;
    function PtOnMDIClose(P: TPoint): Boolean;
    function GetOptionIndicatorRect: TRect;
    procedure MDICloseBtnClick;
    procedure MDIMaxBtnClick;
    procedure MDIMinBtnClick;

    function PtOnDragGrip(P: TPoint): Boolean;
    function PtOnPopupIndicator(P: TPoint): Boolean;
    function PtOnGripCaption(P: TPoint): Boolean;
    function PtOnCustomizedBtn(P: TPoint): Boolean;
    function PtOnCloseBtn(P: TPoint): Boolean;

    function GetMyClientRect: TRect;
    function GetCaptionRect: TRect;
    function FWCustomizedBtnRect: TRect; // FW for Floating Window
    function FWCloseBtnRect: TRect;

    procedure CloseBtnClick;
    procedure OptionIndicatorClick;
    procedure CapOptionIndicatorClick;

    procedure UpdateSize;

    function GetMenuItemCount: integer;
    procedure OnMainMenuChange(Sender: TObject; Source: TMenuItem; Rebuild: Boolean);

    procedure OnMDIChildMenuClick(Sender: TObject);

    procedure BuildSequenceControlList;
    procedure GetSequenceControlList(aList: TDbgList; CheckVisibility: Boolean = True);
    procedure CNDropDownClosed(var Message: TMessage); message CN_DROPDOWNCLOSED;

    procedure OnOptionPictureChanged(Sender: TObject);

    procedure OnCompactPictureChanged(Sender: TObject);
    procedure OnCompactBtnDropDown(Sender: TObject);

    procedure OnGlowButtonKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure OnGlowButtonClick(Sender: TObject);
    procedure OnSetGlowButtonSize(Sender: TObject; var W, H: Integer);
    procedure OnGetGlowButtonShortCutHintPos(Sender: TObject; ButtonSizeState: TButtonSizeState; var ShortCutHintPosition: TShortCutHintPos);

    procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED;
    procedure WMTimer(var Message: TWMTimer); message WM_TIMER;
    procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
    procedure WMCaptureChanged(var Message: TMessage); message WM_CAPTURECHANGED;
    procedure CNChar(var Message: TWMChar); message CN_CHAR;
    procedure CNSysKeyDown(var Message: TWMSysKeyDown); message CN_SYSKEYDOWN;
    procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND;
    procedure WMGetDlgCode(var Message: TMessage); message WM_GETDLGCODE;
    procedure CMControlChange(var Message: TCMControlChange); message CM_CONTROLCHANGE;
    procedure CMControlListChange(var Message: TCMControlListChange); message CM_CONTROLLISTCHANGE;
    procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
    procedure CMHintShow(var Msg: TCMHintShow); message CM_HINTSHOW;
    procedure WMEraseBkGnd(var Msg: TMessage); message WM_ERASEBKGND;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
    procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY;
    procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED;
    procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
    procedure SetToolBarStyler(const Value: TCustomAdvToolBarStyler);
    procedure SetParentStyler(const Value: Boolean);
    procedure SetDragGripWidth(const Value: integer);
    procedure SetPopupIndicatorWidth(const Value: integer);
    procedure SetPosition(const Value: TDockAlign);
    procedure SetRow(const Value: integer);
    procedure SetAllowBoundChange(const Value: boolean);
    procedure SetFullSize(const Value: Boolean);
    procedure SetDockableTo(const Value: TDockableTo);
    procedure SetCaption(const Value: string);
    procedure SetWideCaption(const Value: widestring);
    procedure SetCaptionFont(const Value: TFont);
    procedure SetShowOptionIndicator(const Value: Boolean);
    procedure SetShowPopupIndicator(const Value: Boolean);
    procedure SetShowClose(const Value: Boolean);
    procedure SetCaptionHeight(const Value: integer);
    procedure SetImages(const Value: TCustomImageList);
    procedure SetMenu(const Value: TMainMenu);
    procedure SetAutoRUL(const Value: Boolean);
    procedure SetFloatingRows(const Value: integer);
    procedure SetShowRightHandle(const Value: Boolean);
    procedure SetPersistence(const Value: TPersistence);
    function GetShowHint: Boolean;
    procedure SetShowHint(const Value: Boolean);
    function GetVersion: string;
    procedure SetVersion(const Value: string);
    procedure SetAllowFloating(const Value: Boolean);
    procedure SetLocked(const Value: Boolean);
    procedure SetAutoOptionMenu(const Value: Boolean);
    procedure SetAutoArrangeButtons(const Value: Boolean);
    procedure SetDisabledImages(const Value: TCustomImageList);
    function GetToolBarControlCount: Integer;
    function GetToolBarControls(index: Integer): TControl;
    procedure AddMergedMenuItems;
    procedure DeleteMergedMenuItems;
    procedure SetAutoMDIButtons(const Value: Boolean);
    procedure SetMDIButtonsVisible(const Value: Boolean);
    procedure SetCustomizer(const Value: TAdvToolBarCustomizer);
    procedure SetAutoDockOnClose(const Value: Boolean);
    procedure SetCaptionPosition(const Value: TCaptionPosition);
    procedure SetShowCaption(const Value: Boolean);
    procedure SetCaptionAlignment(const Value: TAlignment);
    procedure SetAutoSizeEx(const Value: Boolean);
    procedure SetOptionDisabledPicture(const Value: TGDIPPicture);
    procedure SetOptionPicture(const Value: TGDIPPicture);
    procedure SetAutoPositionControls(const Value: Boolean);
    procedure SetCompactCaption(const Value: string);
    procedure SetCompactPicture(const Value: TGDIPPicture);
    procedure SetCompactMode(const Value: Boolean);
    procedure SetOfficeHint(const Value: TAdvHintInfo);
    procedure SetAntiAlias(const Value: TAntiAlias);
    procedure SetParentOptionPicture(const Value: Boolean);
    procedure SetCompactImageIndex(const Value: Integer);
    function GetToolBarIndex: Integer;
    procedure SetToolBarIndex(const Value: Integer);
    function GetAdvDockPanel: TAdvDockPanel;
    procedure SetAdvDockPanel(const Value: TAdvDockPanel);
    procedure UpdateCompactButton;
    procedure UpdateButtonRowCount; // only for OfficeRibbon
  protected
    procedure AlignControls(AControl: TControl; var ARect: TRect); override;
    procedure Loaded; override;
    procedure Resize; override;
    procedure UpdateMe(PropID: integer);
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure SetParent(AParent: TWinControl); override;
    procedure WndProc(var Message: TMessage); override;
    procedure Paint; override;

    procedure SetControlsPosition(UpdateMySize: boolean = true);
    function AddAdvToolBarControl(aControl: TAdvCustomToolBarControl): integer;
    procedure InsertAdvToolBarControl(aControl: TAdvCustomToolBarControl; Index: integer);
    procedure RemoveAdvToolBarControl(aControl: TAdvCustomToolBarControl);
    function ButtonAtPos(X, Y: Integer): TAdvCustomToolBarButton;
    function GetMaxLength: Integer;
    procedure AdjustSizeOfAllButtons(MenuButtonsOnly: Boolean = False);
    function GetSizeAtDock(ForFloating: Boolean): Integer;
    procedure GetMaxControlSize(var W, H: Integer);
    procedure GetMaxExternalControlSize(var W, H: Integer);
    procedure GetMaxToolBarButtonSize(var W, H: Integer);

    procedure UpdateAllGlowButtons;
    procedure UpdateAllContainer;

    procedure InvalidateTransparentControls;

    function CanUnCompact: Boolean;
    procedure SetCompact(const Value: Boolean);
    procedure HideCompactWindow;

    function AnyDroppedDownButton: Boolean;

    procedure ShowShortCutHintOfButtons;
    procedure HideShortCutHintOfButtons;
    function HasShortCut(aShortCut: String; var VisibleHintCount: Integer): Boolean;

    function GetControlFromHandle(H: HWnd): TWinControl;
    function GetFirstTabControl(CheckCanFocus: Boolean): TWinControl;
    function GetLastTabControl(CheckCanFocus: Boolean): TWinControl;

    procedure InsertControl(Control: TControl);
    procedure RemoveControl(Control: TControl);
    function ControlIndex(OldIndex, ALeft, ATop: Integer): Integer;
    function ReorderControl(OldIndex, ALeft, ATop: Integer): Integer;
    procedure AdjustControl(Control: TControl);

    function CheckMenuDropdown(Button: TAdvCustomToolBarButton): Boolean; dynamic;
    procedure CancelMenu; dynamic;
    procedure ClearTempMenu;
    procedure ClickButton(Button: TAdvCustomToolBarButton; RealClick: Boolean = false); dynamic;
    function FindButtonFromAccel(Accel: Word): TAdvCustomToolBarButton;
    function TrackMenu(Button: TAdvCustomToolBarButton): Boolean; dynamic;
    procedure InitMenu(Button: TAdvCustomToolBarButton); dynamic;
    procedure UpdateButtonHot(Button: TAdvCustomToolBarButton);
    function SetButtonHot(Button: TAdvCustomToolBarButton): Boolean; overload;
    function SetButtonHot(ButtonNumber: Integer): Boolean; overload;

    procedure UpControlInRUL(aControl: TControl);
    procedure UpdateRULists;
    procedure UnHideAllControls;


    function GetFloatingWindowSizes(aRows: integer; var aHeight, aWidth: integer): Boolean;
    procedure GetFloatingSizes(var aHeight, aWidth: integer);
    function GetMaxFloatingRowCount: integer;
    property FloatingRows: integer read FFloatingRows write SetFloatingRows default 1;

    function AcceptableDockPanel(ADockPanel: TAdvDockPanel): Boolean;
    procedure BeginMove(Shift: TShiftState; X, Y: Integer);
    procedure Move(Shift: TShiftState; X, Y: Integer);
    procedure EndMove;
    procedure SetFloating(X: integer = 0; Y: integer = 0; ForcePoint: Boolean = false);
    function CanShrink: integer;
    function CanExpand: integer;
    property Customizer: TAdvToolBarCustomizer read FCustomizer write SetCustomizer;
    property AllowBoundChange: boolean read FAllowBoundChange write SetAllowBoundChange default false;
    property DragGripWidth: integer read FDragGripWidth write SetDragGripWidth default 7;
    property PopupIndicatorWidth: integer read FPopupIndicatorWidth write SetPopupIndicatorWidth default 14;
    //property MinLength: integer read FMinLength;
    property Row: integer read FRow write SetRow default -1;
    property ToolBarState: TToolBarState read FToolBarState;

    procedure OnCompactWindowHide(Sender: TObject);
    function GetCompactWidth: Integer;
    function GetInCompactWidth: Integer;
    procedure UpdateCompactWindow(UpdateSize: Boolean = false);
    property Compact: Boolean read FCompact write SetCompactMode;  // Can be set when parent = TAdvPage
    property IsCompact: Boolean read FCompact;
    function IsSmallestVariant: Boolean;
    function SetSmallerVariant(CanCompact: Boolean; var NewState: TButtonSizeState; RealSet: Boolean = True): Integer;
    function SmallerVariantDifference(CanCompact: Boolean; var NewState: TButtonSizeState): Integer;
    procedure SetSmallestVaraint;
    function SetLargerVariant(CanCompact: Boolean; var NewState: TButtonSizeState; RealSet: Boolean = True): Integer;
    function LargerVariantDifference(CanCompact: Boolean; var NewState: TButtonSizeState): Integer;
    procedure SetLargestVaraint;

    property Persistence: TPersistence read FPersistence write SetPersistence;

    property AutoRUL: Boolean read FAutoRUL write SetAutoRUL default true;

    property Locked: Boolean read FLocked write SetLocked default false;
    property AllowFloating: Boolean read FAllowFloating write SetAllowFloating;

    property AutoOptionMenu: Boolean read FAutoOptionMenu write SetAutoOptionMenu default false;

    property AutoArrangeButtons: Boolean read FAutoArrangeButtons write SetAutoArrangeButtons default True;

    property AutoMDIButtons: Boolean read FAutoMDIButtons write SetAutoMDIButtons default false;
    function GetMyParentForm: TCustomForm;
    property MDIButtonsVisible: Boolean read FMDIButtonsVisible write SetMDIButtonsVisible;

    property AntiAlias: TAntiAlias read FAntiAlias write SetAntiAlias default aaClearType;
    property AutoDockOnClose: Boolean read FAutoDockOnClose write SetAutoDockOnClose default false;
    property Caption: string read FCaption write SetCaption;
    property CaptionFont: TFont read FCaptionFont write SetCaptionFont;
    property CaptionHeight: integer read FCaptionHeight write SetCaptionHeight default DEFAULT_CAPTIONHEIGHT;
    property HintOptionButton: string read FHintOptionButton write FHintOptionButton;
    property HintCloseButton: string read FHintCloseButton write FHintCloseButton;
    property OptionMenu: TPopupMenu read FOptionMenu write FOptionMenu;
    property ShowPopupIndicator: Boolean read FShowPopupIndicator write SetShowPopupIndicator default true;
    property ShowClose: Boolean read FShowClose write SetShowClose default true;
    property ShowOptionIndicator: Boolean read FShowOptionIndicator write SetShowOptionIndicator default true;
    property ShowRightHandle: Boolean read FShowRightHandle write SetShowRightHandle default true;
    property DockableTo: TDockableTo read FDockableTo write SetDockableTo default [daLeft, daTop, daRight, daBottom];
    property DockMode: TDockMode read FDockMode write FDockMode default dmAll;
    property FullSize: Boolean read FFullSize write SetFullSize default false;
    property ToolBarStyler: TCustomAdvToolBarStyler read FToolBarStyler write SetToolBarStyler default nil;
    property ParentStyler: Boolean read FParentStyler write SetParentStyler default true;
    property Position: TDockAlign read FPosition write SetPosition default daTop;
    property Version: string read GetVersion write SetVersion stored false;

    property Images: TCustomImageList read FImages write SetImages;
    property DisabledImages: TCustomImageList read FDisabledImages write SetDisabledImages;
    property Menu: TMainMenu read FMenu write SetMenu;

    property TextAutoOptionMenu: String read FTextAutoOptionMenu write FTextAutoOptionMenu;
    property TextOptionMenu: String read FTextOptionMenu write FTextOptionMenu;

    property CaptionPosition: TCaptionPosition read FCaptionPosition write SetCaptionPosition default cpTop;
    property CaptionAlignment: TAlignment read FCaptionAlignment write SetCaptionAlignment default taLeftJustify;
    property ShowCaption: Boolean read FShowCaption write SetShowCaption default False;

    property AutoSize: Boolean read FAutoSize write SetAutoSizeEx default True;

    property AutoPositionControls: Boolean read FAutoPositionControls write SetAutoPositionControls default true;

    property OptionDisabledPicture: TGDIPPicture read FIOptionDisabledPicture write SetOptionDisabledPicture;
    property OptionPicture: TGDIPPicture read FIOptionPicture write SetOptionPicture;

    property CompactPicture: TGDIPPicture read FICompactPicture write SetCompactPicture;
    property CompactCaption: string read FCompactCaption write SetCompactCaption;
    property WideCompactCaption: widestring read FWideCompactCaption write FWideCompactCaption;

    property OfficeHint: TAdvHintInfo read FOfficeHint write SetOfficeHint;

    property ParentOptionPicture: Boolean read FParentOptionPicture write SetParentOptionPicture;
    property CompactImageIndex: Integer read FCompactImageIndex write SetCompactImageIndex;
    property CompactShortCutHint: string read FCompactShortCutHint write FCompactShortCutHint;

    property OnClose: TNotifyEvent read FOnClose write FOnClose;
    property OnCompactCloseQuery: TCloseQueryEvent read FOnCompactCloseQuery write FOnCompactCloseQuery;
    property OnOptionClick: TOptionEvent read FOnOptionClick write FOnOptionClick;
    property OnDocked: TDockedEvent read FOnDocked write FOnDocked;
    property OnUnDocked: TNotifyEvent read FOnUnDocked write FOnUnDocked;
    property ToolBarIndex: Integer read GetToolBarIndex write SetToolBarIndex;
    procedure ResetToolBar;

  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
    procedure Update; override;
    procedure UpdateControlsVisibility;

    function IsShortCut(var Message: TWMKey): Boolean; dynamic;

    property AdvDockPanel: TAdvDockPanel read GetAdvDockPanel write SetAdvDockPanel;
    procedure SetToolBarFloating(P: TPoint);

    property ActiveMenu: TAdvPopupMenu read FTempMenu;
    procedure UpdateMenu;
    procedure MergeMenu(AMenu: TMainMenu);
    procedure UnmergeMenu(AMenu: TMainMenu);

    property ShowHint: Boolean read GetShowHint write SetShowHint default True;
    function GetVersionNr: Integer;

    procedure MoveToolBarControl(FromIndex, ToIndex: integer);
    procedure InsertToolBarControl(Index: integer; AControl: TControl);
    function AddToolBarControl(AControl: TControl): Integer;
    function IndexOfToolBarControl(AControl: TControl): Integer;

    property ToolBarControls[index: Integer]: TControl read GetToolBarControls;
    property ToolBarControlCount: Integer read GetToolBarControlCount;

    procedure ShowCustomizer;
    procedure AddMDIChildMenu(ChildForm: TCustomForm; Caption: string = '');
    procedure RemoveMDIChildMenu(ChildForm: TCustomForm; Caption: string = '');
    procedure RemoveAllMDIChildMenu;

    function GetToolBarState: TToolBarState;
    procedure BeginUpdate;
    procedure EndUpdate;
   
    procedure SavePosition;
    procedure LoadPosition;

    procedure MoveUpInRUList(aControl: TControl);
    property WideCaption: widestring read FWideCaption write SetWideCaption;
  end;

  TAdvToolBar = class(TAdvCustomToolBar)
  public
    property Compact;
    property IsCompact;
    property WideCompactCaption;
    property OnCompactCloseQuery; 
  published
    property AllowFloating;
    property AntiAlias;
    property AutoArrangeButtons;
    property AutoDockOnClose;
    property AutoMDIButtons;
    property AutoOptionMenu;
    property AutoPositionControls;
    property AutoSize;
    property Locked;
    property Caption;
    property CaptionFont;
    property CaptionHeight;
    property CaptionPosition;
    property CaptionAlignment;
    property CompactCaption;
    property CompactPicture;
    property CompactImageIndex;
    property CompactShortCutHint;
    property ShowCaption;
    property HintOptionButton;
    property HintCloseButton;
    property ShowRightHandle;
    property ShowClose;
    property ShowOptionIndicator;
    property DockableTo;
    property DockMode;
    property Enabled;
    property FullSize;
    property TextAutoOptionMenu;
    property TextOptionMenu;

    property ToolBarStyler;
    property ParentStyler;
    //property Position;
    property Images;
    property DisabledImages;
    property Menu;
    property OptionMenu;
    property OptionDisabledPicture;
    property OptionPicture;
    property ParentOptionPicture;
    property ParentShowHint;
    property ShowHint;
    property ToolBarIndex;
    property OfficeHint;
    property Version;

    property OnClose;
    property OnOptionClick;
    property OnDocked;
    property OnUnDocked;
    property OnDragOver;
    property OnDragDrop;
    property OnEndDrag;
    property OnStartDrag;

    property OnEnter;
    property OnExit;
    //property OnClick;
    property OnDblClick;
    property OnKeyPress;
    property OnKeyDown;
    property OnKeyUp;
    property OnResize;
  end;

  TResizingClip = (rcLeft, rcTop, rcRight, rcBottom);

  TFloatingWindow = class(TCustomForm)
  private
    FAdvCustomToolBar: TAdvCustomToolBar;
    FOwner: TComponent;
    FBorderWidth: integer;
    FBorderColor: TColor;
    FOldCursor: TCursor;
    FResizing: Boolean;
    FMouseX: integer;
    FMouseY: integer;
    FResizingDir: integer; // (0: None), (i: Expand), (2: Shrink)
    FResizingClip: TResizingClip;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure WMActivate(var Message: TWMActivate); message WM_ACTIVATE;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
    procedure SetBorderWidth(const Value: integer);
    procedure SetBorderColor(const Value: TColor);
  protected
    procedure Loaded; override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure Paint; override;
    function GetParentWnd: HWnd;
    procedure CreateParams(var Params: TCreateParams); override;
  public
    constructor Create(AOwner: TComponent); override;
    constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
    destructor Destroy; override;
    procedure SetWindowSize;
  published
{$IFDEF TMSDOTNET}
    //property OnHide;
{$ENDIF}
    property AdvCustomToolBar: TAdvCustomToolBar read FAdvCustomToolBar write FAdvCustomToolBar;
    property BorderWidth: integer read FBorderWidth write SetBorderWidth default 2;
    property BorderColor: TColor read FBorderColor write SetBorderColor default clGray;
  end;

  // Option Selector window

  TOptionSelectorWindow = class(TCustomForm)
  private
    FAdvToolBar: TAdvCustomToolBar;
    FOptionsPanel: TOptionSelectorPanel;
    FHideOnDeActivate: Boolean;
    FShowAbove: Boolean;
    FOwner: TComponent;
    FHideTimer: TTimer;
    FShowLeft: Boolean;
    procedure WMActivate(var Message: TWMActivate); message WM_ACTIVATE;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
    procedure HideTimerOnTime(Sender: TObject);
  protected
    procedure Paint; override;
    function GetParentWnd: HWnd;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure DoHide; override;
    property HideOnDeActivate: Boolean read FHideOnDeActivate write FHideOnDeActivate;
    property ShowAbove: Boolean read FShowAbove write FShowAbove;
    property ShowLeft: Boolean read FShowLeft write FShowLeft default false;
  public
    constructor Create(AOwner: TComponent); override;
    constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
    destructor Destroy; override;
    procedure SetWindowSize;
  published
{$IFDEF TMSDOTNET}
    //property AutoScroll;
    //property BorderIcons;
    //property FormStyle;
    property OnHide;
{$ENDIF}
    property AdvToolBar: TAdvCustomToolBar read FAdvToolBar write FAdvToolBar;
    property OptionsPanel: TOptionSelectorPanel read FOptionsPanel write FOptionsPanel;
  end;


  TOptionSelectorPanel = class(TCustomPanel)
  private
    FOwner: TComponent;
    FColorTo: TColor;
    FGradientDirection: TGradientDirection;
    FWindowBorderColor: TColor;
    FOnShouldHide: TNotifyEvent;
    FMarginY: Integer;
    FMarginX: Integer;
    FAdvToolBar: TAdvCustomToolBar;
    FAdvQuickAccessToolBar: TAdvQuickAccessToolBar;
    procedure SetColorTo(const Value: TColor);
    procedure SetGradientDirection(const Value: TGradientDirection);
    procedure SetWindowBorderColor(const Value: TColor);
    procedure SetMarginX(const Value: Integer);
    procedure SetMarginY(const Value: Integer);
  protected
    procedure Paint; override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    function GetVisibleHeight: integer; virtual;
    procedure DoHide; virtual;

    property OnShouldHide: TNotifyEvent read FOnShouldHide write FOnShouldHide;
    property MarginX: Integer read FMarginX write SetMarginX;
    property MarginY: Integer read FMarginY write SetMarginY;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property ColorTo: TColor read FColorTo write SetColorTo default clNone;
    property WindowBorderColor: TColor read FWindowBorderColor write SetWindowBorderColor default clGray;
    property GradientDirection: TGradientDirection read FGradientDirection write SetGradientDirection;
    property AdvToolBar: TAdvCustomToolBar read FAdvToolBar write FAdvToolBar;
    property AdvQuickAccessToolBar: TAdvQuickAccessToolBar read FAdvQuickAccessToolBar write FAdvQuickAccessToolBar;
  end;

  TCustomizeOption = class (TOptionSelectorPanel)
  private
    FOwner: TComponent;
    FCustomizeBtnHot: Boolean;
    FCustomizeBtnDown: Boolean;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    function GetCustomizeBtnRect: TRect;
  protected
    FCustomizeText: String;
    procedure UpDateSize;
    procedure Paint; override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
  public
    constructor Create(AOwner: TComponent); override;
  end;

  TSelectorItem = class(TObject)
  private
    FHeight: Integer;
    FCaption: TCaption;
    FBRect: TRect;
    FWidth: Integer;
    procedure SetCaption(const Value: TCaption);
    procedure SetHeight(const Value: Integer);
    procedure SetWidth(const Value: Integer);
  protected
    property BRect: TRect read FBRect write FBRect;
  public
    constructor Create;
    destructor Destroy; override;

    property Caption: TCaption read FCaption write SetCaption;
    property Height: Integer read FHeight write SetHeight;
    property Width: Integer read FWidth write SetWidth;
  end;

  TControlSelectorPanel = class (TOptionSelectorPanel)
  private
    FControlList: TDbgList;
    FAddAndRemoveBtn: TSelectorItem;
    FAddAndRemoveBtnHot: Boolean;
    FAddAndRemoveBtnDown: Boolean;
    FItemColorDown: TColor;
    FItemColorHot: TColor;
    FSeparatorSize: Integer;
    FItemColorDownTo: TColor;
    FItemColorHotTo: TColor;
    FItemTextColorHot: TColor;
    FItemTextColor: TColor;
    FItemTextColorDown: TColor;
    FAddAndRemovePopup: TATBPopupWindow;
    FShowAddAndRemoveBtn: Boolean;
    FOptionsBtn: TSelectorItem;
    FOptionsBtnHot: Boolean;
    FOptionsBtnDown: Boolean;
    FOptionsMenu: TPopupMenu;
    FTimer: TTimer;
    FSeparatorList: TDbgList;
    FInternalHiding: Boolean;
    FCustomizer: TAdvToolBarCustomizer;
    FCustomizeOptionPanel: TCustomizeOption;
    FCustomizeOptionWindow: TOptionSelectorWindow;
    procedure OnCustomizeOptionWindowHide(Sender: TObject);
    procedure TimerOnTime(Sender: TObject);
    procedure OnAddAndRemoveWindowHide(Sender: TObject);
    procedure OnAARWindowDeActivateHide(Sender: TObject);
    procedure CMControlChange(var Message: TCMControlChange); message CM_CONTROLCHANGE;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure SetItemColorDown(const Value: TColor);
    procedure SetItemColorHot(const Value: TColor);
    procedure SetItemColorDownTo(const Value: TColor);
    procedure SetItemColorHotTo(const Value: TColor);
    procedure SetItemTextColor(const Value: TColor);
    procedure SetItemTextColorHot(const Value: TColor);
    procedure SetItemTextColorDown(const Value: TColor);
    procedure SetShowAddAndRemoveBtn(const Value: Boolean);
    function GetShowOptionsBtn: Boolean;
    procedure SetOptionsMenu(const Value: TPopupMenu);
    procedure SetTextAutoOptionMenu(const Value: String);
    procedure SetTextOptionMenu(const Value: String);
    function GetTextAutoOptionMenu: String;
    function GetTextOptionMenu: String;
  protected
    procedure Paint; override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure DoHide; override;
    procedure ShowAddAndRemovePopup;
    procedure HideAddAndRemovePopup;

    procedure ShowOptionsBtnPopup;
    procedure HideOptionsBtnPopup;

    procedure ReSetButtonSize;

    function AddCopySeparator(ASeparator: TAdvToolBarSeparator): TAdvToolBarSeparator;

    property ControlList: TDbgList read FControlList;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    procedure ArrangeControls;
    function AddControl(AControl: TControl): Integer;
    procedure RemoveControl(AControl: TControl);
    function IsEmpty: Boolean;

    property ShowAddAndRemoveBtn: Boolean read FShowAddAndRemoveBtn write SetShowAddAndRemoveBtn;
    property ShowOptionsBtn: Boolean read GetShowOptionsBtn;
    property TextAutoOptionMenu: String read GetTextAutoOptionMenu write SetTextAutoOptionMenu;
    property TextOptionMenu: String read GetTextOptionMenu write SetTextOptionMenu;
    property OptionsMenu: TPopupMenu read FOptionsMenu write SetOptionsMenu;
    property Customizer: TAdvToolBarCustomizer read FCustomizer write FCustomizer;
    property ItemColorHot: TColor read FItemColorHot write SetItemColorHot;
    property ItemColorHotTo: TColor read FItemColorHotTo write SetItemColorHotTo;
    property ItemColorDown: TColor read FItemColorDown write SetItemColorDown;
    property ItemColorDownTo: TColor read FItemColorDownTo write SetItemColorDownTo;
    property ItemTextColor: TColor read FItemTextColor write SetItemTextColor;
    property ItemTextColorHot: TColor read FItemTextColorHot write SetItemTextColorHot;
    property ItemTextColorDown: TColor read FItemTextColorDown write SetItemTextColorDown;
  published
  end;


  // AdvToolBar PopupMenu

  TATBPopupWindow = class(TCustomForm)
  private
    FAdvToolBar: TAdvCustomToolBar;
    FPopupPanel: TATBPopupPanel;
    FHideOnDeActivate: Boolean;
    FShowAbove: Boolean;
    FOwner: TComponent;
    FHideTimer: TTimer;
    FShowLeft: Boolean;
    FItems: TATBMenuItem;
    FOnDeActivateHide: TNotifyEvent;
    procedure CreatePopupPanel;
    procedure WMActivate(var Message: TWMActivate); message WM_ACTIVATE;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
    procedure HideTimerOnTime(Sender: TObject);
    procedure SetPopupPanel(const Value: TATBPopupPanel);
  protected
    procedure Paint; override;
    function GetParentWnd: HWnd;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure CreateItems;
    property HideOnDeActivate: Boolean read FHideOnDeActivate write FHideOnDeActivate;
    property ShowAbove: Boolean read FShowAbove write FShowAbove;
    property ShowLeft: Boolean read FShowLeft write FShowLeft default false;
  public
    constructor Create(AOwner: TComponent); override;
    constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
    destructor Destroy; override;
    procedure SetWindowSize;

    procedure Hide;
  published
{$IFDEF TMSDOTNET}
    //property AutoScroll;
    //property BorderIcons;
    //property FormStyle;
    property OnHide;
{$ENDIF}
    property AdvToolBar: TAdvCustomToolBar read FAdvToolBar write FAdvToolBar;
    property PopupPanel: TATBPopupPanel read FPopupPanel write SetPopupPanel;
    property OnDeActivateHide: TNotifyEvent read FOnDeActivateHide write FOnDeActivateHide;
  end;


  TATBCustomPopupPanel = class(TCustomPanel)
  private
    FOwner: TComponent;
    FColorTo: TColor;
    FGradientDirection: TGradientDirection;
    FWindowBorderColor: TColor;
    FOnShouldHide: TNotifyEvent;
    FMarginY: Integer;
    FMarginX: Integer;
    procedure SetColorTo(const Value: TColor);
    procedure SetGradientDirection(const Value: TGradientDirection);
    procedure SetWindowBorderColor(const Value: TColor);
    procedure SetMarginX(const Value: Integer);
    procedure SetMarginY(const Value: Integer);
  protected
    procedure Paint; override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    function GetVisibleHeight: integer; virtual;

    property OnShouldHide: TNotifyEvent read FOnShouldHide write FOnShouldHide;
    property MarginX: Integer read FMarginX write SetMarginX;
    property MarginY: Integer read FMarginY write SetMarginY;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property ColorTo: TColor read FColorTo write SetColorTo default clNone;
    property WindowBorderColor: TColor read FWindowBorderColor write SetWindowBorderColor default clGray;
    property GradientDirection: TGradientDirection read FGradientDirection write SetGradientDirection;
  end;

  TATBMenuItem = class(TObject)
  private
    FEnabled: Boolean;
    FVisible: Boolean;
    FBoundRect: TRect;
    FItems: TList;
    FParentItem: TATBMenuItem;
    FHeight: Integer;
    FCaption: TCaption;
    FWidth: Integer;
    FChecked: Boolean;
    FHint: string;
    FAutoCheck: Boolean;
    FObjects: TObject;
    procedure SetCaption(const Value: TCaption);
    procedure SetHeight(const Value: Integer);
    procedure SetWidth(const Value: Integer);
    function GetCount: integer;
    function GetItem(Index: Integer): TATBMenuItem;
    procedure SetChecked(const Value: Boolean);
    procedure SetEnabled(const Value: Boolean);
    procedure SetFParentItem(const Value: TATBMenuItem);
    procedure SetVisible(const Value: Boolean);
    procedure SetAutoCheck(const Value: Boolean);
  protected
    property BoundRect: TRect read FBoundRect write FBoundRect;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Clear;
    function HasChildren: Boolean;
    function Add: TATBMenuItem;
    procedure RemoveItem(ItemIndex: Integer);

    property AutoCheck: Boolean read FAutoCheck write SetAutoCheck;
    property Caption: TCaption read FCaption write SetCaption;
    property Height: Integer read FHeight write SetHeight;
    property Width: Integer read FWidth write SetWidth;
    property Checked: Boolean read FChecked write SetChecked;
    property Enabled: Boolean read FEnabled write SetEnabled;
    property Hint: string read FHint write FHint;
    property Visible: Boolean read FVisible write SetVisible;
    property ParentItem: TATBMenuItem read FParentItem write SetFParentItem;

    property Objects: TObject read FObjects write FObjects;

    property Count: integer read GetCount;
    property Items[Index: Integer]: TATBMenuItem read GetItem; default;
  end;

  TATBPopupPanel = class (TATBCustomPopupPanel)
  private
    FItems: TATBMenuItem;
    FAdvMenuStyler: TCustomAdvMenuStyler;
    FItemHeight: Integer;
    FHotItem: Integer;
    FPopupItem: Integer;
    FShowImageBar: Boolean;
    FShowIconBar: Boolean;
    FImageBarSize: Integer;
    FImageBarColorTo: TColor;
    FImageBarColor: TColor;
    FItemPopup: TATBPopupWindow;
    procedure OnItemPopupHide(Sender: TObject);
    procedure OnItemPopupDeActivateHide(Sender: TObject);
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure SetAdvMenuStyler(const Value: TCustomAdvMenuStyler);
    procedure SetItems(const Value: TATBMenuItem);
    procedure SetItemHeight(const Value: Integer);
    procedure SetHotItem(const Value: Integer);
    procedure SetShowImageBar(const Value: Boolean);
    procedure SetShowIconBar(const Value: Boolean);
    procedure SetImageBarSize(const Value: Integer);
  protected
    procedure Paint; override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;

    procedure ShowItemPopup;
    procedure HideItemPopup;
    procedure BeforeHide;

    procedure ItemClick(ItemIndex: Integer);

    function IsAnyAutoCheckItem: Boolean;
    procedure DrawItem(ItemIndex: Integer);
    procedure DrawAllItems;

    property ImageBarSize: Integer read FImageBarSize write SetImageBarSize;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    procedure InvalidateItem(ItemIndex: Integer);
    function IndexOfItemAt(X, Y: Integer): Integer;
    procedure ToggleCheck(ItemIndex: Integer);
    procedure ArrangeItems;

    property HotItem: Integer read FHotItem write SetHotItem;
    property ItemHeight: Integer read FItemHeight write SetItemHeight;
    property Items: TATBMenuItem read FItems write SetItems;
    property AdvMenuStyler: TCustomAdvMenuStyler read FAdvMenuStyler write SetAdvMenuStyler;
    property ShowImageBar: Boolean read FShowImageBar write SetShowImageBar;
    property ShowIconBar: Boolean read FShowIconBar write SetShowIconBar;
    property ImageBarColor: TColor read FImageBarColor write FImageBarColor;
    property ImageBarColorTo: TColor read FImageBarColorTo write FImageBarColorTo;
  published
  end;

  //----------- AdvToolBarCustomizer

  TATBCommand = class(TCollectionItem)
  private
    FOnExecute: TNotifyEvent;
    FCaption: TCaption;
    FItemIndex: Integer;
    FAction: TBasicAction;
    procedure SetCaption(const Value: TCaption);
  protected
  public
    constructor Create(Collection: TCollection); override;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property Caption: TCaption read FCaption write SetCaption;
    property ItemIndex: Integer read FItemIndex write FItemIndex;
    property Action: TBasicAction read FAction write FAction;
    property OnExecute: TNotifyEvent read FOnExecute write FOnExecute;
  end;

  TATBCommands = class(TCollection)
  private
    FOwner: TAdvToolBarCustomizer;
    {$IFNDEF DELPHI6_LVL}
    FMyOwner: TPersistent;
    {$ENDIF}
    FOnChange: TNotifyEvent;
    function GetItem(Index: Integer): TATBCommand;
    procedure SetItem(Index: Integer; const Value: TATBCommand);
  protected
  public
    constructor Create(AOwner: TAdvToolBarCustomizer);
    property Items[Index: Integer]: TATBCommand read GetItem write SetItem; default;
    function Add: TATBCommand;
    function Insert(Index: Integer): TATBCommand;
    function GetOwner: TPersistent; override;
    {$IFNDEF DELPHI6_LVL}
    property Owner: TPersistent read FMyOwner;
    {$ENDIF}
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;

  TButtonProperties = class(TPersistent)
  private
    FCaption: Boolean;
    FShowCaption: Boolean;
    FVisible: Boolean;
    FHint: Boolean;
    FGlyph: Boolean;
    FOnChange: TNotifyEvent;
    //FFormCaption: TCaption;
    procedure SetCaption(const Value: Boolean);
    procedure SetGlyph(const Value: Boolean);
    procedure SetHint(const Value: Boolean);
    procedure SetShowCaption(const Value: Boolean);
    procedure SetVisible(const Value: Boolean);
  protected
    procedure Change;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property Caption: Boolean read FCaption write SetCaption;
    //property FormCaption: TCaption read FFormCaption write FFormCaption;
    property Glyph: Boolean read FGlyph write SetGlyph;
    property Hint: Boolean read FHint write SetHint;
    property Visible: Boolean read FVisible write SetVisible;
    //property Enabled: Boolean read FEnabled write SetEnabled;
    property ShowCaption: Boolean read FShowCaption write SetShowCaption;
  end;

  TCustomizedOptions = class(TPersistent)
  private
    FAddButton: Boolean;
    FReOrder: Boolean;
    FDelete: Boolean;
    FDeleteAll: Boolean;
    FAddSeparator: Boolean;
    FOnChange: TNotifyEvent;
    FAddGlowButton: Boolean;
    FEditButton: Boolean;
    procedure SetAddButton(const Value: Boolean);
    procedure SetAddSeparator(const Value: Boolean);
    procedure SetDelete(const Value: Boolean);
    procedure SetDeleteAll(const Value: Boolean);
    procedure SetReOrder(const Value: Boolean);
    procedure SetAddGlowButton(const Value: Boolean);
    procedure SetEditButton(const Value: Boolean);
  protected
    procedure Change;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property ReOrder: Boolean read FReOrder write SetReOrder;
    property AddButton: Boolean read FAddButton write SetAddButton;
    property AddSeparator: Boolean read FAddSeparator write SetAddSeparator;
    property AddGlowButton: Boolean read FAddGlowButton write SetAddGlowButton default true;
    property Delete: Boolean read FDelete write SetDelete;
    property DeleteAll: Boolean read FDeleteAll write SetDeleteAll;
    property EditButton: Boolean read FEditButton  write SetEditButton default true;
  end;

  TDialogSettings = class(TPersistent)
  private
    FEditCaption: Boolean;
    FLargeIcon: Boolean;
    FEditGlyphPosition: Boolean;
    FUpHint: string;
    FButtonEditCaptionLabel: string;
    FTopHint: string;
    FButtonEditIconLabel: string;
    FToolBarLabel: string;
    FDeleteHint: string;
    FEditHint: string;
    FCaptionLabel: string;
    FGlyphPosLabel: string;
    FCommandLabel: string;
    FButtonEditVisibleCheck: string;
    FButtonEditCaptionCheck: string;
    FButtonEditHintLabel: string;
    FAddHint: string;
    FAddSeparatorHint: string;
    FDeleteAllHint: string;
    FBottomHint: string;
    FDownHint: string;
    FCaption: string;
    FLargeIconCheck: string;
    FButtonEditCaption: string;
    FOnChange: TNotifyEvent;
    FEditGlyph: Boolean;
    FCustomize: string;
    FResetButtonCaption: string;
    FOKButtonCaption: string;
    FCancelButtonCaption: string;
    FEditGlyphVisible: Boolean;
    FCancelButtonHint: string;
    FResetButtonHint: string;
    FAddGlowButtonHint: string;
    FGlyphPositionBottomCaption: string;
    FGlyphPositionLeftCaption: string;
    FGlyphPositionTopCaption: string;
    FGlyphPositionRightCaption: string;
    FOKButtonHint: string;
    FGlyphEditNoneIconCaption: string;
  protected
    procedure Change;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property ToolBarLabel: string read FToolBarLabel write FToolBarLabel;
    property CommandLabel: string read FCommandLabel write FCommandLabel;
    property CaptionLabel: string read FCaptionLabel write FCaptionLabel;
    property GlyphPosLabel: string read FGlyphPosLabel write FGlyphPosLabel;
    property LargeIconCheck: string read FLargeIconCheck write FLargeIconCheck;
    property TopHint: string read FTopHint write FTopHint;
    property UpHint: string read FUpHint write FUpHint;
    property DownHint: string read FDownHint write FDownHint;
    property BottomHint: string read FBottomHint write FBottomHint;
    property AddHint: string read FAddHint write FAddHint;
    property AddSeparatorHint: string read FAddSeparatorHint write FAddSeparatorHint;
    property DeleteHint: string read FDeleteHint write FDeleteHint;
    property DeleteAllHint: string read FDeleteAllHint write FDeleteAllHint;
    property EditHint: string read FEditHint write FEditHint;
    property Caption: string read FCaption write FCaption; //(dialog caption)
    property ButtonEditCaption: string read FButtonEditCaption write FButtonEditCaption;  // ButtonEdit Form Caption
    property ButtonEditCaptionLabel: string read FButtonEditCaptionLabel write FButtonEditCaptionLabel;
    property ButtonEditHintLabel: string read FButtonEditHintLabel write FButtonEditHintLabel;
    property ButtonEditIconLabel: string read FButtonEditIconLabel write FButtonEditIconLabel;
    property ButtonEditCaptionCheck: string read FButtonEditCaptionCheck write FButtonEditCaptionCheck;
    property ButtonEditVisibleCheck: string read FButtonEditVisibleCheck write FButtonEditVisibleCheck;

    property OKButtonCaption: string read FOKButtonCaption write FOKButtonCaption;
    property OKButtonHint: string read FOKButtonHint write FOKButtonHint;
    property CancelButtonCaption: string read FCancelButtonCaption write FCancelButtonCaption;
    property CancelButtonHint: string read FCancelButtonHint write FCancelButtonHint;
    property ResetButtonCaption: string read FResetButtonCaption write FResetButtonCaption;
    property ResetButtonHint: string read FResetButtonHint write FResetButtonHint;
    property AddGlowButtonHint: string read FAddGlowButtonHint write FAddGlowButtonHint;
    property GlyphPositionLeftCaption: string read FGlyphPositionLeftCaption write FGlyphPositionLeftCaption;
    property GlyphPositionTopCaption: string read FGlyphPositionTopCaption write FGlyphPositionTopCaption;
    property GlyphPositionRightCaption: string read FGlyphPositionRightCaption write FGlyphPositionRightCaption;
    property GlyphPositionBottomCaption: string read FGlyphPositionBottomCaption write FGlyphPositionBottomCaption;
    property GlyphEditNoneIconCaption: string read FGlyphEditNoneIconCaption write FGlyphEditNoneIconCaption;

    property EditGlyph: Boolean read FEditGlyph write FEditGlyph default true;
    property EditGlyphVisible: Boolean read FEditGlyphVisible write FEditGlyphVisible;

    property EditCaption: Boolean read FEditCaption write FEditCaption;
    property EditGlyphPosition: Boolean read FEditGlyphPosition write FEditGlyphPosition;
    property LargeIcon: Boolean read FLargeIcon write FLargeIcon;

    property Customize: string read FCustomize write FCustomize;
  end;

  TAdvToolBarWindow = class(TCustomForm)
  private
    FOwner: TComponent;
    FBorderWidth: integer;
    FBorderColor: TColor;
    FColorTo: TColor;
    FGradientDirection: TGradientDirection;
    FCaptionColorTo: TColor;
    FCaptionColor: TColor;
  protected
    procedure Paint; override;
  public
    constructor Create(AOwner: TComponent); override;
    constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
    destructor Destroy; override;
  published
    property ColorTo: TColor read FColorTo write FColorTo;
    property CaptionColor: TColor read FCaptionColor write FCaptionColor;
    property CaptionColorTo: TColor read FCaptionColorTo write FCaptionColorTo;
    property GradientDirection: TGradientDirection read FGradientDirection write FGradientDirection;
    property BorderWidth: integer read FBorderWidth write FBorderWidth;
    property BorderColor: TColor read FBorderColor write FBorderColor;
  end;

  TATBItemProp = class(TObject)
  private
    FATBItem: TObject;
    FCustomizerCreated: Boolean;
    FIsSeparator: Boolean;
    FIsATBButton: Boolean;
    FImageIndex: Integer;
    FCaption: String;
    FShowCaption: Boolean;
    FHint: String;
    FVisible: Boolean;
    FID: String;
    FCommandID: Integer;
    FForceImageIndex: Boolean;
    FIsGlowButton: Boolean;
    procedure SetIsATBButton(const Value: Boolean);
    procedure SetIsSeparator(const Value: Boolean);
  protected
  public
    constructor Create;
    destructor Destroy; override;
    property IsATBButton: Boolean read FIsATBButton write SetIsATBButton;
    property IsSeparator: Boolean read FIsSeparator write SetIsSeparator;
    property IsGlowButton: Boolean read FIsGlowButton write FIsGlowButton;
    property ATBItem: TObject read FATBItem write FATBItem;
    property CustomizerCreated: Boolean read FCustomizerCreated write FCustomizerCreated;
    property ImageIndex: Integer read FImageIndex write FImageIndex;
    property Caption: String read FCaption write FCaption;
    property Hint: String read FHint write FHint;
    property Visible: Boolean read FVisible write FVisible;
    property ShowCaption: Boolean read FShowCaption write FShowCaption;
    property ID: String read FID write FID;
    property CommandID: Integer read FCommandID write FCommandID;
    property ForceImageIndex: Boolean read FForceImageIndex write FForceImageIndex;
  end;

  TCustomizerCanShowEvent = procedure (Sender: TObject; var X, Y: Integer; var CanShow: Boolean) of object;

  TAdvToolBarCustomizer = class (TComponent)
  private
    //FCaption: Boolean;
    FEnablePersistence: Boolean;
    //FLargeIcon: Boolean;
    //FGlyphPosition: Boolean;
    FFileName: String;
    FAdvToolBar: TAdvToolBar;
    FCommands: TATBCommands;
    FButtonProperties: TButtonProperties;
    FLargeImages: TCustomImageList;
    FOptions: TCustomizedOptions;
    //FFormCaption: TCaption;
    FSmallImages: TCustomImageList;
    FOnBeforeDisplay: TNotifyEvent;
    FOnAfterPost: TNotifyEvent;
    FDialogSettings: TDialogSettings;
    FOnCanShow: TCustomizerCanShowEvent;
    procedure OnButtonPropChange(Sender: TObject);
    procedure OnOptionsChange(Sender: TObject);
    procedure OnCommandsChange(Sender: TObject);
    procedure SetAdvToolBar(const Value: TAdvToolBar);
    procedure SetButtonProperties(const Value: TButtonProperties);
    //procedure SetCaption(const Value: Boolean);
    procedure SetCommands(const Value: TATBCommands);
    procedure SetEnablePersistence(const Value: Boolean);
    procedure SetFileName(const Value: String);
    //procedure SetGlyphPosition(const Value: Boolean);
    procedure SetLargeImages(const Value: TCustomImageList);
    //procedure SetLargeIcon(const Value: Boolean);
    procedure SetOptions(const Value: TCustomizedOptions);
    //procedure SetFormCaption(const Value: TCaption);
    procedure SetSmallImages(const Value: TCustomImageList);
    procedure SetDialogSettings(const Value: TDialogSettings);
  protected
    FDeleteItems: TDbgList;
    procedure UpdateAdvToolBar; virtual;
    procedure InitializeWindow;
    procedure ShowCustomizer; virtual;
    procedure ResetToolBar; virtual;
    procedure SaveInitialState; virtual;
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    function GetCtrl(CtrlName: String): TControl;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Loaded; override;
    procedure Assign(Source: TPersistent); override;
  published
    property AdvToolBar: TAdvToolBar read FAdvToolBar write SetAdvToolBar;
    property LargeImages: TCustomImageList read FLargeImages write SetLargeImages;//(for Large Icons)
    property SmallImages: TCustomImageList read FSmallImages write SetSmallImages;
    property Commands: TATBCommands read FCommands write SetCommands;
    property EnablePersistence: Boolean read FEnablePersistence write SetEnablePersistence;
    property FileName: String read FFileName write SetFileName; // Ini File Name
    //property FormCaption: TCaption read FFormCaption write SetFormCaption;

    //property Caption: Boolean read FCaption write SetCaption; // AdvToolBar
    //property GlyphPosition: Boolean read FGlyphPosition write SetGlyphPosition; // Will apply on all Buttons
    //property LargeIcon: Boolean read FLargeIcon write SetLargeIcon;

    property ButtonProperties: TButtonProperties read FButtonProperties write SetButtonProperties;
    property DialogSettings: TDialogSettings read FDialogSettings write SetDialogSettings;
    //Help: Bool
    //HelpText: String
    property Options: TCustomizedOptions read FOptions write SetOptions;
    //Events
    property OnBeforeDisplay: TNotifyEvent read FOnBeforeDisplay write FOnBeforeDisplay;
    property OnAfterPost: TNotifyEvent read FOnAfterPost write FOnAfterPost;
    property OnCanShow: TCustomizerCanShowEvent read FOnCanShow write FOnCanShow;
    //OnAfterCancel
    //OnGetHelp
  end;

  TWinCtrl = class(TWinControl)
  public
    procedure PaintCtrls(DC: HDC; First: TControl);
  end;

  TAdvToolBarContainer = class(TCustomControl)
  private
    FAdvToolBar: TAdvCustomToolBar;
    FParentStyler: Boolean;
    FLine3D: Boolean;
    FCaption: TCaption;
    FLineColor: TColor;
    FColor: TGradientBackground;
    FMargin: Integer;
    FOfficeHint: TAdvHintInfo;
    procedure OnColorChange(Sender: TObject);
    procedure WMEraseBkGnd(var Message: TWMEraseBkGnd); message WM_ERASEBKGND;
    procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
    procedure CMControlChange(var Message: TCMControlChange); message CM_CONTROLCHANGE;
    procedure SetAdvToolBar(const Value: TAdvCustomToolBar);
    procedure SetCaption(const Value: TCaption);
    procedure SetColor(const Value: TGradientBackground);
    procedure SetLineColor(const Value: TColor);
    procedure SetParentStyler(const Value: Boolean);
    procedure SetLine3D(const Value: Boolean);
    procedure SetOfficeHint(const Value: TAdvHintInfo);
  protected
    procedure Paint; override;
    procedure ReadState(Reader: TReader); override;
    procedure Loaded; override;
    procedure UpdateAllGlowButtons;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    property AdvToolBar: TAdvCustomToolBar read FAdvToolBar write SetAdvToolBar;
  published
    property Align;
    property AutoSize; 
    property Caption: TCaption read FCaption write SetCaption;
    property Color: TGradientBackground read FColor write SetColor;
    property OfficeHint: TAdvHintInfo read FOfficeHint write SetOfficeHint;
    property LineColor: TColor read FLineColor write SetLineColor;
    property ParentStyler: Boolean read FParentStyler write SetParentStyler default true;
    property Line3D: Boolean read FLine3D write SetLine3D;
  end;

  //======== AdvToolBarPager ==========
  
  TAdvPageCaption = class(TPersistent)
  private
    FOnChange: TNotifyEvent;
    FVisible: Boolean;
    FHeight: Integer;
    FCaption: TCaption;
    FIndent: Integer;
    FRightIndent: Integer;
    FWideCaption: widestring;
    FMinWidth: Integer;
    procedure SetCaption(const Value: TCaption);
    procedure SetHeight(const Value: Integer);
    procedure SetVisible(const Value: Boolean);
    procedure SetIndent(const Value: Integer);
    procedure SetWideCaption(const Value: widestring);
    procedure SetMinWidth(const Value: Integer);
  protected
    procedure Changed;
    property RightIndent: Integer read FRightIndent write FRightIndent;
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property WideCaption: widestring read FWideCaption write SetWideCaption;
  published
    property Caption: TCaption read FCaption write SetCaption;
    property Visible: Boolean read FVisible write SetVisible default true;
    property Height: Integer read FHeight write SetHeight default DEFAULT_PAGERCAPTIONHEIGHT;
    property Indent: Integer read FIndent write SetIndent default 100;
    property MinWidth: Integer read FMinWidth write SetMinWidth default 100;
  end;

  TATBTabSettings = class(TPersistent)
  private
    FLeftMargin: Integer;
    FRightMargin: Integer;
    FOnChange: TNotifyEvent;
    FHeight: Integer;
    FStartMargin: Integer;
    FEndMargin: Integer;
    FSpacing: Integer;
    FMinSpacing: Integer;
    FMinMargin: Integer;
    procedure SetLeftMargin(const Value: Integer);
    procedure SetRightMargin(const Value: Integer);
    procedure SetHeight(const Value: Integer);
    procedure SetStartMargin(const Value: Integer);
    procedure SetEndMargin(const Value: Integer);
    procedure SetSpacing(const Value: Integer);
  protected
    procedure Changed;
    property MinSpacing: Integer read FMinSpacing write FMinSpacing;
    property MinMargin: Integer read FMinMargin write FMinMargin;
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  published
    property LeftMargin: Integer read FLeftMargin write SetLeftMargin default 4;
    property RightMargin: Integer read FRightMargin write SetRightMargin default 4;
    property StartMargin: Integer read FStartMargin write SetStartMargin default 60;
    property EndMargin: Integer read FEndMargin write SetEndMargin;
    property Height: Integer read FHeight write SetHeight default 26;
    property Spacing: Integer read FSpacing write SetSpacing default 4;
  end;

  TVistaBackground = class(TPersistent)
  private
    FSteps: Integer;
    FColor: TColor;
    FColorTo: TColor;
    FOnChange: TNotifyEvent;
    FColorMirror: TColor;
    FColorMirrorTo: TColor;
    FBorderColor: TColor;
    FGradientMirror: TGDIPGradient;
    FGradient: TGDIPGradient;
    FShadowColor: TColor;
    FHighLightColor: TColor;
    procedure SetColor(const Value: TColor);
    procedure SetColorTo(const Value: TColor);
    procedure SetSteps(const Value: Integer);
    procedure Changed;
    procedure SetBorderColor(const Value: TColor);
    procedure SetColorMirror(const Value: TColor);
    procedure SetColorMirrorTo(const Value: TColor);
    procedure SetGradient(const Value: TGDIPGradient);
    procedure SetGradientMirror(const Value: TGDIPGradient);
  protected
    property ShadowColor: TColor read FShadowColor write FShadowColor;
    property HighLightColor: TColor read FHighLightColor write FHighLightColor;
  public
    constructor Create;
    procedure Assign(Source: TPersistent); override;
  published
    property BorderColor: TColor read FBorderColor write SetBorderColor;
    property Color: TColor read FColor write SetColor;
    property ColorTo: TColor read FColorTo write SetColorTo;
    property ColorMirror: TColor read FColorMirror write SetColorMirror;
    property ColorMirrorTo: TColor read FColorMirrorTo write SetColorMirrorTo;
    property Gradient: TGDIPGradient read FGradient write SetGradient;
    property GradientMirror: TGDIPGradient read FGradientMirror write SetGradientMirror;
    property Steps: Integer read FSteps write SetSteps default 64;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;

  TVistaPageBackground = class(TVistaBackground)
  published
    property ShadowColor;
    property HighLightColor;
  end;

  TVistaTextBackGround = class(TVistaBackground)
  private
    FTextColor: TColor;
    FFont: TFont;
    FSystemFont: boolean;
    procedure SetTextColor(const Value: TColor);
    procedure SetFont(const Value: TFont);
    procedure SetSystemFont(const Value: boolean);
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property TextColor: TColor read FTextColor write SetTextColor;
    property Font: TFont read FFont write SetFont;
    property SystemFont: boolean read FSystemFont write SetSystemFont default true;
  end;

  TQATAppearance = class(TPersistent)
  private
    FFullSizeColorTo: TColor;
    FFullSizeColor: TColor;
    FFullSizeBorderColor: TColor;
    FSteps: Integer;
    FColor: TColor;
    FColorTo: TColor;
    FBorderColor: TColor;
    FOnChange: TNotifyEvent;
    procedure SetFullSizeColor(const Value: TColor);
    procedure SetFullSizeColorTo(const Value: TColor);
    procedure SetFullSizeBorderColor(const Value: TColor);
    procedure SetBorderColor(const Value: TColor);
    procedure SetColor(const Value: TColor);
    procedure SetColorTo(const Value: TColor);
    procedure SetSteps(const Value: Integer);
  protected
    procedure Changed;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property BorderColor: TColor read FBorderColor write SetBorderColor;
    property Color: TColor read FColor write SetColor;
    property ColorTo: TColor read FColorTo write SetColorTo;
    property FullSizeBorderColor: TColor read FFullSizeBorderColor write SetFullSizeBorderColor;
    property FullSizeColor: TColor read FFullSizeColor write SetFullSizeColor;
    property FullSizeColorTo: TColor read FFullSizeColorTo write SetFullSizeColorTo;
    property Steps: Integer read FSteps write SetSteps default 64;
  end;
  
 { TPageGroupBackGround = class(TVistaBackground)
  private
    FCaptionAppearance: TCaptionAppearance;
    procedure SetCaptionAppearance(const Value: TCaptionAppearance);
  public
    constructor Create;
    destructor destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property CaptionAppearance: TCaptionAppearance read FCaptionAppearance write SetCaptionAppearance;
  end;  }

  TToolBarAppearance = class(TPersistent)
  private
    FBorderColorHot: TColor;
    FBorderColor: TColor;
    FColor: TGradientBackground;
    FColorHot: TGradientBackground;
    FOnChange: TNotifyEvent;
    procedure SetBorderColor(const Value: TColor);
    procedure SetBorderColorHot(const Value: TColor);
    procedure SetColor(const Value: TGradientBackground);
    procedure SetColorHot(const Value: TGradientBackground);
  protected
    procedure Changed;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property BorderColor: TColor read FBorderColor write SetBorderColor default clNone;
    property BorderColorHot: TColor read FBorderColorHot write SetBorderColorHot default clNone;
    property Color: TGradientBackground read FColor write SetColor;
    property ColorHot: TGradientBackground read FColorHot write SetColorHot;
  end;

  TGroupAppearance = class(TPersistent)
  private
    FSteps: Integer;
    FColor: TColor;
    FColorTo: TColor;
    FOnChange: TNotifyEvent;
    FColorMirror: TColor;
    FColorMirrorTo: TColor;
    FBorderColor: TColor;
    FGradientMirror: TGDIPGradient;
    FGradient: TGDIPGradient;
    FTextColor: TColor;
    FCaptionAppearance: TCaptionAppearance;
    FPageAppearance: TVistaPageBackground;
    FToolBarAppearance: TToolBarAppearance;
    FTabAppearance: TCustomTabAppearance;
    FFont: TFont;
    FSystemFont: boolean;
    procedure OnCaptionAppearanceChanged(Sender: TObject);
    procedure OnPageAppearanceChanged(Sender: TObject);
    procedure OnToolBarAppearanceChanged(Sender: TObject);
    procedure OnTabAppearanceChanged(Sender: TObject);

    procedure SetColor(const Value: TColor);
    procedure SetColorTo(const Value: TColor);
    procedure SetSteps(const Value: Integer);
    procedure Changed;
    procedure SetBorderColor(const Value: TColor);
    procedure SetColorMirror(const Value: TColor);
    procedure SetColorMirrorTo(const Value: TColor);
    procedure SetGradient(const Value: TGDIPGradient);
    procedure SetGradientMirror(const Value: TGDIPGradient);
    procedure SetTextColor(const Value: TColor);
    procedure SetCaptionAppearance(const Value: TCaptionAppearance);
    procedure SetPageAppearance(const Value: TVistaPageBackground);
    procedure SetToolBarAppearance(const Value: TToolBarAppearance);
    procedure SetTabAppearance(const Value: TCustomTabAppearance);
    procedure SetFont(const Value: TFont);
    procedure SetSystemFont(const Value: boolean);
  protected
    property Steps: Integer read FSteps write SetSteps default 64;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property BorderColor: TColor read FBorderColor write SetBorderColor;
    property Color: TColor read FColor write SetColor;
    property ColorTo: TColor read FColorTo write SetColorTo;
    property ColorMirror: TColor read FColorMirror write SetColorMirror;
    property ColorMirrorTo: TColor read FColorMirrorTo write SetColorMirrorTo;
    property Font: TFont read FFont write SetFont;
    property Gradient: TGDIPGradient read FGradient write SetGradient;
    property GradientMirror: TGDIPGradient read FGradientMirror write SetGradientMirror;
    property TextColor: TColor read FTextColor write SetTextColor;
    property CaptionAppearance: TCaptionAppearance read FCaptionAppearance write SetCaptionAppearance;
    property PageAppearance: TVistaPageBackground read FPageAppearance write SetPageAppearance;
    property SystemFont: boolean read FSystemFont write SetSystemFont default true;
    property TabAppearance: TCustomTabAppearance read FTabAppearance write SetTabAppearance;
    property ToolBarAppearance: TToolBarAppearance read FToolBarAppearance write SetToolBarAppearance;
  end;

  TCustomTabAppearance = class(TPersistent)
  private
    FOnChange: TNotifyEvent;
    FBorderColor: TColor;
    FBorderColorHot: TColor;
    FColor: TColor;
    FColorTo: TColor;
    FColorHot: TColor;
    FColorHotTo: TColor;
    FColorSelectedTo: TColor;
    FBorderColorDisabled: TColor;
    FBorderColorSelected: TColor;
    FColorDisabled: TColor;
    FColorDisabledTo: TColor;
    FColorSelected: TColor;
    FColorMirror: TColor;
    FColorMirrorTo: TColor;
    FColorMirrorHot: TColor;
    FColorMirrorHotTo: TColor;
    FGradientMirror: TGDIPGradient;
    FGradientMirrorHot: TGDIPGradient;
    FGradient: TGDIPGradient;
    FGradientHot: TGDIPGradient;
    FColorMirrorDisabledTo: TColor;
    FColorMirrorDisabled: TColor;
    FColorMirrorSelectedTo: TColor;
    FColorMirrorSelected: TColor;
    FGradientSelected: TGDIPGradient;
    FGradientDisabled: TGDIPGradient;
    FGradientMirrorSelected: TGDIPGradient;
    FGradientMirrorDisabled: TGDIPGradient;
    FTextColorDisabled: TColor;
    FTextColorSelected: TColor;
    FTextColor: TColor;
    FTextColorHot: TColor;
    FBackGround: TGradientBackground;
    FBorderColorSelectedHot: TColor;
    FBorderColorDown: TColor;
    FFont: TFont;
    FSystemFont: Boolean;
    FShadowColor: TColor;
    FHighLightColor: TColor;
    FHighLightColorSelected: TColor;
    FHighLightColorDown: TColor;
    FHighLightColorHot: TColor;
    FHighLightColorSelectedHot: TColor;
    procedure OnBackGroundChanged(Sender: TObject);
    procedure SetBackGround(const Value: TGradientBackground);
    procedure SetBorderColor(const Value: TColor);
    procedure SetBorderColorDisabled(const Value: TColor);
    procedure SetBorderColorSelected(const Value: TColor);
    procedure SetBorderColorSelectedHot(const Value: TColor);
    procedure SetColor(const Value: TColor);
    procedure SetColorDisabled(const Value: TColor);
    procedure SetColorDisabledTo(const Value: TColor);
    procedure SetColorHot(const Value: TColor);
    procedure SetColorHotTo(const Value: TColor);
    procedure SetColorMirror(const Value: TColor);
    procedure SetColorMirrorDisabled(const Value: TColor);
    procedure SetColorMirrorDisabledTo(const Value: TColor);
    procedure SetColorMirrorHot(const Value: TColor);
    procedure SetColorMirrorHotTo(const Value: TColor);
    procedure SetColorMirrorSelected(const Value: TColor);
    procedure SetColorMirrorSelectedTo(const Value: TColor);
    procedure SetColorMirrorTo(const Value: TColor);
    procedure SetColorSelected(const Value: TColor);
    procedure SetColorSelectedTo(const Value: TColor);
    procedure SetColorTo(const Value: TColor);
    procedure SetGradient(const Value: TGDIPGradient);
    procedure SetGradientDisabled(const Value: TGDIPGradient);
    procedure SetGradientHot(const Value: TGDIPGradient);
    procedure SetGradientMirror(const Value: TGDIPGradient);
    procedure SetGradientMirrorDisabled(const Value: TGDIPGradient);
    procedure SetGradientMirrorHot(const Value: TGDIPGradient);
    procedure SetGradientMirrorSelected(const Value: TGDIPGradient);
    procedure SetGradientSelected(const Value: TGDIPGradient);
    procedure SetTextColor(const Value: TColor);
    procedure SetTextColorDisabled(const Value: TColor);
    procedure SetTextColorHot(const Value: TColor);
    procedure SetTextColorSelected(const Value: TColor);
    procedure SetBorderColorDown(const Value: TColor);
    procedure SetFont(const Value: TFont);
    procedure SetSystemFont(const Value: boolean);
  protected
    procedure Changed;
    property BackGround: TGradientBackground read FBackGround write SetBackGround;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  published
    property BorderColor: TColor read FBorderColor write SetBorderColor;
    property BorderColorHot: TColor read FBorderColorHot write FBorderColorHot;
    property BorderColorSelected: TColor read FBorderColorSelected write SetBorderColorSelected;
    property BorderColorSelectedHot: TColor read FBorderColorSelectedHot write SetBorderColorSelectedHot;
    property BorderColorDisabled: TColor read FBorderColorDisabled write SetBorderColorDisabled;
    property BorderColorDown: TColor read FBorderColorDown write SetBorderColorDown;
    property Color: TColor read FColor write SetColor;
    property ColorTo: TColor read FColorTo write SetColorTo;
    property ColorSelected: TColor read FColorSelected write SetColorSelected;
    property ColorSelectedTo: TColor read FColorSelectedTo write SetColorSelectedTo;
    property ColorDisabled: TColor read FColorDisabled write SetColorDisabled;
    property ColorDisabledTo: TColor read FColorDisabledTo write SetColorDisabledTo;
    property ColorHot: TColor read FColorHot write SetColorHot;
    property ColorHotTo: TColor read FColorHotTo write SetColorHotTo;
    property ColorMirror: TColor read FColorMirror write SetColorMirror;
    property ColorMirrorTo: TColor read FColorMirrorTo write SetColorMirrorTo;
    property ColorMirrorHot: TColor read FColorMirrorHot write SetColorMirrorHot;
    property ColorMirrorHotTo: TColor read FColorMirrorHotTo write SetColorMirrorHotTo;
    property ColorMirrorSelected: TColor read FColorMirrorSelected write SetColorMirrorSelected;
    property ColorMirrorSelectedTo: TColor read FColorMirrorSelectedTo write SetColorMirrorSelectedTo;
    property ColorMirrorDisabled: TColor read FColorMirrorDisabled write SetColorMirrorDisabled;
    property ColorMirrorDisabledTo: TColor read FColorMirrorDisabledTo write SetColorMirrorDisabledTo;
    property Font: TFont read FFont write SetFont;
    property Gradient: TGDIPGradient read FGradient write SetGradient;
    property GradientMirror: TGDIPGradient read FGradientMirror write SetGradientMirror;
    property GradientHot: TGDIPGradient read FGradientHot write SetGradientHot;
    property GradientMirrorHot: TGDIPGradient read FGradientMirrorHot write SetGradientMirrorHot;
    property GradientSelected: TGDIPGradient read FGradientSelected write SetGradientSelected;
    property GradientMirrorSelected: TGDIPGradient read FGradientMirrorSelected write SetGradientMirrorSelected;
    property GradientDisabled: TGDIPGradient read FGradientDisabled write SetGradientDisabled;
    property GradientMirrorDisabled: TGDIPGradient read FGradientMirrorDisabled write SetGradientMirrorDisabled;
    property SystemFont: boolean read FSystemFont write SetSystemFont default true;    
    property TextColor: TColor read FTextColor write SetTextColor;
    property TextColorHot: TColor read FTextColorHot write SetTextColorHot;
    property TextColorSelected: TColor read FTextColorSelected write SetTextColorSelected;
    property TextColorDisabled: TColor read FTextColorDisabled write SetTextColorDisabled;
    property ShadowColor: TColor read FShadowColor write FShadowColor;
    property HighLightColor: TColor read FHighLightColor write FHighLightColor;
    property HighLightColorHot: TColor read FHighLightColorHot write FHighLightColorHot;
    property HighLightColorSelected: TColor read FHighLightColorSelected write FHighLightColorSelected;
    property HighLightColorSelectedHot: TColor read FHighLightColorSelectedHot write FHighLightColorSelectedHot;
    property HighLightColorDown: TColor read FHighLightColorDown write FHighLightColorDown;
  end;

  TTabAppearance = class(TCustomTabAppearance)
  private
  protected
  public
  published
    property BackGround;
  end;

  TATBTabScroller = class(TObject)
  private
    FMin: integer;
    FMax: integer;
    FPosition: integer;
    FVisible: Boolean;
    procedure SetMax(const Value: integer);
    procedure SetMin(const Value: integer);
    procedure SetPosition(const Value: integer);
    procedure SetVisible(const Value: Boolean);
  protected
  public
    constructor Create;
    function CanGoForward: Boolean;
    function CanGoBack: Boolean;
    property Min: integer read FMin write SetMin;
    property Max: integer read FMax write SetMax;
    property Position: integer read FPosition write SetPosition;
    property Visible: Boolean read FVisible write SetVisible;
  end;

  TTabGroupItem = class(TCollectionItem)
  private
    FCaption: TCaption;
    FImageIndex: Integer;
    FTabIndexStart: Integer;
    FTabIndexEnd: Integer;
    FWideCaption: widestring;
    FDefaultAppearance: Boolean;
    FGroupAppearance: TGroupAppearance;
    FCaptionAlignment: TAlignment;
    procedure OnGroupAppearanceChanged(Sender: TObject);
    procedure SetCaption(const Value: TCaption);
    procedure SetImageIndex(const Value: Integer);
    procedure SetTabIndexEnd(const Value: Integer);
    procedure SetTabIndexStart(const Value: Integer);
    procedure SetDefaultAppearance(const Value: Boolean);
    procedure SetGroupAppearance(const Value: TGroupAppearance);
    procedure SetCaptionAlignment(const Value: TAlignment);
    procedure SetWideCaption(const Value: widestring);
  protected
  public
    constructor Create(Collection: TCollection); override;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
    property WideCaption: widestring read FWideCaption write SetWideCaption;
  published
    property Caption: TCaption read FCaption write SetCaption;
    property CaptionAlignment: TAlignment read FCaptionAlignment write SetCaptionAlignment;
    property DefaultAppearance: Boolean read FDefaultAppearance write SetDefaultAppearance;
    property ImageIndex: Integer read FImageIndex write SetImageIndex;
    property TabIndexStart: Integer read FTabIndexStart write SetTabIndexStart;
    property TabIndexEnd: Integer read FTabIndexEnd write SetTabIndexEnd;
    property GroupAppearance: TGroupAppearance read FGroupAppearance write SetGroupAppearance;
  end;

  TTabGroups = class(TCollection)
  private
    FOwner: TAdvToolBarPager;
    {$IFNDEF DELPHI6_LVL}
    FMyOwner: TPersistent;
    {$ENDIF}
    FOnChange: TNotifyEvent;
    function GetItem(Index: Integer): TTabGroupItem;
    procedure SetItem(Index: Integer; const Value: TTabGroupItem);
  protected
    procedure UpdateChange;
  public
    constructor Create(AOwner: TAdvToolBarPager);
    property Items[Index: Integer]: TTabGroupItem read GetItem write SetItem; default;
    function Add: TTabGroupItem;
    function Insert(Index: Integer): TTabGroupItem;
    function GetOwner: TPersistent; override;
    {$IFNDEF DELPHI6_LVL}
    property Owner: TPersistent read FMyOwner;
    {$ENDIF}
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;

  TAdvPageScrollButton = class(TCustomControl)
  private
    FMouseEnter: Boolean;
    FOnMouseLeave: TNotifyEvent;
    FOnMouseEnter: TNotifyEvent;
    FAppearance: TGlowButtonAppearance;
    FTransparent: Boolean;
    FButtonPosition: TButtonPosition;
    FMouseDown: Boolean;
    FScrollArrow: TScrollArrow;

    procedure AppearanceChanged(Sender: TObject);
    procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW;
    procedure WMLButtonDblClk(var Message: TWMLButtonDown); message WM_LBUTTONDBLCLK;
    procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
    procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
    procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
    procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
    procedure CMSysColorChange(var Message: TMessage); message CM_SYSCOLORCHANGE;
    procedure WMEraseBkGnd(var Message: TWMEraseBkGnd); message WM_ERASEBKGND;
    procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure SetAppearance(const Value: TGlowButtonAppearance);
    procedure SetTransparent(const Value: Boolean);
    procedure SetButtonPosition(const Value: TButtonPosition);
    procedure SetScrollArrow(const Value: TScrollArrow);
  protected
    procedure SetParent(AParent: TWinControl); override;
    procedure Loaded; override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure Paint; override;
    procedure Notification(AComponent: TComponent; AOperation: TOperation); override;

    // published
    property Appearance: TGlowButtonAppearance read FAppearance write SetAppearance;
    property Enabled;
    property Font;
    property Position: TButtonPosition read FButtonPosition write SetButtonPosition default bpStandalone;
    property Transparent: Boolean read FTransparent write SetTransparent default false;
    property ScrollArrow: TScrollArrow read FScrollArrow write SetScrollArrow;
    property Visible;
    property OnClick;
    property OnDblClick;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
    property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Click; override;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
  end;

  TAdvPage = class(TCustomControl)
  private
    FAdvToolBars: TDbgList;
    FTabVisible: Boolean;
    FAdvToolBarPager: TAdvToolBarPager;
    FCaption: TCaption;
    FWideCaption: widestring;
    FTabEnabled: Boolean;
    FImageIndex: Integer;
    FAutoPosition: Boolean;
    FUpdatingATBPosition: Boolean;
    FTimer: TTimer;
    FTimeInc: Integer;
    FStepHover: Integer;
    FStepPush: Integer;
    FGlowState: TGlowState;  //TTabGlowState
    FTabHint: string;
    FOfficeHint: TAdvHintInfo;
    FUpdatingParent: Boolean;
    FShortCutHint: TShortCutHintWindow;
    FShortCutHintPos: TShortCutHintPos;
    FShortCutHintText: string;
    FToolBarShortCutShowing: Boolean;
    FShortCutChars: String;
    FToolBarScroller: TATBTabScroller;
    FScrolling: Boolean;
    FLeftATBIndex: Integer;
    FLeftScrollBtn: TAdvPageScrollButton;
    FRightScrollBtn: TAdvPageScrollButton;
    FTabWidth: Integer;
    FTabLeft: Integer;
    FTabClientWidth: Integer;
    FTabRealClientWidth: Integer;
    FOldWidth: Integer;
    FSelfClone: TAdvPage;
    FCloning: Boolean;
    FOldAutoPosition: Boolean;
    procedure TimerProc(Sender: TObject);
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
    procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED;
    procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED;
    procedure CMControlChange(var Message: TCMControlChange); message CM_CONTROLCHANGE;
    procedure CMControlListChange(var Message: TCMControlListChange); message CM_CONTROLLISTCHANGE;
    procedure WMEraseBkGnd(var Message: TWMEraseBkGnd); message WM_ERASEBKGND;
    function GetAdvToolBarCount: integer;
    function GetAdvToolBars(index: integer): TAdvToolBar;
    procedure SetAdvToolBarPager(const Value: TAdvToolBarPager);
    procedure SetTabVisible(const Value: Boolean);
    procedure SetCaption(const Value: TCaption);
    procedure SetWideCaption(const Value: widestring);
    procedure SetTabEnabled(const Value: Boolean);
    procedure SetImageIndex(const Value: Integer);
    procedure SetAutoPosition(const Value: Boolean);
    procedure SetOfficeHint(const Value: TAdvHintInfo);
    function GetPageIndex: Integer;
    procedure SetPageIndex(const Value: Integer);
    procedure SetTabLeft(const Value: Integer);
    function GetTabWidth: Integer;
  protected
    procedure AlignControls(AControl: TControl; var ARect: TRect); override;
    procedure Loaded; override;
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure SetParent(AParent: TWinControl); override;
    procedure Paint; override;
    procedure ReadState(Reader: TReader); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;

    procedure GetSequencialToolBarList(ATBList: TDbgList);

    procedure UpdateAdvToolBarsPosition;

    procedure InvalidateAllAdvToolBars;

    procedure ShowShortCutHintOfAllToolBars;
    procedure HideShortCutHintOfAllToolBars;
    function GetFirstToolBar(Visible: Boolean): TAdvToolBar;
    function HasShortCut(aShortCut: String): Boolean;

    function RealIndexToVisIndex(ATBIndex: Integer): Integer;
    function VisIndexToRealIndex(ATBIndex: Integer): Integer;
    function VisibleToolBarCount: Integer;

    function ALLATBSmallestVariant: Boolean;
    procedure IncreaseToolBarSize;
    procedure DecreaseToolBarSize;

    procedure InitializeScroller;
    procedure UpdateScroller;
    function ScrollPageATBVisibleCount(AIndex: Integer; GoForward: Boolean): Integer;
    procedure ChangeLeftATBIndexTo(Value: Integer);
    function ScrollToolBars(Value: Integer): Integer;
    procedure InvalidateScrollBtns;
    procedure OnScrollLeftClick(Sender: TObject);
    procedure OnScrollRightClick(Sender: TObject);
    procedure ScrollInView(ATBIndex: Integer);

    function IsGroupTab: Boolean;

    function CreateClone(ParntWin: TWinControl): TAdvPage;
    procedure DestroyClone;
    procedure PopulateClone;
    procedure UnPopulateClone;

    property TabWidth: Integer read GetTabWidth; // for internal use
    property TabClientWidth: Integer read FTabClientWidth write FTabClientWidth; // for internal use
    property TabRealClientWidth: Integer read FTabRealClientWidth write FTabRealClientWidth; // for internal use
    property TabLeft: Integer read FTabLeft write SetTabLeft; // for internal use
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;

    procedure ShowShortCutHint;
    procedure HideShortCutHint;

    function CreateAdvToolBar: TAdvToolBar;
    function AddAdvToolBar(ToolBar: TAdvToolBar): Integer;
    procedure InsertAdvToolBar(Index: integer; ToolBar: TAdvToolBar);
    procedure RemoveAdvToolBar(ToolBar: TAdvToolBar);
    function IndexOfAdvToolBar(ToolBar: TAdvToolBar): Integer;
    procedure MoveAdvToolBar(CurIndex, NewIndex: Integer);
    property WideCaption: widestring read FWideCaption write SetWideCaption;
  	procedure UpdateAllToolBars;
    property AdvToolBarCount: integer read GetAdvToolBarCount;
    property AdvToolBars[index: integer]: TAdvToolBar read GetAdvToolBars;
    property AdvToolBarPager: TAdvToolBarPager read FAdvToolBarPager write SetAdvToolBarPager;
  published
    property AutoPosition: Boolean read FAutoPosition write SetAutoPosition default true;
    property Caption: TCaption read FCaption write SetCaption;
    property ImageIndex: Integer read FImageIndex write SetImageIndex default -1;
    property TabHint: string read FTabHint write FTabHint;
    property TabVisible: Boolean read FTabVisible write SetTabVisible default true;
    property TabEnabled: Boolean read FTabEnabled write SetTabEnabled default true;
    property ParentShowHint;
    property ShowHint;
    property OfficeHint: TAdvHintInfo read FOfficeHint write SetOfficeHint;
    property PageIndex: Integer read GetPageIndex write SetPageIndex stored false;
    property ShortCutHint: string read FShortCutHintText write FShortCutHintText;
    property ShortCutHintPos: TShortCutHintPos read FShortCutHintPos write FShortCutHintPos default shpBottom;

    property OnDblClick;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
  end;

  TTabChangingEvent = procedure(Sender: TObject; FromPage, ToPage: Integer; var AllowChange: Boolean) of object;
  TTabClickEvent = procedure(Sender: TObject; Page: integer) of object;
  TTabGroupClickEvent = procedure(Sender: TObject; TabGroup: integer) of object;

  TAdvToolBarPager = class(TCustomControl)
  private
    FInternalToolBarStyler: TCustomAdvToolBarStyler;
    FToolBarStyler: TCustomAdvToolBarStyler;
    FCurrentToolBarStyler: TCustomAdvToolBarStyler;
    FOfficeToolBarStyler: TCustomAdvToolBarStyler;
    FDockAlign: TDockAlign;
    FOffSetY: integer;
    FOffSetX: integer;
    FAdvPages: TDbgList;
    FMinimumSize: Integer;
    //FLockHeight: Boolean;
    FPropertiesLoaded: Boolean;
    FShowNonSelectedTabs: Boolean;
    FTabSettings: TATBTabSettings;
    FCaption: TAdvPageCaption;
    FTabScroller: TATBTabScroller;
    FActivePageIndex: Integer;
    FHotPageIndex: Integer;
    FDownPageIndex: Integer;
    FOldHotPageIndex: Integer;
    FHintPageIndex: Integer;
    FImages: TCustomImageList;
    FDisabledImages: TCustomImageList;
    FScrollerHoverLeftBtn: Boolean;
    FScrollerDownLeftBtn: Boolean;
    FScrollerHoverRightBtn: Boolean;
    FScrollerDownRightBtn: Boolean;
    FShowTabHint: Boolean;
    FTabGroups: TTabGroups;
    FCanMove: Boolean;
    FCaptionButtons: TCaptionButtons;
    FCaptionCloseBtn: TAdvGlowButton;
    FCaptionMinBtn: TAdvGlowButton;
    FCaptionMaxBtn: TAdvGlowButton;
    FOnCloseButtonClick: TNotifyEvent;
    FOnMinButtonClick: TNotifyEvent;
    FOnMaxButtonClick: TNotifyEvent;
    FCaptionBtnImages: TImageList;
    FOnChange: TNotifyEvent;
    FOnChanging: TTabChangingEvent;
    FOldCapRightIndent: Integer;
    FOfficeHint: TAdvHintInfo;
    FAntiAlias: TAntiAlias;
    FPageRightMargin: Integer;
    FPageLeftMargin: Integer;
    FShortCutHintWinList: TDbgList;
    FFormWndProc: TWndMethod;
    FTabShortCutHintShowing: Boolean;
    FTabShortCutChars: String;
    FIOptionPicture: TGDIPPicture;
    FIOptionDisabledPicture: TGDIPPicture;
    FAutoMDIButtons: Boolean;
    FMDIButtonsVisible: Boolean;
    FMDIButtonsWidth: Integer;
    FMDIButtonsSpace: Integer;
    FMDICloseBtn: TAdvGlowButton;
    FMDIMinBtn: TAdvGlowButton;
    FMDIMaxBtn: TAdvGlowButton;
    FMDIChildForm: TCustomForm;
    FMDIBtnImages: TImageList;
    FExpanded: Boolean;
    FExpandedHeight: Integer;
    FShortCutTimer: TTimer;
    FALTDown: Boolean;
    FFormWindowState: TWindowState;
    //FUseRunTimeHeight: Boolean;
    FCurrentTabSpacing: Integer;
    FCurrentTabLeftMargin: Integer;
    FCurrentTabRightMargin: Integer;
    FCurrentGroupTabLeftMargin: Integer;
    FCurrentGroupTabRightMargin: Integer;
    FLeftScrollBtn: TAdvPageScrollButton;
    FRightScrollBtn: TAdvPageScrollButton;
    FStartTabIndex: Integer;
    FOnlyALT: Boolean;
    FQuickAccessToolBar: TAdvQuickAccessToolBar;
    FShortCutDelay: Cardinal;
    FDesignTime: boolean;
    FEnableWheel: boolean;
    FOnTabClick: TTabClickEvent;
    FOnTabDblClick: TTabClickEvent;
    FPersistence: TPersistence;
    FOldHeight: Integer;
    FOnTabGroupClick: TTabGroupClickEvent;
    FHideState: Boolean;
    FQATOldVisible: Boolean;
    FShapeBtnOldVisible: Boolean;
    FDblClickTimer: TTimer;
    FClickCount: Integer;
    FMinimizedRibbonWindow: TMinimizedRibbonWindow;
    FOnExpand: TNotifyEvent;
    FOnCollaps: TNotifyEvent;
    FNonActiveMouseWheelOnFocus: Boolean;
    FHidePagesOnDblClick: boolean;
    procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
    procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED;
    procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED;
    procedure CMControlChange(var Message: TCMControlChange); message CM_CONTROLCHANGE;
    procedure CMControlListChange(var Message: TCMControlListChange); message CM_CONTROLLISTCHANGE;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
    procedure CMDesignHitTest(var Msg: TCMDesignHitTest); message CM_DESIGNHITTEST;
    procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW;
    procedure WMNCHitTest(var Msg: TWMNCHitTest); message WM_NCHITTEST;
    procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
    procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
    procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY;
    procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
    procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED;
    procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
    procedure SubclassProc(var Msg: TMessage);
    procedure OnPersistenceChanged(Sender: TObject);
    procedure OnDblClickTimer(Sender: TObject);
    procedure OnFloatingRibbonWindowCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure OnFloatingRibbonWindowClose(Sender: TObject; var Action: TCloseAction);
    procedure OnRibbonWindowHide(Sender: TObject);
    procedure UpdateCaptionButtons(UpdateImage: Boolean);
    procedure UpdateShapeButton;
    procedure OnCaptionCloseBtnClick(Sender: TObject);
    procedure OnCaptionMaxBtnClick(Sender: TObject);
    procedure OnCaptionMinBtnClick(Sender: TObject);
    procedure OnTabGroupsChanged(Sender: TObject);
    procedure OnTabSettingsChanged(Sender: TObject);
    procedure OnCaptionChanged(Sender: TObject);
    procedure OnOptionPictureChanged(Sender: TObject);
    procedure OnShortCutTime(Sender: TObject);
    procedure OnMDICloseBtnClick(Sender: TObject);
    procedure OnMDIMaxBtnClick(Sender: TObject);
    procedure OnMDIMinBtnClick(Sender: TObject);
    procedure UpdateMDIButtonsShowing;
    procedure OnEnterTab(PageIndex: Integer);
    procedure OnExitTab(PageIndex: Integer);
    procedure SetPagePosition(AdvPage: TAdvPage);
    procedure SetAllPagesPosition;
    procedure SetToolBarStyler(const Value: TCustomAdvToolBarStyler);
    function GetAlign: TDockAlign;
    procedure SetAlign(const Value: TDockAlign);
    function GetAdvToolBarPageCount: integer;
    function GetAdvPages(index: integer): TAdvPage;
    function GetPopupMenuEx: TPopupMenu;
    procedure SetPopupMenuEx(const Value: TPopupMenu);
    procedure SetShowNonSelectedTabs(const Value: Boolean);
    function GetActivePage: TAdvPage;
    function GetActivePageIndex: Integer;
    procedure SetActivePage(const Value: TAdvPage);
    procedure SetActivePageIndex(const Value: Integer);
    procedure SetTabSettings(const Value: TATBTabSettings);
    procedure SetCaption(const Value: TAdvPageCaption);
    procedure SetImages(const Value: TCustomImageList);
    procedure SetDisabledImages(const Value: TCustomImageList);
    procedure SetTabGroups(const Value: TTabGroups);
    procedure SetCaptionButtons(const Value: TCaptionButtons);
    function GetVersion: string;
    procedure SetVersion(const Value: string);
    procedure SetOfficeHint(const Value: TAdvHintInfo);
    procedure SetAntiAlias(const Value: TAntiAlias);
    procedure SetPageLeftMargin(const Value: Integer);
    procedure SetPageRightMargin(const Value: Integer);
    procedure SetOptionPicture(const Value: TGDIPPicture);
    procedure SetOptionDisabledPicture(const Value: TGDIPPicture);
    procedure SetAutoMDIButtons(const Value: Boolean);
    procedure SetMDIButtonsVisible(const Value: Boolean);
    procedure SetExpanded(Value: Boolean);
    function GetTabsWidth(FromIndex, ToIndex: Integer): Integer;
    function GetLargestTabIndex(ConsiderGroupTabs: Boolean): Integer;
    function GetSmallestExpandableTabIndex(PriorityGroupTabs: Boolean): Integer;
    function ShouldDrawSeparator(PageIndex: Integer): Boolean;
    procedure SetShowQATBelow(const Value: Boolean);
    function GetShowQATBelow: Boolean;
    procedure SetPersistence(const Value: TPersistence);
    procedure SetHideState(const Value: Boolean);
  protected
    procedure AlignControls(AControl: TControl; var ARect: TRect); override;
    procedure Loaded; override;
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure SetParent(AParent: TWinControl); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure KeyDown(var Key: Word; Shift: TShiftState); override;
    procedure KeyUp(var Key: Word; Shift: TShiftState); override;
    procedure AdjustClientRect(var Rect: TRect); override;
    procedure DrawCaption;
    procedure DrawTab(PageIndex: Integer);
    procedure DrawAllTabs;
    procedure DrawTabScrollBtnLeft;
    procedure DrawTabScrollBtnRight;
    procedure DrawTabScrollButtons;
    procedure DrawTabGroups;
    procedure Paint; override;
    procedure WndProc(var Msg: TMessage); override;

    procedure SetAdvPageBounds(AdvPage: TAdvPage; var ALeft, ATop, AWidth, AHeight: Integer);

    function TabInDisplayRange(PageIndex: Integer): Boolean;

    procedure UpdateMe(PropID: integer);
    procedure ChangeActivePage(PageIndex: Integer);

    function GetRealTabWidth(TabIndex: Integer; var TabClientWidth: Integer): Integer;
    function AnyTabCanBeExpanded: Boolean;
    function TotalGroupTabsCanBeExpanded: Integer;
    function AnyTabCanBeShrunk(ConsiderGroupTabs: Boolean): Boolean;
    function AnyGroupTabCanBeExpanded: Boolean;
    function GetMinTabWidth: Integer;
    function GetTotalTabsWidth: Integer;
    procedure UpdateTabSizes;
    procedure ResetTabsPosition;
    procedure UpdateTabPosition(FromIndex, ToIndex: Integer); overload;
    procedure UpdateTabPosition; overload;
    procedure InitializeTabsSize;
    procedure InitializeTabWidth(TabIndex: Integer);

    procedure InitializeScroller;
    procedure UpdateTabScroller;
    function TabCountOnVisibleArea(TabIndex: Integer; GoForward: Boolean; var LastTabIndex: Integer): Integer;
    function VisibleTabCount(FromIndex, ToIndex: Integer): Integer; overload;
    function VisibleTabCount: Integer; overload;
    function GetFirstVisibleTabIndex: Integer;
    function GetLastVisibleTabIndex: Integer;
    procedure ChangeLeftTabIndexTo(Value: Integer);
    function ScrollTabsPage(Value: Integer): Integer;
    procedure InvalidateScrollBtns;
    procedure ScrollInView(TabIndex: Integer);
    procedure OnScrollLeftBtnClick(Sender: TObject);
    procedure OnScrollRightBtnClick(Sender: TObject);

    procedure ShowShortCutHintOfAllPages;
    procedure HideShortCutHintOfAllPages(ToolBarHint: Boolean = false);
    function CreateShortCutHintWin: TShortCutHintWindow;
    procedure DestroyShortCutHintWin(ShortCutWin: TShortCutHintWindow);

    function IsTabGroupVisible(GroupIndex: Integer): Boolean;
    function GroupOfTab(PageIndex: Integer): Integer;

    function CanShowTab(PageIndex: Integer): Boolean;

    procedure InvalidateActivePageAttachement;
    procedure InvalidateTab(PageIndex: Integer);
    function GetCaptionRect: TRect;
    function GetAvailableCaptionRect: TRect;
    function GetAdvPageRect: TRect;
    function GetTabsArea: TRect;
    function GetTabsRect: TRect;
    function GetTabVisibleRect(Page: TAdvPage): TRect; overload;
    function GetTabVisibleRect(PageIndex: Integer): TRect; overload;
    function GetTabRect(StartIndex, PageIndex: Integer; ConsiderTabScroller: Boolean): TRect;  overload;
    function GetTabRect(PageIndex: Integer): TRect;  overload;
    function GetTabRect(Page: TAdvPage): TRect; overload;
    function PTOnTab(X, Y: Integer): Integer;
    function PtOntTabGroup(X, Y: Integer): Integer;
    function GetTabScrollerRect: TRect;
    function GetTabScrollerLeftRect: TRect;
    function GetTabScrollerRightRect: TRect;
    function PtOnTabScrollLeftBtn(X, Y: integer): Boolean;
    function PtOnTabScrollRightBtn(X, Y: integer): Boolean;
    function GetTabGroupRect(GroupIndex: Integer; var LeftVisible, RightVisible: Boolean): TRect;
    function GetMDIButtonsRectRect: TRect;
    procedure UpdateMDIButtons(UpdateImage: Boolean);
    function GetCaptionButtonsRect: TRect;
    function MaxQATRect: TRect;
    function GetQATHeight: Integer;
    procedure CreateFloatingRibbon;
    procedure DestroyFloatingRibbon;
    procedure ShowFloatingRibbon;
    procedure HideFloatingRibbon;
    function IsFloatingRibbonShowing: Boolean;
    procedure HandleKey(Code: Word);

    property Align: TDockAlign read GetAlign write SetAlign default daTop;
    property MDIButtonsVisible: Boolean read FMDIButtonsVisible write SetMDIButtonsVisible;
    property CurrentToolBarStyler: TCustomAdvToolBarStyler read FCurrentToolBarStyler;
    property HideState: Boolean read FHideState write SetHideState default false;
    //property MinimumSize: Integer read FMinimumSize write SetMinimumSize;
    //property LockHeight: Boolean read FLockHeight write SetLockHeight;
    //property UseRunTimeHeight: Boolean read FUseRunTimeHeight write SetUseRunTimeHeight;
  public
    constructor Create(AOwner: TComponent); override;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure CreateWnd; override;
    destructor Destroy; override;
    procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
    procedure SetGlowSpeed(speed: integer);
    function GetVersionNr: integer;

    procedure ShowShortCutHint;
    procedure HideShortCutHint;

    procedure SaveState;
    procedure LoadState;

    procedure Expand;
    procedure Collaps;
    function AddAdvPage(AdvPage: TAdvPage): integer; overload;
    function AddAdvPage(PageCaption: TCaption): integer; overload;
    procedure RemoveAdvPage(AdvPage: TAdvPage);
    procedure MoveAdvPage(CurIndex, NewIndex: Integer);
    function FindNextPage(CurPage: TAdvPage; GoForward, CheckTabVisible: Boolean): TAdvPage;
    procedure SelectNextPage(GoForward: Boolean);
    function IndexOfPage(AdvPage: TAdvPage): Integer;
    property ActivePageIndex: Integer read GetActivePageIndex write SetActivePageIndex;
    property AdvPageCount: integer read GetAdvToolBarPageCount;
    property AdvPages[index: integer]: TAdvPage read GetAdvPages;
    procedure NextActivePage;
    procedure PrevActivePage;
    property ShowQATBelow: Boolean read GetShowQATBelow write SetShowQATBelow default false;
    property QuickAccessToolBar: TAdvQuickAccessToolBar read FQuickAccessToolBar;
    property Expanded: Boolean read FExpanded;
    property NonActiveMouseWheelOnFocus: Boolean read FNonActiveMouseWheelOnFocus write FNonActiveMouseWheelOnFocus default false;
  published
    property ActivePage: TAdvPage read GetActivePage write SetActivePage;
    property AntiAlias: TAntiAlias read FAntiAlias write SetAntiAlias default aaClearType;    
    property AutoMDIButtons: Boolean read FAutoMDIButtons write SetAutoMDIButtons default false;
    property CanMove: Boolean read FCanMove write FCanMove default False;
    property Caption: TAdvPageCaption read FCaption write SetCaption;
    property CaptionButtons: TCaptionButtons read FCaptionButtons write SetCaptionButtons;
    property Images: TCustomImageList read FImages write SetImages;
    property DisabledImages: TCustomImageList read FDisabledImages write SetDisabledImages;
    property HidePagesOnDblClick: boolean read FHidePagesOnDblClick write FHidePagesOnDblClick default true;
    property EnableWheel: boolean read FEnableWheel write FEnableWheel default true;
    property TabGroups: TTabGroups read FTabGroups write SetTabGroups;
    property TabSettings: TATBTabSettings read FTabSettings write SetTabSettings;
    property Persistence: TPersistence read FPersistence write SetPersistence;
    property PopupMenu: TPopupMenu read GetPopupMenuEx write SetPopupMenuEx;
    property ToolBarStyler: TCustomAdvToolBarStyler read FToolBarStyler write SetToolBarStyler;
    property ShowNonSelectedTabs: Boolean read FShowNonSelectedTabs write SetShowNonSelectedTabs default False;
    property ShowTabHint: Boolean read FShowTabHint write FShowTabHint default false;
    property ParentShowHint;
    property ShowHint;
    property OfficeHint: TAdvHintInfo read FOfficeHint write SetOfficeHint;
    property Version: string read GetVersion write SetVersion stored false;
    property PageLeftMargin: Integer read FPageLeftMargin write SetPageLeftMargin;
    property PageRightMargin: Integer read FPageRightMargin write SetPageRightMargin;
    property OptionPicture: TGDIPPicture read FIOptionPicture write SetOptionPicture;
    property OptionDisabledPicture: TGDIPPicture read FIOptionDisabledPicture write SetOptionDisabledPicture;
    property Visible;
    property TabOrder;
    property TabStop;
    property OnCloseButtonClick: TNotifyEvent read FOnCloseButtonClick write FOnCloseButtonClick;
    property OnMinButtonClick: TNotifyEvent read FOnMinButtonClick write FOnMinButtonClick;
    property OnMaxButtonClick: TNotifyEvent read FOnMaxButtonClick write FOnMaxButtonClick;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property OnChanging: TTabChangingEvent read FOnChanging write FOnChanging;
    property OnDblClick;
    property OnEnter;
    property OnExit;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnKeyDown;
    property OnKeyUp;
    property OnKeyPress;
    property OnTabClick: TTabClickEvent read FOnTabClick write FOnTabClick;
    property OnTabDblClick: TTabClickEvent read FOnTabDblClick write FOnTabDblClick;
    property OnTabGroupClick: TTabGroupClickEvent read FOnTabGroupClick write FOnTabGroupClick;
    property OnExpand: TNotifyEvent read FOnExpand write FOnExpand;
    property OnCollaps: TNotifyEvent read FOnCollaps write FOnCollaps;
  end;

  TAdvVistaButton = class(TGraphicControl)
  private
    FMouseEnter: Boolean;
    FOnMouseLeave: TNotifyEvent;
    FOnMouseEnter: TNotifyEvent;
    FAppearance: TGlowButtonAppearance;
    FTransparent: Boolean;
    FButtonPosition: TButtonPosition;
    FMouseDown: Boolean;
    FScrollArrow: TScrollArrow;
    FArrowStyle: TArrowStyle;
    FDown: Boolean;
    procedure AppearanceChanged(Sender: TObject);
    procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW;
    procedure WMLButtonDblClk(var Message: TWMLButtonDown); message WM_LBUTTONDBLCLK;
    procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
    procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
    procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
    procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
    procedure CMSysColorChange(var Message: TMessage); message CM_SYSCOLORCHANGE;
    procedure WMEraseBkGnd(var Message: TWMEraseBkGnd); message WM_ERASEBKGND;
    procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure SetAppearance(const Value: TGlowButtonAppearance);
    procedure SetTransparent(const Value: Boolean);
    procedure SetButtonPosition(const Value: TButtonPosition);
    procedure SetScrollArrow(const Value: TScrollArrow);
    procedure SetArrowStyle(const Value: TArrowStyle);
    procedure SetDown(const Value: Boolean);
  protected
    procedure SetParent(AParent: TWinControl); override;
    procedure Loaded; override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure Paint; override;
    procedure Notification(AComponent: TComponent; AOperation: TOperation); override;

    // published
    property Appearance: TGlowButtonAppearance read FAppearance write SetAppearance;
    property Down: Boolean read FDown write SetDown;
    property Enabled;
    property Font;
    property Position: TButtonPosition read FButtonPosition write SetButtonPosition default bpStandalone;
    property Transparent: Boolean read FTransparent write SetTransparent default false;
    property ScrollArrow: TScrollArrow read FScrollArrow write SetScrollArrow;
    property ArrowStyle: TArrowStyle read FArrowStyle write SetArrowStyle;
    property Visible;
    property OnClick;
    property OnDblClick;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
    property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Click; override;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
  end;

  TAdvCustomQuickAccessToolBar = class(TCustomControl)
  private
    FFullSize: Boolean;
    FShowCustomizeOption: Boolean;
    FCtrlList: TDbgList;
    FHiddenCtrlList: TDbgList;
    FInternalUpdatingControlPos: Boolean;
    FInternalUpdatingSize: Boolean;
    FCustomizeButton: TAdvVistaButton;
    FScrollButton: TAdvVistaButton;
    FOverflowWindow: TOptionSelectorWindow;
    FOverflowWindowPanel: TControlSelectorPanel;
    FDisabledImages: TCustomImageList;
    FImages: TCustomImageList;
    FButtonWidth: Integer;
    FButtonGap: Integer;
    FDropDownPopupMenu: TPopupMenu;
    FUpdateCount: Integer;
    FCustomizeHint: string;
    FOnCustomizeClick: TNotifyEvent;
    procedure WMEraseBkGnd(var Msg: TMessage); message WM_ERASEBKGND;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
    procedure CMControlChange(var Message: TCMControlChange); message CM_CONTROLCHANGE;
    procedure OnCustomizeButtonClick(Sender: TObject);
    procedure OnScrollButtonClick(Sender: TObject);
    procedure OnScrollButtonDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure SetFullSize(const Value: Boolean);
    procedure SetShowCustomizeOption(const Value: Boolean);
    function GetCustomAdvToolBarStyler: TCustomAdvToolBarStyler;
    procedure SetDisabledImages(const Value: TCustomImageList);
    procedure SetImages(const Value: TCustomImageList);
    function GetShowScrollButton: Boolean;
    procedure SetShowScrollButton(const Value: Boolean);
    procedure SetCustomizeHint(const Value: string);
  protected
    procedure AlignControls(AControl: TControl; var ARect: TRect); override;
    procedure Loaded; override;
    procedure UpdateMe(PropID: integer);
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure SetParent(AParent: TWinControl); override;
    procedure Paint; override;

    procedure UpdateAllGlowButtons;

    procedure ShowShortCutHintOfButtons;
    procedure HideShortCutHintOfButtons;
    function HasShortCut(aShortCut: String; var VisibleHintCount: Integer): Boolean;

    procedure UpdateControlList;
    procedure GetSequentialControlList(aList: TDbgList);
    procedure UpdateControlsPos(SizeUpdate: Boolean = False);
    procedure UpdateControlsVisiblity;
    function CanShrink: Integer;
    function CanExpand: Integer;
    function TotalCtrlsWidth: Integer;
    function MaxWidth: Integer;
    function MinWidth: Integer;
    procedure UpdateSize;

    procedure InitializeOverflowWindow;
    procedure ShowOverflowWindow(X, Y: Integer; ForcePoint: Boolean=True);
    procedure HideOverflowWindow;
    procedure OnOverflowWindowHide(Sender: TObject);

    function GetMyClientRect: TRect;
    function GetDrawingRect: TRect;
    function GetLeftMargin: Integer;
    function GetRightMargin: Integer;
    function GetCustomizeBtnRect: TRect;

    property CurrentToolBarStyler: TCustomAdvToolBarStyler read GetCustomAdvToolBarStyler;
    property ShowScrollButton: Boolean read GetShowScrollButton write SetShowScrollButton;

    property FullSize: Boolean read FFullSize write SetFullSize default false;
    property ShowCustomizeOption: Boolean read FShowCustomizeOption write SetShowCustomizeOption;
    property Images: TCustomImageList read FImages write SetImages;
    property DisabledImages: TCustomImageList read FDisabledImages write SetDisabledImages;
    property DropDownPopupMenu: TPopupMenu read FDropDownPopupMenu write FDropDownPopupMenu;
    property CustomizeHint: string read FCustomizeHint write SetCustomizeHint;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
    procedure Update; override;
    procedure AddToolBarControl(AControl: TControl);

    procedure BeginUpdate;
    procedure EndUpdate;
    property OnCustomizeClick: TNotifyEvent read FOnCustomizeClick write FOnCustomizeClick;
  published

  end;

  TAdvQuickAccessToolBar = class(TAdvCustomQuickAccessToolBar)
  published
    property CustomizeHint;
    property DisabledImages;
    property Images;
    property ShowCustomizeOption;
    property DropDownPopupMenu;
    property PopupMenu;
    property ShowHint;
    property OnCustomizeClick;
  end;

  TAdvGlowMenuButton = class(TAdvCustomGlowButton)
  private
  protected
    function IsMenuButton: Boolean; override;
  public
    constructor Create(AOwner: TComponent); override;
  published
    //property AllowAllUp;
    property Appearance;
    //property Down;
    property Enabled;
    //property GroupIndex;
    property Layout;
    //property Style;
    property DropDownButton;
    property DropDownPosition;
    property DropDownSplit;
    property DropDownMenu;
    property OnDropDown;
  end;

  TCompactWindow = class(TCustomForm)
  private
    FAdvToolBar: TAdvCustomToolBar;
    FHideOnDeActivate: Boolean;
    FOwner: TComponent;
    FHideTimer: TTimer;
    FDropDownButton: TAdvGlowButton;
    procedure WMActivate(var Message: TWMActivate); message WM_ACTIVATE;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
    procedure HideTimerOnTime(Sender: TObject);
    function GetHideOnDeActivate: Boolean; 
  protected
    procedure Paint; override;
    function GetParentWnd: HWnd;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure DoHide; override;
    procedure SetCornersRounded; 
    property HideOnDeActivate: Boolean read GetHideOnDeActivate write FHideOnDeActivate;
  public
    constructor Create(AOwner: TComponent); override;
    constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
    destructor Destroy; override;
    procedure SetWindowSize;
  published
(*{$IFDEF TMSDOTNET}
    property OnHide;
{$ENDIF} *)
    property AdvToolBar: TAdvCustomToolBar read FAdvToolBar write FAdvToolBar;
    property DropDownButton: TAdvGlowButton read FDropDownButton write FDropDownButton;
  end;

  TMinimizedRibbonWindow = class(TCustomForm)
  private
    FHideOnDeActivate: Boolean;
    FOwner: TComponent;
    FHideTimer: TTimer;
    FAdvToolBarPager: TAdvToolBarPager;
    FAdvPage: TAdvPage;
    procedure WMActivate(var Message: TWMActivate); message WM_ACTIVATE;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
    procedure HideTimerOnTime(Sender: TObject);
    function GetHideOnDeActivate: Boolean;
  protected
    procedure Paint; override;
    function GetParentWnd: HWnd;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure DoHide; override;
    property HideOnDeActivate: Boolean read GetHideOnDeActivate write FHideOnDeActivate;
  public
    constructor Create(AOwner: TComponent); override;
    constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
    destructor Destroy; override;
    procedure SetWindowSize;
    property AdvToolBarPager: TAdvToolBarPager read FAdvToolBarPager write FAdvToolBarPager;
    property AdvPage: TAdvPage read FAdvPage write FAdvPage;
  end;

  TAdvToolBarForm = class(TForm)
  private
    { Private declarations }
    procedure WMGetMinMaxInfo(var Msg: TMessage); message WM_GETMINMAXINFO;
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
  protected
    //procedure PaintNCFrame(ACanvas : TCanvas);
    function GetClientRect: TRect; override;
    procedure AdjustClientRect(var Rect: TRect); override;  
    procedure CreateParams(var Params: TCreateParams); override;
    procedure Paint; override;
  end;

procedure DrawVerticalText(Canvas: TCanvas; Text: String; TextP: TPoint);


function ColorToARGB(Color: TColor): ARGB;
procedure DrawGDIPArc(graphics: TGPGraphics; Pen: TGPPen; X,Y,Width,Height: integer; StartAngle, SweepAngle: Single; closed : boolean = true);

{
procedure DrawVistaGradient(Canvas: TCanvas; r: TRect; CFU, CTU, CFB, CTB, PC: TColor;
   GradientU,GradientB: TGDIPGradient; Caption:string; AFont: TFont;
   Images: TImageList; ImageIndex: integer; EnabledImage: Boolean; Layout: TButtonLayout;
   DropDownButton: Boolean; DrawDwLine: Boolean; Enabled: Boolean; Focus: Boolean; DropDownPos: TDropDownPosition;
   AntiAlias: TAntiAlias; RoundEdges: Boolean); overload;
}


var
  SHORTCUT_DELAY: Cardinal = 700;
  CANCAPTURE: Boolean = True;

implementation

uses
  CustomizerU, MultiMon, AdvToolBarStylers
  {$IFNDEF TMS_STD}
  {$IFDEF DELPHI6_LVL}
  , VDBConsts
  {$ELSE}
  , DBConsts
  {$ENDIF}
  {$ENDIF}
  ;

const
  GDIP_NOWRAP = 4096;
  DBLCLICK_DELAY = 600;
  PAGEGRAD_HEIGHT = 22;

type
  PDockInfo = ^TDockInfo;
  TDockInfo = record
    Dock: TAdvDockPanel;
    DockRect: TRect;
  end;

  TButtonDisplay = (bdNone, bdButton, bdDropDown);

//----------------------------------------------------------------- DrawGradient

procedure DrawGradient(Canvas: TCanvas; FromColor, ToColor: TColor; Steps: Integer; R: TRect; Direction: Boolean);
var
  diffr, startr, endr: Integer;
  diffg, startg, endg: Integer;
  diffb, startb, endb: Integer;
  rstepr, rstepg, rstepb, rstepw: Real;
  i, stepw: Word;

begin
  if Direction then
    R.Right := R.Right - 1
  else
    R.Bottom := R.Bottom - 1;

  if Steps = 0 then
    Steps := 1;

  FromColor := ColorToRGB(FromColor);
  ToColor := ColorToRGB(ToColor);

  startr := (FromColor and $0000FF);
  startg := (FromColor and $00FF00) shr 8;
  startb := (FromColor and $FF0000) shr 16;
  endr := (ToColor and $0000FF);
  endg := (ToColor and $00FF00) shr 8;
  endb := (ToColor and $FF0000) shr 16;

  diffr := endr - startr;
  diffg := endg - startg;
  diffb := endb - startb;

  rstepr := diffr / steps;
  rstepg := diffg / steps;
  rstepb := diffb / steps;

  if Direction then
    rstepw := (R.Right - R.Left) / Steps
  else
    rstepw := (R.Bottom - R.Top) / Steps;

  with Canvas do
  begin
    for i := 0 to steps - 1 do
    begin
      endr := startr + Round(rstepr * i);
      endg := startg + Round(rstepg * i);
      endb := startb + Round(rstepb * i);
      stepw := Round(i * rstepw);
      Pen.Color := endr + (endg shl 8) + (endb shl 16);
      Brush.Color := Pen.Color;
      if Direction then
        Rectangle(R.Left + stepw, R.Top, R.Left + stepw + Round(rstepw) + 1, R.Bottom)
      else
        Rectangle(R.Left, R.Top + stepw, R.Right, R.Top + stepw + Round(rstepw) + 1);
    end;
  end;
end;

//------------------------------------------------------------------------------

function BlendColor(Col1,Col2:TColor; BlendFactor:Integer): TColor;
var
  r1,g1,b1: Integer;
  r2,g2,b2: Integer;

begin
  if BlendFactor >= 100 then
  begin
    Result := Col1;
    Exit;
  end;
  if BlendFactor <= 0 then
  begin
    Result := Col2;
    Exit;
  end;

  Col1 := Longint(ColorToRGB(Col1));
  r1 := GetRValue(Col1);
  g1 := GetGValue(Col1);
  b1 := GetBValue(Col1);

  Col2 := Longint(ColorToRGB(Col2));
  r2 := GetRValue(Col2);
  g2 := GetGValue(Col2);
  b2 := GetBValue(Col2);

  r1 := Round( BlendFactor/100 * r1 + (1 - BlendFactor/100) * r2);
  g1 := Round( BlendFactor/100 * g1 + (1 - BlendFactor/100) * g2);
  b1 := Round( BlendFactor/100 * b1 + (1 - BlendFactor/100) * b2);

  Result := RGB(r1,g1,b1);
end;

//------------------------------------------------------------------------------

procedure Draw3DLine(Canvas: TCanvas; FromPoint, ToPoint: TPoint; Embossed: Boolean; VerticalLine: Boolean = true);
begin
  with Canvas do
  begin
    if Embossed then
      Pen.Color := clWhite
    else
      Pen.Color := clBtnShadow;

    if VerticalLine then
    begin
      MoveTo(FromPoint.X - 1, FromPoint.Y - 1);
      LineTo(ToPoint.X - 1, ToPoint.Y);
      LineTo(ToPoint.X + 1, ToPoint.Y);
    end
    else
    begin
      MoveTo(FromPoint.X - 1, FromPoint.Y + 1);
      LineTo(FromPoint.X - 1, FromPoint.Y - 1);
      LineTo(ToPoint.X + 1, ToPoint.Y - 1);
    end;

    if Embossed then
      Pen.Color := clBtnShadow
    else
      Pen.Color := clWhite;

    if VerticalLine then
    begin
      MoveTo(ToPoint.X + 1, ToPoint.Y);
      LineTo(ToPoint.X + 1, FromPoint.Y);
      LineTo(ToPoint.X - 1, FromPoint.Y);
    end
    else
    begin
      MoveTo(ToPoint.X + 1, ToPoint.Y - 1);
      LineTo(ToPoint.X + 1, ToPoint.Y + 1);
      LineTo(FromPoint.X, FromPoint.Y + 1);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure DrawVerticalText(Canvas: TCanvas; Text: String; TextP: TPoint);
var
  i, ci, j: Integer;
  Lp1, Lp2: TPoint;
  S: String;
begin
  // First find char to be underlined
  ci := -1;
  i := 1;
  j := 1;
  while i <= length(Text) do
  begin
    if Text[i] = '&' then
    begin
      if i <= length(Text)-1 then
        if Text[i+1] = '&' then
        begin
          inc(i);
        end
        else
        begin
          ci := j;
          dec(j);
        end;
    end;
    inc(i);
    inc(j);
  end;
  
  // now remove double occurance of '&&' to '&'
  Text := StripHotkey(Text);
 {
  i := 1;
  while i <= length(Text) do
  begin
    if Text[i] = '&' then
    begin
      if i < length(Text)-1 then
        if Text[i+1] = '&' then
        begin
          //ci := -1;
          inc(i);
        end
        else
          ci := i +1;
    end;
    inc(i);
  end;
  }

  Canvas.TextOut(TextP.X, Textp.Y, Text);

  // draw underline
  if ci >= 0 then
  begin
    j := Canvas.TextHeight(Text);
    Lp1.X := TextP.X - j+1;
    Lp2.X := Lp1.X;
    S := '';
    i := 1;
    while i < ci do
    begin
      S := S + Text[i];
      inc(i);
    end;
    Lp1.Y := TextP.Y + Canvas.TextWidth(S);
    Lp2.Y := Lp1.Y + Canvas.TextWidth(Text[ci]);

    Canvas.Pen.Color := Canvas.Font.Color;
    Canvas.MoveTo(Lp1.X, Lp1.Y);
    Canvas.LineTo(Lp2.X, Lp2.Y);
  end;
end;

//------------------------------------------------------------------------------

procedure CenterRect(var Rect: TRect; const Width, Height: Integer);
begin
  with Rect do
  begin
    Right := (Left + Right + Width) div 2;
    Bottom := (Top + Bottom + Height) div 2;
    Left := Right - Width;
    Top := Bottom - Height;
  end;
end;

{
function GetUniqueName(AOwner: TComponent; S: string): string;
var
  i: integer;
  Found: boolean;
begin
  Result := S;
  i := 1;
  Found := false;
  while not found do
  begin
    Result := S + inttostr(i);
    if AOwner.FindComponent(Result) = nil then
      Found := true;
    inc(i);
  end;
end;
}

//------------------------------------------------------------------------------

function DarkenColor(Color: TColor; Perc: integer): TColor;
var
  r,g,b: longint;
  l: longint;
begin
  l := ColorToRGB(Color);
  r := ((l AND $FF0000) shr 16) and $FF;
  g := ((l AND $FF00) shr 8) and $FF;
  b := (l AND $FF);

  r := Round(r * (100 - Perc)/100);
  g := Round(g * (100 - Perc)/100);
  b := Round(b * (100 - Perc)/100);

  Result := (r shl 16) or (g shl 8) or b;
end;

//------------------------------------------------------------------------------

function ColorToARGB(Color: TColor): ARGB;
var
  c: TColor;
begin
  c := ColorToRGB(Color);
  Result := ARGB( $FF000000 or ((DWORD(c) and $FF) shl 16) or ((DWORD(c) and $FF00) or ((DWORD(c) and $ff0000) shr 16)));
end;

//------------------------------------------------------------------------------

procedure DrawGDIPLine(graphics: TGPGraphics; Pen: TGPPen; X,Y,Width,Height: integer);
var
  path:TGPGraphicsPath;
begin
  path := TGPGraphicsPath.Create;
  path.AddLine(X, Y, X + Width, Y + Height);
  path.CloseFigure;
  graphics.DrawPath(pen, path);
  path.Free;
end;

//------------------------------------------------------------------------------

procedure DrawGDIPArc(graphics: TGPGraphics; Pen: TGPPen; X,Y,Width,Height: integer; StartAngle, SweepAngle: Single; closed : boolean = true);
var
  path:TGPGraphicsPath;
begin
  path := TGPGraphicsPath.Create;
  path.AddArc(X, Y, Width, Height, StartAngle, SweepAngle);
  if closed then
    path.CloseFigure;
  graphics.DrawPath(pen, path);
  path.Free;
end;

//------------------------------------------------------------------------------

procedure DrawGDIPRound(graphics: TGPGraphics; Pen: TGPPen; X,Y,Width,Height,RadiusX, RadiusY: integer);
var
  path:TGPGraphicsPath;
begin
  path := TGPGraphicsPath.Create;
  path.AddLine(X + radiusX, Y, X + width - (radiusX*2), Y);
  path.AddArc(X + width - (radiusX*2), Y, radiusX*2, radiusY*2, 270, 90);
  path.AddLine(X + width, Y + radiusY, X + width, Y + height - (radiusY*2));
  path.AddArc(X + width - (radiusX*2), Y + height - (radiusY*2), radiusX*2, radiusY*2,0,90);
  path.AddLine(X + width - (radiusX*2), Y + height, X + radiusX, Y + height);
  path.AddArc(X, Y + height - (radiusY*2), radiusX*2, radiusY*2, 90, 90);
  path.AddLine(X, Y + height - (radiusY*2), X, Y + radiusY);
  path.AddArc(X, Y, radiusX*2, radiusY*2, 180, 90);
  path.CloseFigure;
  graphics.DrawPath(pen, path);
  path.Free;
end;

//------------------------------------------------------------------------------

procedure DrawRoundRect(graphics: TGPGraphics; Pen: TGPPen; X,Y,Width,Height,Radius: integer);
var
  path:TGPGraphicsPath;
begin
  path := TGPGraphicsPath.Create;
  path.AddLine(X + radius, Y, X + width - (radius*2), Y);
  path.AddArc(X + width - (radius*2), Y, radius*2, radius*2, 270, 90);
  path.AddLine(X + width, Y + radius, X + width, Y + height - (radius*2));
  path.AddArc(X + width - (radius*2), Y + height - (radius*2), radius*2, radius*2,0,90);
  path.AddLine(X + width - (radius*2), Y + height, X + radius, Y + height);
  path.AddArc(X, Y + height - (radius*2), radius*2, radius*2, 90, 90);
  path.AddLine(X, Y + height - (radius*2), X, Y + radius);
  path.AddArc(X, Y, radius*2, radius*2, 180, 90);
  path.CloseFigure;
  graphics.DrawPath(pen, path);
  path.Free;
end;

//------------------------------------------------------------------------------

procedure DrawRect(graphics: TGPGraphics; Pen: TGPPen; X,Y,Width,Height: integer);
var
  path:TGPGraphicsPath;
begin
  path := TGPGraphicsPath.Create;
  path.AddLine(X, Y, X + width, Y);
  path.AddLine(X + width, Y, X + width, Y + height);
  path.AddLine(X + width, Y + height, X, Y + height);
  path.AddLine(X, Y + height, X, Y);
  path.CloseFigure;
  graphics.DrawPath(pen, path);
  path.Free;
end;

//------------------------------------------------------------------------------

function IsTTF(Canvas: TCanvas): Boolean;
var
  tm: TTextMetric;
begin
  Result := false;
  if not Assigned(Canvas) then
    Exit;

  GetTextMetrics(Canvas.Handle, tm);

  if ((tm.tmPitchAndFamily AND TMPF_VECTOR) = TMPF_VECTOR) then
  begin
    if not ((tm.tmPitchAndFamily AND TMPF_DEVICE) = TMPF_DEVICE) then
    begin
      Result := true;
      if (Screen.Fonts.IndexOf(Canvas.Font.Name) = -1) then
        Result := false;
    end;
  end;
end;

//------------------------------------------------------------------------------

function DrawVistaText2(Canvas: TCanvas; Alignment: TAlignment; DTSTYLE: DWORD; r: TRect; Text:string; WideCaption: widestring; AFont: TFont; Enabled: Boolean; RealDraw: Boolean; AntiAlias: TAntiAlias; Ellipsis: Boolean; MultiLine: Boolean): TRect;
var
  graphics : TGPGraphics;
  w,h: Integer;
  fontFamily: TGPFontFamily;
  font: TGPFont;
  rectf: TGPRectF;
  stringFormat: TGPStringFormat;
  solidBrush: TGPSolidBrush;
  x1,y1,x2,y2: single;
  fs: integer;
  sizerect: TGPRectF;
  s, s2: string;
  i, j: Integer;
begin
  Result := Rect(0, 0, 0, 0);
  if (Text <> '') then
  begin
    Canvas.Font.Name := AFont.Name;
    if (AntiAlias = aaNone) or not IsTTF(Canvas) then
    begin
      Result := Rect(0, 0, 1000, 100);
      DrawText(Canvas.Handle,PChar(Text),Length(Text), Result, DT_CALCRECT or DT_LEFT or DT_SINGLELINE);

      if RealDraw then
      begin
{$IFNDEF TMSDOTNET}
        DrawText(Canvas.Handle, PChar(Text), Length(Text), r, DTSTYLE);
{$ENDIF}
{$IFDEF TMSDOTNET}
        DrawText(Canvas.Handle, Text, Length(Text), r, DTSTYLE);
{$ENDIF}
      end;
    end
    else
    begin
      graphics := TGPGraphics.Create(Canvas.Handle);
      fontFamily:= TGPFontFamily.Create(AFont.Name);
      
      if (fontFamily.Status in [FontFamilyNotFound, FontStyleNotFound]) then
      begin
        fontFamily.Free;
        fontFamily := TGPFontFamily.Create('Arial');
      end;


      fs := AdvGDIP.TFontStyle(byte(AFont.Style));

      font := TGPFont.Create(fontFamily, AFont.Size , fs, UnitPoint);
      graphics.SetSmoothingMode(SmoothingModeAntiAlias);

      w := R.Right - R.Left;
      h := R.Bottom - R.Top;

      x1 := r.Left;
      y1 := r.Top;
      x2 := w;
      y2 := h;

      rectf := MakeRect(x1,y1,x2,y2);

      stringFormat := TGPStringFormat.Create;

      if Enabled then
        solidBrush := TGPSolidBrush.Create(ColorToARGB(AFont.Color))
      else
        solidBrush := TGPSolidBrush.Create(ColorToARGB(clGray));

      case Alignment of
        taLeftJustify: stringFormat.SetAlignment(StringAlignmentNear);
        taRightJustify: stringFormat.SetAlignment(StringAlignmentFar);
        else
        begin
          // Center-justify each line of text.
          stringFormat.SetAlignment(StringAlignmentCenter);
        end;

      end;

      // Center the block of text (top to bottom) in the rectangle.
      stringFormat.SetLineAlignment(StringAlignmentCenter);

      stringFormat.SetHotkeyPrefix(HotkeyPrefixShow);

      case AntiAlias of
      aaClearType:graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
      aaAntiAlias:graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
      end;

      if RealDraw and (Ellipsis or not MultiLine) then
      begin
        rectf := MakeRect(x1,y1,1000,y2);
        graphics.MeasureString(Text, Length(Text), font, rectf, stringFormat, sizerect);
      end
      else
        graphics.MeasureString(Text, Length(Text), font, rectf, stringFormat, sizerect);

      Result := Rect(round(sizerect.X), Round(sizerect.Y), Round(sizerect.X + sizerect.Width), Round(sizerect.Y + sizerect.Height));
      rectf := MakeRect(x1,y1,x2,y2);

      if RealDraw then
      begin
        //-- Add ellipsis
        if (sizerect.Width > x2) and (Ellipsis or not MultiLine) then
        begin
          rectf := MakeRect(x1,y1,1000,y2);
          if Ellipsis then
          begin
            s := '...';
            //Text := Copy(Text, 1, Length(Text)- 3);
            //Delete(Text, Length(Text)-3, 3);
          end
          else
          begin
            s := '';
          end;
          j := Length(Text);
          for i := 0 to j do
          begin
            s2 := Text + s;
            graphics.MeasureString(s2, Length(s2), font, rectf, stringFormat, sizerect);
            if (sizerect.Width > x2) and (Text <> '') then
            begin
              Text := Copy(Text, 1, Length(Text)-1);
              //Delete(Text, Length(Text)-1, 1);
            end
            else
            begin
              Break;
            end;
          end;
          Text := Text + s;
          rectf := MakeRect(x1,y1,x2,y2);
        end;

        graphics.DrawString(Text, Length(Text), font, rectf, stringFormat, solidBrush);
      end;

      stringformat.Free;
      solidBrush.Free;
      font.Free;
      fontfamily.Free;
      graphics.Free;
    end;
  end;
end;

function DrawVistaText(Canvas: TCanvas; Alignment: TAlignment; r: TRect; Caption:string; WideCaption: widestring; AFont: TFont; Enabled: Boolean; RealDraw: Boolean; AntiAlias: TAntiAlias): TRect;
var
  graphics : TGPGraphics;
  w,h: Integer;
  fontFamily: TGPFontFamily;
  font: TGPFont;
  rectf: TGPRectF;
  stringFormat: TGPStringFormat;
  solidBrush: TGPSolidBrush;
  x1,y1,x2,y2: single;
  fs: integer;
  sizerect: TGPRectF;
  szRect: TRect;
  DTFLAG: DWORD;
begin
  if (Caption <> '') or (WideCaption <> '') then
  begin
    graphics := TGPGraphics.Create(Canvas.Handle);
    fontFamily:= TGPFontFamily.Create(AFont.Name);

    if (fontFamily.Status in [FontFamilyNotFound, FontStyleNotFound]) then
    begin
      fontFamily.Free;
      fontFamily := TGPFontFamily.Create('Arial');
    end;
    

    fs := 0;

    if (fsBold in AFont.Style) then
      fs := fs + 1;

    if (fsItalic in AFont.Style) then
      fs := fs + 2;

    if (fsUnderline in AFont.Style) then
      fs := fs + 4;

    font := TGPFont.Create(fontFamily, AFont.Size , fs, UnitPoint);

    graphics.SetSmoothingMode(SmoothingModeAntiAlias);

    w := R.Right - R.Left;
    h := R.Bottom - R.Top;

    x1 := r.Left;
    y1 := r.Top;
    x2 := w;
    y2 := h;

    rectf := MakeRect(x1,y1,x2,y2);

    stringFormat := TGPStringFormat.Create;

    if Enabled then
      solidBrush := TGPSolidBrush.Create(ColorToARGB(AFont.Color))
    else
      solidBrush := TGPSolidBrush.Create(ColorToARGB(clGray));

    case Alignment of
      taLeftJustify: stringFormat.SetAlignment(StringAlignmentNear);
      taCenter:
      begin
        // Center-justify each line of text.
        stringFormat.SetAlignment(StringAlignmentCenter);
      end;
      taRightJustify: stringFormat.SetAlignment(StringAlignmentFar);
    end;

    // Center the block of text (top to bottom) in the rectangle.

    stringFormat.SetLineAlignment(StringAlignmentCenter);
    stringFormat.SetHotkeyPrefix(HotkeyPrefixShow);
    stringFormat.SetTrimming(StringTrimmingNone);


    case AntiAlias of
    aaClearType:graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
    aaAntiAlias:graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
    end;

    // graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);

    if (AntiAlias = aaNone) then
    begin
      szRect.Left := round(rectf.X);
      szRect.Top := round(rectf.Y);

      szRect.Right := szRect.Left + 2;

      if (Caption <> '') then
        szRect.Bottom := DrawText(Canvas.Handle,PChar(Caption),Length(Caption), szrect, DT_CALCRECT or DT_LEFT or DT_WORDBREAK)
      else
        szRect.Bottom := DrawTextW(Canvas.Handle,PWideChar(WideCaption),Length(WideCaption), szrect, DT_CALCRECT or DT_LEFT or DT_WORDBREAK);

      sizeRect.X := szRect.Left;
      sizeRect.Y := szRect.Top;
      sizeRect.Width := szRect.Right - szRect.Left;
      sizeRect.Height := szRect.Bottom - szRect.Top;
    end
    else
    begin
      fillchar(sizerect,sizeof(sizerect),0);

      if (Caption <> '') then
        graphics.MeasureString(Caption, Length(Caption), font, rectf, stringFormat, sizerect)
      else
        graphics.MeasureString(WideCaption, Length(WideCaption), font, rectf, stringFormat, sizerect)
    end;

    Result := Rect(round(sizerect.X), Round(sizerect.Y), Round(sizerect.X + sizerect.Width), Round(sizerect.Y + sizerect.Height));
    rectf := MakeRect(x1,y1,x2,y2);

    if RealDraw then
    begin
      if (AntiAlias = aaNone) then
      begin
        szRect.Left := round(rectf.X);
        szRect.Top := round(rectf.Y);
        szRect.Right := szRect.Left + round(rectf.Width);
        szRect.Bottom := szRect.Top + round(rectf.Height);
        Canvas.Brush.Style := bsClear;

        DTFLAG := DT_LEFT;
        case Alignment of
        taRightJustify: DTFLAG := DT_RIGHT;
        taCenter: DTFLAG := DT_CENTER;
        end;
        if Caption <> '' then
          DrawText(Canvas.Handle,PChar(Caption),Length(Caption), szrect, DTFLAG or DT_VCENTER or DT_SINGLELINE)
        else
          DrawTextW(Canvas.Handle,PWideChar(WideCaption),Length(WideCaption), szrect, DTFLAG or DT_VCENTER or DT_SINGLELINE)
      end
      else
      begin
        if (Caption <> '') then
          graphics.DrawString(Caption, Length(Caption), font, rectf, stringFormat, solidBrush)
        else
          graphics.DrawString(WideCaption, Length(WideCaption), font, rectf, stringFormat, solidBrush)
      end;
    end;
    stringformat.Free;
    solidBrush.Free;
    font.Free;
    fontfamily.Free;
    graphics.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure DrawVistaBackGround(Canvas: TCanvas; r: TRect; CFU, CTU, CFB, CTB, PC: TColor;
   GradientU,GradientB: TGDIPGradient; Caption:string; AFont: TFont;
   {Images: TImageList; ImageIndex: integer; EnabledImage: Boolean; Layout: TButtonLayout;
   } Enabled: Boolean{; Focus: Boolean; Picture: TGDIPPicture}; RoundEdges: Boolean);
var
  graphics : TGPGraphics;
  path: TGPGraphicsPath;
  pthGrBrush: TGPPathGradientBrush;
  linGrBrush: TGPLinearGradientBrush;
  gppen : tgppen;
  count: Integer;
  w,h,h2,w2: Integer;
  colors : array[0..0] of TGPColor;
  fontFamily: TGPFontFamily;
  font: TGPFont;
  rectf: TGPRectF;
  stringFormat: TGPStringFormat;
  solidBrush: TGPSolidBrush;
  x1,y1,x2,y2: single;
  fs: integer;
  sizerect: TGPRectF;
  BtnR: TRect;

 { procedure DrawArrow(ArP: TPoint; ArClr: TColor);
  begin
    Canvas.Pen.Color := ArClr;
    Canvas.MoveTo(ArP.X, ArP.Y);
    Canvas.LineTo(ArP.X + 5, ArP.Y);
    Canvas.MoveTo(ArP.X + 1, ArP.Y + 1);
    Canvas.LineTo(ArP.X + 4, ArP.Y + 1);
    Canvas.Pixels[ArP.X + 2, ArP.Y + 2] := ArClr;
  end;
 }
begin
  BtnR := R;
 { if DropDownPos = dpRight then
  begin
    DwR := Rect(BtnR.Right - DropDownSectWidth, BtnR.Top, BtnR.Right, BtnR.Bottom);
    if DropDownButton then
      BtnR.Right := DwR.Left;
  end
  else // DropDownPos = doBottom
  begin
    DwR := Rect(BtnR.Left, BtnR.Bottom - DropDownSectWidth, BtnR.Right, BtnR.Bottom);
    if DropDownButton then
      BtnR.Bottom := DwR.Top;
  end;
  }
  w := r.Right - r.Left;
  h := r.Bottom - r.Top;

  h2 := h div 2;
  w2 := w div 2;

  graphics := TGPGraphics.Create(Canvas.Handle);

  // down ellips brush

  Canvas.Brush.Color := cfb;
  Canvas.FillRect(rect(r.Left, r.top +  h div 2, r.Right, r.Bottom));

  // Create a path that consists of a single ellipse.
  path:= TGPGraphicsPath.Create;
//  path.AddRectangle(MakeRect(r.Left, r.Top +  (h div 2), w , h));
  path.AddEllipse(r.Left, r.Top +  h2, r.Right , r.Bottom + h2);

  pthGrBrush := nil;
  linGrBrush := nil;

  case GradientB of
  ggRadial: pthGrBrush := TGPPathGradientBrush.Create(path);
  ggVertical: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CFB),ColorToARGB(CTB), LinearGradientModeVertical);
  ggDiagonalForward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CFB),ColorToARGB(CTB), LinearGradientModeForwardDiagonal);
  ggDiagonalBackward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CFB),ColorToARGB(CTB), LinearGradientModeBackwardDiagonal);
  end;

  if GradientB = ggRadial then
  begin
    pthGrBrush.SetCenterPoint(MakePoint(r.Left + w2, r.Bottom));

    // Set the color at the center point to blue.
    pthGrBrush.SetCenterColor(ColorToARGB(CTB));

    colors[0] := ColorToARGB(CFB);
    count := 1;
    pthGrBrush.SetSurroundColors(@colors, count);
    graphics.FillRectangle(pthGrBrush, r.Left,r.Top + h2, r.Right, r.Bottom);
    pthGrBrush.Free;
  end
  else
  begin
    graphics.FillRectangle(linGrBrush, r.Left,r.Top + h2, r.Right, r.Bottom);
    linGrBrush.Free;
  end;

  path.Free;

  // upper ellips brush

  Canvas.Brush.Color := cfu;
  Canvas.FillRect(rect(r.Left, r.top , r.Right, r.top +  h2));

  // Create a path that consists of a single ellipse.
  path:= TGPGraphicsPath.Create;
  path.AddEllipse(r.Left, r.Top - h2 , r.Right , r.Top + h );

  case GradientU of
  ggRadial: pthGrBrush := TGPPathGradientBrush.Create(path);
  ggVertical: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CFU),ColorToARGB(CTU), LinearGradientModeVertical);
  ggDiagonalForward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CFU),ColorToARGB(CTU), LinearGradientModeForwardDiagonal);
  ggDiagonalBackward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CFU),ColorToARGB(CTU), LinearGradientModeBackwardDiagonal);
  end;

  if GradientU = ggRadial then
  begin
    pthGrBrush.SetCenterPoint(MakePoint(r.Left + w2, r.Top));

    // Set the color at the center point to blue.
    pthGrBrush.SetCenterColor(ColorToARGB(CTU));

    colors[0] := ColorToARGB(CFU);
    count := 1;
    pthGrBrush.SetSurroundColors(@colors, count);

    graphics.FillRectangle(pthGrBrush, r.Left,r.Top, r.Right, r.Bottom - h2 - 1);
    pthGrBrush.Free;
  end
  else
  begin
    graphics.FillRectangle(linGrBrush, r.Left,r.Top, r.Right, r.Bottom - h2 - 1);
    linGrBrush.Free;
  end;

  path.Free;

  gppen := TGPPen.Create(ColorToARGB(PC),1);

  graphics.SetSmoothingMode(SmoothingModeAntiAlias);

  if (PC <> clNone) then
  begin
    if not RoundEdges then
      DrawRect(graphics, gppen,r.Left,r.Top, r.Right - 1, r.Bottom - 1)
    else
      DrawRoundRect(graphics, gppen,r.Left,r.Top, r.Right - 1, r.Bottom - 1, 3);
  end;

 { if Focus then
  begin
    gppen := tgppen.Create(ColorToARGB($E4AD89),1);
    graphics.SetSmoothingMode(SmoothingModeAntiAlias);
    DrawRoundRect(graphics, gppen,r.Left + 1,r.Top + 1, r.Right - 3, r.Bottom - 3, 3);
    gppen := tgppen.Create(ColorToARGB(clgray),1);
    gppen.SetDashStyle(DashStyleDot);
    graphics.SetSmoothingMode(SmoothingModeAntiAlias);
    DrawRoundRect(graphics, gppen,r.Left + 2,r.Top + 2, r.Right - 5, r.Bottom - 5, 3);
  end;
  }

  gppen.Free;

  fontFamily:= TGPFontFamily.Create(AFont.Name);

  if (fontFamily.Status in [FontFamilyNotFound, FontStyleNotFound]) then
  begin
    fontFamily.Free;
    fontFamily := TGPFontFamily.Create('Arial');
  end;


  fs := 0;

  //ImgH := 0;
  //ImgW := 0;

  if (fsBold in AFont.Style) then
    fs := fs + 1;
  if (fsItalic in AFont.Style) then
    fs := fs + 2;
  if (fsUnderline in AFont.Style) then
    fs := fs + 4;

 { if not Picture.Empty then
  begin
    Picture.GetImageSizes;
    ImgW := Picture.Width;
    ImgH := Picture.Height;
  end
  else
  begin
    if (ImageIndex > -1) and Assigned(Images) then
    begin
      ImgW := Images.Width;
      ImgH := Images.Height;
    end;
  end;
  }
  if (Caption <> '') then
  begin
    font := TGPFont.Create(fontFamily, AFont.Size , fs, UnitPoint);

    w := BtnR.Right - BtnR.Left;
    h := BtnR.Bottom - BtnR.Top;

    x1 := r.Left;
    y1 := r.Top;
    x2 := w;
    y2 := h;

    rectf := MakeRect(x1,y1,x2,y2);

    stringFormat := TGPStringFormat.Create;

    if Enabled then
      solidBrush := TGPSolidBrush.Create(ColorToARGB(AFont.Color))
    else
      solidBrush := TGPSolidBrush.Create(ColorToARGB(clGray));

    // Center-justify each line of text.
    stringFormat.SetAlignment(StringAlignmentCenter);

    // Center the block of text (top to bottom) in the rectangle.
    stringFormat.SetLineAlignment(StringAlignmentCenter);

    stringFormat.SetHotkeyPrefix(HotkeyPrefixShow);

    //graphics.SetTextRenderingHint({TextRenderingHintClearTypeGridFit} TextRenderingHintAntiAliasGridFit});
    graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
    graphics.MeasureString(Caption, Length(Caption), font, rectf, stringFormat, sizerect);
    {
    if (ImgW > 0) then
    begin
      case Layout of
        blGlyphLeft:
        begin
          x1 := r.Left + 2 + ImgW;
          x2 := w - 2 - ImgW;

          ImgX := round(sizerect.X - ImgW div 2);
          if ImgX < 2 then ImgX := 2;
          ImgY := r.Top + Max(0, (h - ImgH) div 2);
        end;
        blGlyphTop:
        begin
          y1 := r.Top + ImgH;
          y2 := h - 2 - ImgH;

          ImgX := r.Left + Max(0, (w - ImgW) div 2);
          ImgY := round(y2 - sizerect.Height);
          ImgY := Max(0, ImgY div 2);
          ImgY := round(y1) - ImgH + ImgY; //round(sizerect.Height) - ImgY - 4;
          if ImgY < 2 then ImgY := 2;
        end;
        blGlyphRight:
        begin
          x1 := 2;
          x2 := w - 4 - ImgW;

          ImgX := round(X2 - sizerect.width);
          ImgX := Max(0, ImgX div 2);
          ImgX := ImgX + round(sizerect.width) + 4;
          if ImgX > (w - ImgW) then
            ImgX := w - ImgW - 2;
          ImgY := r.Top + Max(0, (h - ImgH) div 2);
        end;
        blGlyphBottom:
        begin
          y1 := 2;
          y2 := h - 2 - ImgH;

          ImgX := r.Left + Max(0, (w - ImgW) div 2);
          ImgY := round(y2 - sizerect.Height);
          ImgY := Max(0, ImgY div 2);
          ImgY := round(sizerect.Height + 2) + ImgY;
          if ImgY > (h - ImgH) then ImgY := h - ImgH - 2;
        end;
      end;
    end;
    }
    rectf := MakeRect(x1,y1,x2,y2);

    graphics.DrawString(Caption, Length(Caption), font, rectf, stringFormat, solidBrush);
    stringformat.Free;
    font.Free;
  end;

  fontfamily.Free;

 { if DropDownButton then
  begin

    if DropDownPos = dpRight then
      w := w - 8
    else
      h := h - 8;
  end;

  if not Picture.Empty then
  begin
     if Caption = '' then
       Canvas.Draw(r.Left + Max(0, (w - ImgW) div 2), r.Top + Max(0, (h - ImgH) div 2), Picture)
     else
       Canvas.Draw(ImgX, ImgY, Picture);
  end
  else
    if (ImageIndex <> -1) and Assigned(Images) then
    begin
      if Caption = '' then
        Images.Draw(Canvas, r.Left + Max(0, (w - Images.Width) div 2), r.Top + Max(0, (h - Images.Height) div 2), ImageIndex, EnabledImage)
      else
      begin
        Images.Draw(Canvas, ImgX, ImgY, ImageIndex, EnabledImage);
      end;
    end;


  Canvas.Brush.Style := bsClear;
  if DropDownButton then
  begin
    if DrawDwLine then
    begin
      Canvas.Pen.Color := PC;
      //Canvas.RoundRect(R.Left, R.Top, R.Right, R.Bottom, 6, 6);
      if (DropDownPos = dpRight) then
      begin
        Canvas.MoveTo(DwR.Left, DwR.Top);
        Canvas.LineTo(DwR.Left, DwR.Bottom);
      end
      else
      begin
        Canvas.MoveTo(DwR.Left, DwR.Top);
        Canvas.LineTo(DwR.Right, DwR.Top);
      end;
    end;
    AP.X := DwR.Left + ((DwR.Right - DwR.Left - 5) div 2);
    AP.Y := DwR.Top + ((DwR.Bottom - DwR.Top - 3) div 2) + 1;
    if not Enabled then
      DrawArrow(AP, clGray)
    else
      DrawArrow(AP, clBlack);
  end;
  }
  graphics.Free;
end;

//------------------------------------------------------------------------------

procedure DrawVistaPageGradient(Canvas: TCanvas; R: TRect; GradHeight: Integer; FC, TC, MFC, MTC, PC: TColor; RoundEdges: Integer);
var
  R1, R2: TRect;
  graphics: TGPGraphics;
  w, h: Integer;
  gppen: TGPPen;
begin
  R1 := Rect(R.Left, R.Top, R.Right, R.Top + GradHeight + 1);
  R2 := Rect(R.Left, R.Top + GradHeight, R.Right, R.Bottom);
  DrawGradient(Canvas, FC, TC, 40, R1, False);
  DrawGradient(Canvas, MFC, MTC, 40, R2, False);

  if (PC <> clNone) then
  begin
    w := r.Right - r.Left;
    h := r.Bottom - r.Top;
    graphics := TGPGraphics.Create(Canvas.Handle);
    gppen := TGPPen.Create(ColorToARGB(PC),1);
    graphics.SetSmoothingMode(SmoothingModeAntiAlias);
    
    if (RoundEdges <= 0) then
      DrawRect(graphics, gppen,r.Left,r.Top, w - 1, h - 1)
    else
      DrawRoundRect(graphics, gppen,r.Left,r.Top, w - 1, h - 1, RoundEdges);
    graphics.free;
    gppen.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure DrawVistaGradient(Canvas: TCanvas; r: TRect; CFU, CTU, CFB, CTB, PC: TColor;
   GradientU,GradientB: TGDIPGradient; Caption:string; AFont: TFont;
   Images: TImageList; ImageIndex: integer; EnabledImage: Boolean; Layout: TButtonLayout;
   DropDownButton: Boolean; DrawDwLine: Boolean; Enabled: Boolean; Focus: Boolean; DropDownPos: TDropDownPosition;
   Picture: TGDIPPicture; AntiAlias: TAntiAlias; RoundEdges: Boolean); overload;
var
  graphics : TGPGraphics;
  path: TGPGraphicsPath;
  pthGrBrush: TGPPathGradientBrush;
  linGrBrush: TGPLinearGradientBrush;
  gppen : tgppen;
  count: Integer;
  w,h,h2,w2: Integer;
  colors : array[0..0] of TGPColor;
  fontFamily: TGPFontFamily;
  font: TGPFont;
  rectf: TGPRectF;
  stringFormat: TGPStringFormat;
  solidBrush: TGPSolidBrush;
  x1,y1,x2,y2: single;
  fs: integer;
  sizerect: TGPRectF;
  ImgX, ImgY, ImgW, ImgH: Integer;
  BtnR, DwR: TRect;
  AP: TPoint;
  szRect: TRect;

  procedure DrawArrow(ArP: TPoint; ArClr: TColor);
  begin
    Canvas.Pen.Color := ArClr;
    Canvas.MoveTo(ArP.X, ArP.Y);
    Canvas.LineTo(ArP.X + 5, ArP.Y);
    Canvas.MoveTo(ArP.X + 1, ArP.Y + 1);
    Canvas.LineTo(ArP.X + 4, ArP.Y + 1);
    Canvas.Pixels[ArP.X + 2, ArP.Y + 2] := ArClr;
  end;

begin
  BtnR := R;
  if DropDownPos = dpRight then
  begin
    DwR := Rect(BtnR.Right - DropDownSectWidth, BtnR.Top, BtnR.Right, BtnR.Bottom);
    if DropDownButton then
      BtnR.Right := DwR.Left;
  end
  else // DropDownPos = doBottom
  begin
    DwR := Rect(BtnR.Left, BtnR.Bottom - DropDownSectWidth, BtnR.Right, BtnR.Bottom);
    if DropDownButton then
      BtnR.Bottom := DwR.Top;
  end;

  w := r.Right - r.Left;
  h := r.Bottom - r.Top;

  h2 := h div 2;
  w2 := w div 2;

  // down ellips brush
  Canvas.Brush.Color := cfb;
  Canvas.FillRect(rect(r.Left , r.top +  h2, r.Right , r.Bottom ));

  graphics := TGPGraphics.Create(Canvas.Handle);

  // Create a path that consists of a single ellipse.
  path := TGPGraphicsPath.Create;
  //  path.AddRectangle(MakeRect(r.Left, r.Top +  (h div 2), w , h));
  path.AddEllipse(r.Left, r.Top +  h2, w , h);

  pthGrBrush := nil;
  linGrBrush := nil;

  case GradientB of
  ggRadial: pthGrBrush := TGPPathGradientBrush.Create(path);
  ggVertical: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top + h2,w,h2),ColorToARGB(CFB),ColorToARGB(CTB), LinearGradientModeVertical);
  ggDiagonalForward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top + h2,w,h2),ColorToARGB(CFB),ColorToARGB(CTB), LinearGradientModeForwardDiagonal);
  ggDiagonalBackward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top + h2,w,h2),ColorToARGB(CFB),ColorToARGB(CTB), LinearGradientModeBackwardDiagonal);
  end;

  if GradientB = ggRadial then
  begin
    pthGrBrush.SetCenterPoint(MakePoint(r.Left + w2, r.Bottom));

    // Set the color at the center point to blue.
    pthGrBrush.SetCenterColor(ColorToARGB(CTB));

    colors[0] := ColorToARGB(CFB);
    count := 1;
    pthGrBrush.SetSurroundColors(@colors, count);
    graphics.FillRectangle(pthGrBrush, r.Left + 1,r.Top + h2, w - 1, h2+1);
    pthGrBrush.Free;
  end
  else
  begin
    graphics.FillRectangle(linGrBrush, r.Left + 1,r.Top + h2 + 1, w - 1, h2 + 1);
    linGrBrush.Free;
  end;

  path.Free;
  graphics.Free;
  
  // upper ellips brush
  Canvas.Brush.Color := cfu;
  Canvas.FillRect(rect(r.Left , r.Top , r.Right , r.top +  h2));

  graphics := TGPGraphics.Create(Canvas.Handle);

  // Create a path that consists of a single ellipse.
  path := TGPGraphicsPath.Create;
  path.AddEllipse(r.Left, r.Top - h2 , w , h);

  case GradientU of
  ggRadial: pthGrBrush := TGPPathGradientBrush.Create(path);                      // FF: Gradient fix here replace h by h2
  ggVertical: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h2),ColorToARGB(CFU),ColorToARGB(CTU), LinearGradientModeVertical);
  ggDiagonalForward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CFU),ColorToARGB(CTU), LinearGradientModeForwardDiagonal);
  ggDiagonalBackward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CFU),ColorToARGB(CTU), LinearGradientModeBackwardDiagonal);
  end;

  if odd(h) then
    inc(h2);
  

  if GradientU = ggRadial then
  begin
    pthGrBrush.SetCenterPoint(MakePoint(r.Left + w2, r.top));

    // Set the color at the center point to blue.
    pthGrBrush.SetCenterColor(ColorToARGB(CTU));

    colors[0] := ColorToARGB(CFU);
    count := 1;
    pthGrBrush.SetSurroundColors(@colors, count);

    graphics.FillRectangle(pthGrBrush, r.Left + 1,r.Top + 1, w - 1, h - h2 - 1);
    pthGrBrush.Free;
  end
  else
  begin
    graphics.FillRectangle(linGrBrush, r.Left + 1,r.Top + 1, w - 1, h - h2 - 1);
    linGrBrush.Free;
  end;

  path.Free;

  gppen := TGPPen.Create(ColorToARGB(PC),1);

  graphics.SetSmoothingMode(SmoothingModeAntiAlias);

  if (PC <> clNone) then
  begin
    if not RoundEdges then
      DrawRect(graphics, gppen,r.Left,r.Top, w - 1, h - 1)
    else
      DrawRoundRect(graphics, gppen,r.Left,r.Top, w - 1, h - 1, 3);
  end;

  gppen.Free;

  if Focus then
  begin
    gppen := TGPPen.Create(ColorToARGB($E4AD89),1);
    graphics.SetSmoothingMode(SmoothingModeAntiAlias);
    DrawRoundRect(graphics, gppen,r.Left + 1,r.Top + 1, r.Right - 3, r.Bottom - 3, 3);
    gppen.Free;
    gppen := TGPPen.Create(ColorToARGB(clgray),1);
    gppen.SetDashStyle(DashStyleDot);
    graphics.SetSmoothingMode(SmoothingModeAntiAlias);
    DrawRoundRect(graphics, gppen,r.Left + 2,r.Top + 2, r.Right - 5, r.Bottom - 5, 3);
    gppen.Free;
  end;

  fontFamily := TGPFontFamily.Create(AFont.Name);

  if (fontFamily.Status in [FontFamilyNotFound, FontStyleNotFound]) then
  begin
    fontFamily.Free;
    fontFamily := TGPFontFamily.Create('Arial');
  end;

  fs := 0;

  ImgH := 0;
  ImgW := 0;

  if (fsBold in AFont.Style) then
    fs := fs + 1;
  if (fsItalic in AFont.Style) then
    fs := fs + 2;
  if (fsUnderline in AFont.Style) then
    fs := fs + 4;

  if Assigned(Picture) and not Picture.Empty then
  begin
    Picture.GetImageSizes;
    ImgW := Picture.Width;
    ImgH := Picture.Height;
  end
  else
  begin
    if (ImageIndex > -1) and Assigned(Images) then
    begin
      ImgW := Images.Width;
      ImgH := Images.Height;
    end;
  end;

  if (Caption <> '') then
  begin
    font := TGPFont.Create(fontFamily, AFont.Size , fs, UnitPoint);

    w := BtnR.Right - BtnR.Left;
    h := BtnR.Bottom - BtnR.Top;

    x1 := r.Left;
    y1 := r.Top;
    x2 := w;
    y2 := h;

    rectf := MakeRect(x1,y1,x2,y2);

    stringFormat := TGPStringFormat.Create;

    if Enabled then
      solidBrush := TGPSolidBrush.Create(ColorToARGB(AFont.Color))
    else
      solidBrush := TGPSolidBrush.Create(ColorToARGB(clGray));

    // Center-justify each line of text.
    stringFormat.SetAlignment(StringAlignmentCenter);

    // Center the block of text (top to bottom) in the rectangle.
    stringFormat.SetLineAlignment(StringAlignmentCenter);

    stringFormat.SetHotkeyPrefix(HotkeyPrefixShow);

    case AntiAlias of
    aaClearType:graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
    aaAntiAlias:graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
    end;

    if AntiAlias = aaNone then
    begin
      szRect.Left := round(rectf.X);
      szRect.Top := round(rectf.Y);

      szRect.Right := szRect.Left + 2;
      szRect.Bottom := DrawText(Canvas.Handle,PChar(Caption),Length(Caption), szrect, DT_CALCRECT or DT_LEFT or DT_WORDBREAK);

      sizeRect.X := szRect.Left;
      sizeRect.Y := szRect.Top;
      sizeRect.Width := szRect.Right - szRect.Left;
      sizeRect.Height := szRect.Bottom - szRect.Top;
    end
    else
      graphics.MeasureString(Caption, Length(Caption), font, rectf, stringFormat, sizerect);

    if (ImgW > 0) then
    begin
      case Layout of
        blGlyphLeft:
        begin
          x1 := r.Left + 2 + ImgW;
          x2 := w - 2 - ImgW;

          ImgX := round(sizerect.X - ImgW div 2);
          if ImgX < 2 then ImgX := 2;
          ImgY := r.Top + Max(0, (h - ImgH) div 2);
        end;
        blGlyphTop:
        begin
          y1 := r.Top{ + 2} + ImgH;
          y2 := h - 2 - ImgH;

          ImgX := r.Left + Max(0, (w - ImgW) div 2);
          ImgY := round(y2 - sizerect.Height);
          ImgY := Max(0, ImgY div 2);
          ImgY := round(y1) - ImgH + ImgY; //round(sizerect.Height) - ImgY - 4;
          if ImgY < 2 then ImgY := 2;
        end;
        blGlyphRight:
        begin
          x1 := 2;
          x2 := w - 4 - ImgW;

          ImgX := round(X2 - sizerect.width);
          ImgX := Max(0, ImgX div 2);
          ImgX := ImgX + round(sizerect.width) + 4;
          if ImgX > (w - ImgW) then
            ImgX := w - ImgW - 2;
          ImgY := r.Top + Max(0, (h - ImgH) div 2);
        end;
        blGlyphBottom:
        begin
          y1 := 2;
          y2 := h - 2 - ImgH;

          ImgX := r.Left + Max(0, (w - ImgW) div 2);
          ImgY := round(y2 - sizerect.Height);
          ImgY := Max(0, ImgY div 2);
          ImgY := round(sizerect.Height + 2) + ImgY;
          if ImgY > (h - ImgH) then ImgY := h - ImgH - 2;
        end;
      end;
    end;

    rectf := MakeRect(x1,y1,x2,y2);

    if AntiAlias = aaNone then
    begin
      szRect.Left := round(rectf.X);
      szRect.Top := round(rectf.Y);
      szRect.Right := szRect.Left + round(rectf.Width);
      szRect.Bottom := szRect.Top + round(rectf.Height);
      Canvas.Brush.Style := bsClear;
      DrawText(Canvas.Handle,PChar(Caption),Length(Caption), szrect, DT_CENTER or DT_VCENTER or DT_SINGLELINE)
    end
    else
      graphics.DrawString(Caption, Length(Caption), font, rectf, stringFormat, solidBrush);

    stringformat.Free;
    font.Free;
  end;

  fontfamily.Free;
  graphics.Free;

  if DropDownButton then
  begin

    if DropDownPos = dpRight then
      w := w - 8
    else
      h := h - 8;
  end;

  if Assigned(Picture) and not Picture.Empty then
  begin
     if Caption = '' then
       Canvas.Draw(r.Left + Max(0, (w - ImgW) div 2), r.Top + Max(0, (h - ImgH) div 2), Picture)
     else
       Canvas.Draw(ImgX, ImgY, Picture);
  end
  else
    if (ImageIndex <> -1) and Assigned(Images) then
    begin
      if Caption = '' then
        Images.Draw(Canvas, r.Left + Max(0, (w - Images.Width) div 2), r.Top + Max(0, (h - Images.Height) div 2), ImageIndex, EnabledImage)
      else
      begin
        Images.Draw(Canvas, ImgX, ImgY, ImageIndex, EnabledImage);
      end;
    end;

  Canvas.Brush.Style := bsClear;
  if DropDownButton then
  begin
    if DrawDwLine then
    begin
      Canvas.Pen.Color := PC;
      if (DropDownPos = dpRight) then
      begin
        Canvas.MoveTo(DwR.Left, DwR.Top);
        Canvas.LineTo(DwR.Left, DwR.Bottom);
      end
      else
      begin
        Canvas.MoveTo(DwR.Left, DwR.Top);
        Canvas.LineTo(DwR.Right, DwR.Top);
      end;
    end;
    AP.X := DwR.Left + ((DwR.Right - DwR.Left - 5) div 2);
    AP.Y := DwR.Top + ((DwR.Bottom - DwR.Top - 3) div 2) + 1;
    if not Enabled then
      DrawArrow(AP, clGray)
    else
      DrawArrow(AP, clBlack);
  end;


end;


procedure DrawVistaGradient(Canvas: TCanvas; r: TRect; CFU, CTU, CFB, CTB, PC: TColor;
   GradientU,GradientB: TGDIPGradient; Caption:string; AFont: TFont; Enabled: Boolean; Focus: Boolean;
   AntiAlias: TAntiAlias; RoundEdges: Boolean); overload;
begin
  DrawVistaGradient(Canvas, r, CFU, CTU, CFB, CTB, PC, GradientU,GradientB, Caption, AFont,
   nil, -1, True, blGlyphLeft, False, False, Enabled, Focus, dpRight, nil, AntiAlias, RoundEdges);
end;

//------------------------------------------------------------------------------

function BrightnessColor(Col: TColor; Brightness: integer): TColor; overload;
var
  r1,g1,b1: Integer;
begin
  Col := ColorToRGB(Col);
  r1 := GetRValue(Col);
  g1 := GetGValue(Col);
  b1 := GetBValue(Col);

  if r1 = 0 then
    r1 := Max(0,Brightness)
  else
    r1 := Round( Min(100,(100 + Brightness))/100 * r1 );

  if g1 = 0 then
    g1 := Max(0,Brightness)
  else
    g1 := Round( Min(100,(100 + Brightness))/100 * g1 );

  if b1 = 0 then
    b1 := Max(0,Brightness)
  else
    b1 := Round( Min(100,(100 + Brightness))/100 * b1 );

  Result := RGB(r1,g1,b1);
end;

//------------------------------------------------------------------------------

function BrightnessColor(Col: TColor; BR,BG,BB: integer): TColor; overload;
var
  r1,g1,b1: Integer;
begin
  Col := Longint(ColorToRGB(Col));
  r1 := GetRValue(Col);
  g1 := GetGValue(Col);
  b1 := GetBValue(Col);

  if r1 = 0 then
    r1 := Max(0,BR)
  else
    r1 := Round( Min(100,(100 + BR))/100 * r1 );

  if g1 = 0 then
    g1 := Max(0,BG)
  else
    g1 := Round( Min(100,(100 + BG))/100 * g1 );

  if b1 = 0 then
    b1 := Max(0,BB)
  else
    b1 := Round( Min(100,(100 + BB))/100 * b1 );

  Result := RGB(r1,g1,b1);
end;

//------------------------------------------------------------------------------

procedure DrawCross(Canvas: TCanvas; R: TRect; Clr: TColor; Size: Integer);
var
  x, y: Integer;
begin
  with Canvas do
  begin
    x := (R.Right - R.Left - Size) div 3;
    y := (R.Bottom - R.Top - Size) div 3;
    Pen.Color := Clr;
                   {/}
    MoveTo(R.Left+x, R.Top + Size+y);
    LineTo(R.Left + Size+1+x, R.Top+y);
    MoveTo(R.Left + 1+x, R.Top + Size+y);
    LineTo(R.Left + Size+x, R.Top+y);
                   {\}
    MoveTo(R.Left+x, R.Top + 1+y);
    LineTo(R.Left + Size+1+x, R.Top + 1 + Size+y);
    MoveTo(R.Left + 1+x, R.Top + 1+y);
    LineTo(R.Left + Size+x, R.Top + 1 + Size+y);
  end;
end;

//------------------------------------------------------------------------------

procedure DrawOpenRoundRectMiddle(graphics: TGPGraphics; PC: TColor; X,Y,Width,Height,Radius: integer;Hot:boolean);
var
  path:TGPGraphicsPath;
  gppen:TGPPen;

begin
  path := TGPGraphicsPath.Create;

  gppen := tgppen.Create(ColorToARGB(PC),1);
  path.AddLine(X-1, Y + height, X + width, Y + height);
  graphics.DrawPath(gppen, path);
  path.Free;

  path := TGPGraphicsPath.Create;
  path.AddLine(X-1, Y, X + width, Y);
  graphics.DrawPath(gppen, path);
  gppen.Free;
  path.Free;

  path := TGPGraphicsPath.Create;
  gppen := tgppen.Create(ColorToARGB(BrightnessColor(PC,-5)),1);
  path.AddLine(X + Width, Y, X + width, Y + Height);
  graphics.DrawPath(gppen, path);
  gppen.Free;
  path.Free;

  if hot then
  begin
    path := TGPGraphicsPath.Create;
    gppen := tgppen.Create(ColorToARGB(BrightnessColor(PC,-5)),1);
    path.AddLine(X  , Y, X    , Y + Height);
    graphics.DrawPath(gppen, path);
    gppen.Free;
    path.Free;
  end
  else
  begin
    path := TGPGraphicsPath.Create;
    // 3D color effect
    gppen := tgppen.Create(ColorToARGB(BrightnessColor(clwhite,-10)),1);
    path.AddLine(X, Y + 2, X, Y + Height - 2);
    graphics.DrawPath(gppen, path);
    gppen.Free;
    path.Free;
  end;
end;


//------------------------------------------------------------------------------

procedure DrawOpenRoundRectLeft(graphics: TGPGraphics; PC:TColor; X,Y,Width,Height,Radius: integer);
var
  path:TGPGraphicsPath;
  gppen:TGPPen;
begin
  path := TGPGraphicsPath.Create;
  gppen := tgppen.Create(ColorToARGB(PC),1);
  path.AddLine(X + width , Y + height, X + radius, Y + height);
  path.AddArc(X, Y + height - (radius*2), radius*2, radius*2, 90, 90);
  path.AddLine(X, Y + height - (radius*2), X, Y + radius);
  path.AddArc(X, Y, radius*2, radius*2, 180, 90);
  path.AddLine(X + radius, Y, X + width, Y);
  graphics.DrawPath(gppen, path);
  gppen.Free;
  path.Free;

  path := TGPGraphicsPath.Create;
  gppen := tgppen.Create(ColorToARGB(BrightnessColor(PC,-5)),1);
  path.AddLine(X + Width , Y, X + width , Y + Height);
  graphics.DrawPath(gppen, path);
  gppen.Free;
  path.Free;

end;

procedure DrawOpenRoundRectRight(graphics: TGPGraphics; PC: TColor; X,Y,Width,Height,Radius: integer;Hot: boolean);
var
  path:TGPGraphicsPath;
  gppen:TGPPen;
begin
  path := TGPGraphicsPath.Create;
  gppen := tgppen.Create(ColorToARGB(PC),1);
  path.AddLine(X, Y, X + width - (radius *2), Y);
  path.AddArc(X + width - (radius*2), Y, radius*2, radius*2, 270, 90);
  path.AddLine(X + width, Y + radius, X + width, Y + height - (radius*2));
  path.AddArc(X + width - (radius*2), Y + height - (radius*2), radius*2, radius*2,0,90);
  path.AddLine(X + width , Y + height, X, Y + height);
  graphics.DrawPath(gppen, path);
  gppen.Free;

  path.Free;


  if hot then
  begin
    path := TGPGraphicsPath.Create;
    gppen := tgppen.Create(ColorToARGB(BrightnessColor(PC,-5)),1);
    path.AddLine(X  , Y, X    , Y + Height);
    graphics.DrawPath(gppen, path);
    gppen.Free;
    path.Free;
  end
  else
  begin
    path := TGPGraphicsPath.Create;
    // 3D color effect
    gppen := tgppen.Create(ColorToARGB(BrightnessColor(clwhite,-10)),1);
    path.AddLine(X, Y + 2, X, Y + Height - 2);
    graphics.DrawPath(gppen, path);
    gppen.Free;
    path.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure DrawDottedRoundRect(graphics: TGPGraphics; PC: TColor; X,Y,Width,Height,Radius: integer);
var
  path:TGPGraphicsPath;
  gppen:TGPPen;
begin
  path := TGPGraphicsPath.Create;
  gppen := tgppen.Create(ColorToARGB(PC),1);
  gppen.SetDashStyle(DashStyleDot);
  path.AddLine(X + radius, Y, X + width - (radius*2), Y);
  path.AddArc(X + width - (radius*2), Y, radius*2, radius*2, 270, 90);
  path.AddLine(X + width, Y + radius, X + width, Y + height - (radius*2));
  path.AddArc(X + width - (radius*2), Y + height - (radius*2), radius*2, radius*2,0,90);
  path.AddLine(X + width - (radius*2), Y + height, X + radius, Y + height);
  path.AddArc(X, Y + height - (radius*2), radius*2, radius*2, 90, 90);
  path.AddLine(X, Y + height - (radius*2), X, Y + radius);
  path.AddArc(X, Y, radius*2, radius*2, 180, 90);
  path.CloseFigure;
  graphics.DrawPath(gppen, path);
  gppen.Free;
  path.Free;
end;


//------------------------------------------------------------------------------

procedure DrawRoundRect2(graphics: TGPGraphics; PC: TColor; X,Y,Width,Height,Radius: integer);
var
  path:TGPGraphicsPath;
  gppen:TGPPen;
begin
  path := TGPGraphicsPath.Create;
  gppen := tgppen.Create(ColorToARGB(PC),1);
  path.AddLine(X + radius, Y, X + width - (radius*2), Y);
  path.AddArc(X + width - (radius*2), Y, radius*2, radius*2, 270, 90);
  path.AddLine(X + width, Y + radius, X + width, Y + height - (radius*2));
  path.AddArc(X + width - (radius*2), Y + height - (radius*2), radius*2, radius*2,0,90);
  path.AddLine(X + width - (radius*2), Y + height, X + radius, Y + height);
  path.AddArc(X, Y + height - (radius*2), radius*2, radius*2, 90, 90);
  path.AddLine(X, Y + height - (radius*2), X, Y + radius);
  path.AddArc(X, Y, radius*2, radius*2, 180, 90);
  path.CloseFigure;
  graphics.DrawPath(gppen, path);
  gppen.Free;
  path.Free;
end;

procedure DrawArrow(Canvas: TCanvas; ArP: TPoint; ArClr, ArShad: TColor; Down:boolean);
begin
  if Down then
  begin
    Canvas.Pen.Color := ArClr;
    Canvas.MoveTo(ArP.X, ArP.Y);
    Canvas.LineTo(ArP.X + 5, ArP.Y);
    Canvas.MoveTo(ArP.X + 1, ArP.Y + 1);
    Canvas.LineTo(ArP.X + 4, ArP.Y + 1);
    Canvas.Pixels[ArP.X + 2, ArP.Y + 2] := ArClr;
    Canvas.Pixels[ArP.X, ArP.Y + 1] := ArShad;
    Canvas.Pixels[ArP.X + 4, ArP.Y + 1] := ArShad;
    Canvas.Pixels[ArP.X + 1, ArP.Y + 2] := ArShad;
    Canvas.Pixels[ArP.X + 3, ArP.Y + 2] := ArShad;
    Canvas.Pixels[ArP.X + 2, ArP.Y + 3] := ArShad;
  end
  else
  begin
    Canvas.Pen.Color := ArClr;
    Canvas.MoveTo(ArP.X, ArP.Y);
    Canvas.LineTo(ArP.X, ArP.Y + 5);
    Canvas.MoveTo(ArP.X + 1, ArP.Y + 1);
    Canvas.LineTo(ArP.X + 1, ArP.Y + 4);
    Canvas.Pixels[ArP.X + 2, ArP.Y + 2] := ArClr;
    Canvas.Pixels[ArP.X + 2, ArP.Y + 1] := ArShad;
    Canvas.Pixels[ArP.X + 1, ArP.Y + 4] := ArShad;
    Canvas.Pixels[ArP.X + 2, ArP.Y + 1] := ArShad;
    Canvas.Pixels[ArP.X + 3, ArP.Y + 2] := ArShad;
    Canvas.Pixels[ArP.X + 3, ArP.Y + 2] := ArShad;
  end;
end;

procedure DrawButtonBackground(Canvas: TCanvas; Graphics: TGPGraphics; R: TRect; CF,CT: TColor; Gradient: TGDIPGradient; Upper: boolean);
var
  path: TGPGraphicsPath;
  pthGrBrush: TGPPathGradientBrush;
  linGrBrush: TGPLinearGradientBrush;
  solGrBrush: TGPSolidBrush;
  
  w,h,w2,h2: Integer;
  colors : array[0..0] of TGPColor;
  count: Integer;

begin
  w := r.Right - r.Left;
  h := r.Bottom - r.Top;

  h2 := h div 2;
  w2 := w div 2;

  {
  // draw background
  if Upper then
    Canvas.Brush.Color := CF
  else
    Canvas.Brush.Color := CT;
  Canvas.FillRect(rect(r.Left , r.Top, r.Right , r.Bottom));
  }

  if Upper then
    solGrBrush := TGPSolidBrush.Create(ColorToARGB(CF))
  else
    solGrBrush := TGPSolidBrush.Create(ColorToARGB(CT));

  Graphics.FillRectangle(solGrBrush, MakeRect(r.Left , r.Top, r.Right , r.Bottom));

  solGrBrush.Free;

  // Create a path that consists of a single ellipse.
  path := TGPGraphicsPath.Create;

  if Upper then        // take borders in account
    path.AddEllipse(r.Left, r.Top - h2 + 2, r.Right , r.Bottom)
  else
    path.AddEllipse(r.Left, r.Top, r.Right , r.Bottom);

  pthGrBrush := nil;
  linGrBrush := nil;

  case Gradient of
  ggRadial: pthGrBrush := TGPPathGradientBrush.Create(path);
  ggVertical: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CF),ColorToARGB(CT), LinearGradientModeVertical);
  ggDiagonalForward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CF),ColorToARGB(CT), LinearGradientModeForwardDiagonal);
  ggDiagonalBackward: linGrBrush := TGPLinearGradientBrush.Create(MakeRect(r.Left,r.Top,w,h),ColorToARGB(CF),ColorToARGB(CT), LinearGradientModeBackwardDiagonal);
  end;

  if Gradient = ggRadial then
  begin
    if Upper then
      pthGrBrush.SetCenterPoint(MakePoint(r.Left + w2, r.Top))
    else
      pthGrBrush.SetCenterPoint(MakePoint(r.Left + w2, r.Bottom));

    // Set the color at the center point to blue.
    if Upper then
    begin
      pthGrBrush.SetCenterColor(ColorToARGB(CT));
      colors[0] := ColorToARGB(CF);
    end
    else
    begin
      pthGrBrush.SetCenterColor(ColorToARGB(CF));
      colors[0] := ColorToARGB(CT);
    end;

    count := 1;
    pthGrBrush.SetSurroundColors(@colors, count);
    graphics.FillRectangle(pthGrBrush, r.Left, r.Top, r.Right, r.Bottom);
    pthGrBrush.Free;
  end
  else
  begin
    graphics.FillRectangle(linGrBrush, r.Left, r.Top, r.Right, r.Bottom);
    linGrBrush.Free;
  end;

  path.Free;
end;

//------------------------------------------------------------------------------

function DrawVistaButton(Canvas: TCanvas; r: TRect; CFU, CTU, CFB, CTB, PC: TColor;
   GradientU, GradientB: TGDIPGradient; Caption:string; WideCaption: widestring; DrawCaption: Boolean; AFont: TFont;
   Images: TImageList; ImageIndex: Integer; EnabledImage: Boolean; Layout: TButtonLayout;
   DropDownButton: Boolean; DrawDwLine: Boolean; Enabled: Boolean; Focus: Boolean; DropDownPos: TDropDownPosition;
   Picture: TGDIPPicture; AntiAlias: TAntiAlias; DrawPic: Boolean; Glyph: TBitmap; ButtonDisplay: TButtonDisplay; Transparent, Hot: boolean;
   ButtonPosition: TButtonPosition; DropDownSplit, DrawBorder, OverlapText, WordWrap, AutoSize, Rounded, DropDir: Boolean; Spacing: integer;
   Trimming: TStringTrimming): TSize;
var
  graphics : TGPGraphics;
  path: TGPGraphicsPath;
  pthGrBrush: TGPPathGradientBrush;
  linGrBrush: TGPLinearGradientBrush;
  count: Integer;
  w,h,h2,h2d: Integer;
  colors : array[0..0] of TGPColor;
  fontFamily: TGPFontFamily;
  font: TGPFont;
  rectf: TGPRectF;
  stringFormat: TGPStringFormat;
  solidBrush: TGPSolidBrush;
  x1,y1,x2,y2: single;
  fs: integer;
  sizerect: TGPRectF;
  ImgX, ImgY, ImgW, ImgH: Integer;
  BtnR, DwR: TRect;
  BR1,BR2: TRect;
  DR1,DR2: TRect;
  AP: TPoint;
  szRect: TRect;
  tm: TTextMetric;
  ttf: boolean;
  Radius: integer;
  uformat: Cardinal;
begin
  BtnR := R;

  if Rounded then
    Radius := 3
  else
    Radius := 0;  

  if DropDownPos = dpRight then
  begin
    DwR := Rect(BtnR.Right - DropDownSectWidth, BtnR.Top, BtnR.Right, BtnR.Bottom);
    if DropDownButton then
      BtnR.Right := DwR.Left;
  end
  else // DropDownPos = doBottom
  begin
    DwR := Rect(BtnR.Left, BtnR.Bottom - DropDownSectWidth, BtnR.Right, BtnR.Bottom);
    if DropDownButton then
      BtnR.Bottom := DwR.Top;
  end;

  w := r.Right - r.Left;
  h := r.Bottom - r.Top;

  h2 := h div 2;

  // Create GDI+ canvas
  graphics := TGPGraphics.Create(Canvas.Handle);

  if not Transparent then
  begin

    if DropDownButton and (DrawDwLine) and DropDownSplit then
    begin
      if DropDownPos = dpRight then
      begin
        DR1 := Rect(r.Right - 12, r.Top + h2 - 1, r.Right, r.Bottom);
        DR2 := Rect(r.Right - 12, r.Top, r.Right, r.Bottom - h2);
        BR1 := Rect(r.Left, r.Top + h2 - 1, r.Right - 12, r.Bottom);
        BR2 := Rect(r.Left, r.Top, r.Right - 12, r.Bottom - h2);
      end
      else
      begin
        DR1 := Rect(r.Left, r.Bottom - 6, r.Right, r.Bottom);
        DR2 := Rect(r.Left, r.Bottom - 12, r.Right, r.Bottom - 6);

        DR2 := Rect(r.Left, r.Bottom - 12, r.Right, r.Bottom);

        h2d := (r.Bottom - r.Top - 12) div 2;
        BR1 := Rect(r.Left, r.Top + h2d - 1, r.Right, r.Bottom - 12);
        BR2 := Rect(r.Left, r.Top, r.Right, r.Bottom - 12 - h2d);
      end;

      if ButtonDisplay = bdDropDown then
      begin
        DrawButtonBackground(Canvas, Graphics, BR1, CTB, CFB, GradientB, False);
        DrawButtonBackground(Canvas, Graphics, BR2, CFU, CTU, GradientU, True);

        DrawButtonBackground(Canvas, Graphics, DR2, BrightnessColor(CFU,-10), BrightnessColor(CTU,-10), GradientU, True);
        if (DropDownPos = dpRight) then
          DrawButtonBackground(Canvas, Graphics, DR1, BrightnessColor(CTB,-10), BrightnessColor(CFB,-10), GradientB, False);
      end
      else
      begin
        DrawButtonBackground(Canvas, Graphics, BR1, BrightnessColor(CTB,-10), BrightnessColor(CFB,-10), GradientB, False);
        DrawButtonBackground(Canvas, Graphics, BR2, BrightnessColor(CFU,-10), BrightnessColor(CTU,-10), GradientU, True);

        DrawButtonBackground(Canvas, Graphics, DR2, CFU, CTU, ggRadial, True);
        if DropDownPos = dpRight then
          DrawButtonBackground(Canvas, Graphics, DR1, CTB, CFB, GradientB, False);
      end;
    end
    else
    begin
      DrawButtonBackground(Canvas, Graphics, Rect(r.left, r.Top + h2 - 1, r.Right, r.Bottom), CTB, CFB, GradientB, False);
      DrawButtonBackground(Canvas, Graphics, Rect(r.Left, r.Top, r.Right, r.Bottom - h2), CFU, CTU, GradientU, True);
    end;

  end;

  graphics.SetSmoothingMode(SmoothingModeAntiAlias);

  if not Transparent and DrawBorder then
  begin
    case ButtonPosition of
    bpStandalone: DrawRoundRect2(Graphics, PC, r.Left, r.Top, r.Right - 1, r.Bottom - 1, Radius);
    bpLeft: DrawOpenRoundRectLeft(Graphics, PC, r.Left, r.Top, r.Right - 1, r.Bottom - 1, Radius);
    bpRight: DrawOpenRoundRectRight(Graphics, PC, r.Left, r.Top, r.Right - 1, r.Bottom - 1, Radius, Hot);
    bpMiddle: DrawOpenRoundRectMiddle(Graphics, PC, r.Left, r.Top, r.Right - 1, r.Bottom - 1, Radius, Hot);
    end;
  end;

  if Focus then // Draw focus line
  begin
    graphics.SetSmoothingMode(SmoothingModeAntiAlias);
    DrawRoundRect2(graphics, $E4AD89,r.Left + 1,r.Top + 1, r.Right - 3, r.Bottom - 3, Radius);
    graphics.SetSmoothingMode(SmoothingModeAntiAlias);
    DrawDottedRoundRect(graphics, clGray,r.Left + 2,r.Top + 2, r.Right - 5, r.Bottom - 5, Radius);
  end;

  fontFamily := TGPFontFamily.Create(AFont.Name);

  if (fontFamily.Status in [FontFamilyNotFound, FontStyleNotFound]) then
  begin
    fontFamily.Free;
    fontFamily := TGPFontFamily.Create('Arial');
  end;


  fs := 0;

  ImgX := 0;
  ImgY := 0;
  ImgH := 0;
  ImgW := 0;

  if (fsBold in AFont.Style) then
    fs := fs + 1;
  if (fsItalic in AFont.Style) then
    fs := fs + 2;
  if (fsUnderline in AFont.Style) then
    fs := fs + 4;

  if Assigned(Glyph) and not Glyph.Empty and (Glyph.Width > 1) and (Glyph.Height > 1) then
  begin
    ImgW := Glyph.Width;
    ImgH := Glyph.Height;
  end
  else if (Picture <> nil) and not Picture.Empty then
  begin
    Picture.GetImageSizes;
    ImgW := Picture.Width;
    ImgH := Picture.Height;
  end
  else
  begin
    if (ImageIndex > -1) and Assigned(Images) then
    begin
      ImgW := Images.Width;
      ImgH := Images.Height;
    {end
    else if Assigned(ToolImage) and not (ToolImage.Empty) and (ToolImage.Width > 1) then
    begin
      ImgW := ToolImage.Width;
      ImgH := ToolImage.Height; }
    end;
  end;

  if (ImgW > 0) then
    ImgW := ImgW + Spacing;

  Result.cx := ImgW;
  Result.cy := ImgH;

  if (Caption <> '') or (WideCaption <> '') then
  begin
    Canvas.Font.Name := AFont.Name;

    ttf := false;

    GetTextMetrics(Canvas.Handle, tm);

    if ((tm.tmPitchAndFamily AND TMPF_VECTOR) = TMPF_VECTOR) then
    begin
      if not ((tm.tmPitchAndFamily AND TMPF_DEVICE) = TMPF_DEVICE) then
      begin
        ttf := true;
      end
    end;

    if Screen.Fonts.IndexOf(AFont.Name) = -1 then
      ttf := false;

    font := TGPFont.Create(fontFamily, AFont.Size , fs, UnitPoint);

    w := BtnR.Right - BtnR.Left;
    h := BtnR.Bottom - BtnR.Top;

    x1 := r.Left;
    y1 := r.Top;
    x2 := w;
    y2 := h;

    if AutoSize then
    begin
      x2 := 4096;
      y2 := 4096;
    end;

    rectf := MakeRect(x1,y1,x2,y2);

    if WordWrap then
      stringFormat := TGPStringFormat.Create(0)
    else
      stringFormat := TGPStringFormat.Create(GDIP_NOWRAP);

    if Enabled then
      solidBrush := TGPSolidBrush.Create(ColorToARGB(AFont.Color))
    else
      solidBrush := TGPSolidBrush.Create(ColorToARGB(clGray));

    // Center-justify each line of text.
   // stringFormat.SetAlignment(StringAlignmentCenter);
    case Layout of
      blGlyphLeftAdjusted: stringFormat.SetAlignment(StringAlignmentNear);
      blGlyphRightAdjusted: stringFormat.SetAlignment(StringAlignmentFar);
      else stringFormat.SetAlignment(StringAlignmentCenter);
    end;

    // Center the block of text (top to bottom) in the rectangle.
    
    case Layout of
      blGlyphTopAdjusted: stringFormat.SetLineAlignment(StringAlignmentNear);
      blGlyphBottomAdjusted: stringFormat.SetLineAlignment(StringAlignmentFar);
      else stringFormat.SetLineAlignment(StringAlignmentCenter);
    end;
    
    stringFormat.SetHotkeyPrefix(HotkeyPrefixShow);
    stringFormat.SetTrimming(Trimming);

    case AntiAlias of
    aaClearType:graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
    aaAntiAlias:graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
    end;

    if (AntiAlias = aaNone) or not ttf then
    begin
      Canvas.Font.Assign(AFont);
      szRect.Left := round(rectf.X);
      szRect.Top := round(rectf.Y);

      szRect.Right := szRect.Left + 2;
      szRect.Bottom := DrawText(Canvas.Handle,PChar(Caption),Length(Caption), szrect, DT_CALCRECT or DT_LEFT or DT_SINGLELINE or DT_VCENTER);

      case Layout of
        blGlyphLeft:
        begin
          sizeRect.X := (w - (szRect.Right - szRect.Left) - ImgW) div 2;
          sizeRect.Y := szRect.Top;
        end;
        blGlyphLeftAdjusted:
        begin
          sizeRect.X := szRect.Left;
          sizeRect.Y := szRect.Top;
        end;
        blGlyphTop:
        begin
          sizeRect.X := szRect.Left;
          sizeRect.Y := (h - (szRect.Bottom - szRect.Top) - ImgH - 2) div 2;
        end;
        blGlyphTopAdjusted:
        begin
          sizeRect.X := szRect.Left;
          sizeRect.Y := szRect.Top;
        end;
        blGlyphRight:
        begin
          sizeRect.X := szRect.Left;
          sizeRect.Y := szRect.Top;
        end;
        blGlyphRightAdjusted:
        begin
          sizeRect.X := szRect.Left;
          sizeRect.Y := szRect.Top;
        end;
        blGlyphBottom:
        begin
          sizeRect.X := szRect.Left;
          sizeRect.Y := szRect.Top;
        end;
        blGlyphBottomAdjusted:
        begin
          sizeRect.X := szRect.Left;
          sizeRect.Y := szRect.Top;
        end;
      end;
      sizeRect.Width := szRect.Right - szRect.Left;
      sizeRect.Height := szRect.Bottom - szRect.Top;
    end
    else
    begin
      if Caption <> '' then
        graphics.MeasureString(Caption, Length(Caption), font, rectf, stringFormat, sizerect)
      else
        graphics.MeasureString(WideCaption, Length(WideCaption), font, rectf, stringFormat, sizerect);
    end;

    Result.cx := ImgW + Spacing + round(sizerect.Width);
    Result.cy := Max(ImgH + Spacing, Spacing + round(sizerect.Height));

    if not AutoSize then
    begin
      if not WordWrap then
      begin
        x2 := w;
        y2 := h;
        rectf := MakeRect(x1,y1,x2,y2);
      end;

//      if (ImgW > 0) then
      begin
        case Layout of
          blGlyphLeft:
          begin
            if (AntiAlias = aaNone) or not ttf then
            begin
              x1 := sizeRect.X + ImgW;
              x2 := w - 2 - ImgW;
              ImgX := round(sizeRect.X);
            end
            else
            begin
              x1 := r.Left + 2 + ImgW;
              x2 := w - 2 - ImgW;
              ImgX := round(sizerect.X - ImgW div 2);
            end;
            if ImgX < 2 then ImgX := 2;
            ImgY := r.Top + Max(0, (h - ImgH) div 2);
          end;
          blGlyphLeftAdjusted:
          begin
            x1 := r.Left + 2 + ImgW;
            x2 := w - 2 - ImgW;

            ImgX := round(sizerect.X - ImgW div 2);
            if ImgX < 2 then ImgX := 2;
            ImgY := r.Top + Max(0, (h - ImgH) div 2);
          end;
          blGlyphTop:
          begin
            if (AntiAlias = aaNone) or not ttf then
            begin
              y1 := r.Top + ImgH;
 //             y1 := sizeRect.Y + ImgH;
              y2 := h - 2 - ImgH;

              ImgX := r.Left + Max(0, (w - ImgW) div 2);
//              ImgY := round(sizeRect.Y);
              ImgY := round(y2 - sizerect.Height);
              ImgY := Max(0, ImgY div 2);
              ImgY := round(y1) - ImgH + ImgY - 4;
            end
            else
            begin
              y1 := r.Top + ImgH;
              y2 := h - 2 - ImgH;
              ImgX := r.Left + Max(0, (w - ImgW) div 2);
              ImgY := round(y2 - sizerect.Height);
              ImgY := Max(0, ImgY div 2);
              ImgY := round(y1) - ImgH + ImgY;
            end;
            if ImgY < 2 then ImgY := 2;
          end;
          blGlyphTopAdjusted:
          begin
            y1 := r.Top{ + 2} + ImgH;
            y2 := h - 2 - ImgH;

            ImgX := r.Left + Max(0, (w - ImgW) div 2);
            if Layout = blGlyphTopAdjusted then
              ImgY := 0 //force to top margin
            else
              ImgY := round(y2 - sizerect.Height);
            ImgY := Max(0, ImgY div 2);
            ImgY := round(y1) - ImgH + ImgY; //round(sizerect.Height) - ImgY - 4;
            if ImgY < 2 then ImgY := 2;
          end;
          blGlyphRight, blGlyphRightAdjusted:
          begin
            x1 := 2;
            x2 := w - 4 - ImgW;
            if Layout = blGlyphRightAdjusted then
              ImgX := w - ImgW - 2
            else
            begin

               ImgX := round(X2 - sizerect.width);
               ImgX := Max(0, ImgX div 2);
               ImgX := ImgX + round(sizerect.width) + 4;
               if ImgX > (w - ImgW) then
                 ImgX := w - ImgW - 2;
            end;
            ImgY := r.Top + Max(0, (h - ImgH) div 2);
          end;
          blGlyphBottom:
          begin
            if (AntiAlias = aaNone) or not ttf then
            begin
              y1 := 2;
              y2 := h - 2 - ImgH;

              ImgX := r.Left + Max(0, (w - ImgW) div 2);
              ImgY := round(y2 - sizerect.Height);
              ImgY := Max(0, ImgY div 2);
              ImgY := round(sizerect.Height + 5) + ImgY;
              if ImgY > (h - ImgH) then ImgY := h - ImgH - 2;
            end
            else
            begin
              y1 := 2;
              y2 := h - 2 - ImgH;

              ImgX := r.Left + Max(0, (w - ImgW) div 2);
              ImgY := round(y2 - sizerect.Height);
              ImgY := Max(0, ImgY div 2);
              ImgY := round(sizerect.Height + 2) + ImgY;
              if ImgY > (h - ImgH) then ImgY := h - ImgH - 2;
            end;
          end;
          blGlyphBottomAdjusted:
          begin
            if (AntiAlias = aaNone) or not ttf then
            begin
              y1 := 2;
              y2 := h - 4 - ImgH;

              ImgX := r.Left + Max(0, (w - ImgW) div 2);
              ImgY := (h - ImgH - 2);
            end
            else
            begin
              y1 := 2;
              y2 := h - 2 - ImgH;

              ImgX := r.Left + Max(0, (w - ImgW) div 2);
              if Layout = blGlyphBottomAdjusted then
                ImgY := h; //force to bottom margin

              ImgY := Max(0, ImgY div 2);
              ImgY := round(sizerect.Height + 2) + ImgY;
              if ImgY > (h - ImgH) then ImgY := h - ImgH - 2;
            end;
          end;
        end;
      end;

      if OverlapText then
        rectf := MakeRect(r.Left, r.Top, r.Right, r.Bottom)
      else
        rectf := MakeRect(x1, y1, x2, y2);

      if DrawPic and OverlapText then
      begin
        if Assigned(Glyph) and not Glyph.Empty and (Glyph.Width > 1) and (Glyph.Height > 1) then
          Canvas.Draw(ImgX, ImgY, Glyph);
      end;

      if DrawCaption then
      begin
        if (AntiAlias = aaNone) or not ttf then
        begin
          szRect.Left := round(rectf.X);
          szRect.Top := round(rectf.Y);
          szRect.Right := szRect.Left + round(rectf.Width);
          szRect.Bottom := szRect.Top + round(rectf.Height);
          Canvas.Brush.Style := bsClear;
          uformat := DT_VCENTER or DT_SINGLELINE;           
          case Layout of
            blGlyphLeft:
            begin
              uformat := DT_VCENTER or DT_SINGLELINE or DT_LEFT;
              szrect.Left := szrect.Left;
            end;
            blGlyphLeftAdjusted:
            begin
              uformat := DT_VCENTER or DT_SINGLELINE or DT_LEFT;
              szrect.Left := szrect.Left + 2;
            end;
            blGlyphTop:
            begin
              uformat := DT_TOP or DT_SINGLELINE or DT_CENTER or DT_VCENTER;
            end;
            blGlyphTopAdjusted: uformat := DT_TOP or DT_SINGLELINE or DT_CENTER;
            blGlyphRight: uformat := DT_VCENTER or DT_SINGLELINE or DT_CENTER;
            blGlyphRightAdjusted: uformat := DT_VCENTER or DT_SINGLELINE or DT_RIGHT;
            blGlyphBottom: uformat := DT_VCENTER or DT_SINGLELINE or DT_CENTER;
            blGlyphBottomAdjusted: uformat := DT_BOTTOM or DT_SINGLELINE or DT_CENTER;
          end;
          DrawText(Canvas.Handle,PChar(Caption),Length(Caption), szrect, uformat)
        end
        else
        begin
          if (Caption <> '') then
            graphics.DrawString(Caption, Length(Caption), font, rectf, stringFormat, solidBrush)
          else
            graphics.DrawString(WideCaption, Length(WideCaption), font, rectf, stringFormat, solidBrush);
        end;
      end;
    end;

    stringformat.Free;
    solidBrush.Free;
    font.Free;
  end;

  fontFamily.Free;

  if not AutoSize then
  begin
    if DropDownButton then
    begin
      if DropDownPos = dpRight then
        w := w - 8
      else
        h := h - 8;
    end;

    if DrawPic and not OverlapText then
    begin
      if Assigned(Glyph) and not Glyph.Empty and (Glyph.Width > 1) and (Glyph.Height > 1) then
      begin
         if (Caption = '') and (WideCaption = '') then
           Canvas.Draw(r.Left + Max(0, (w - ImgW) div 2), r.Top + Max(0, (h - ImgH) div 2), Glyph)
         else
           Canvas.Draw(ImgX, ImgY, Glyph);
      end
      else
        if (Picture <> nil) and not Picture.Empty then
        begin
           if (Caption = '') and (WideCaption = '') then
             Canvas.Draw(r.Left + Max(0, (w - ImgW) div 2), r.Top + Max(0, (h - ImgH) div 2), Picture)
           else
             Canvas.Draw(ImgX, ImgY, Picture);
        end
        else
          if (ImageIndex <> -1) and Assigned(Images) then
          begin
            if (Caption = '') and (WideCaption = '') then
              Images.Draw(Canvas, r.Left + Max(0, (w - Images.Width) div 2), r.Top + Max(0, (h - Images.Height) div 2), ImageIndex, EnabledImage)
            else
            begin
              Images.Draw(Canvas, ImgX, ImgY, ImageIndex, EnabledImage);
            end;
            {end
            else if Assigned(ToolImage) and not (ToolImage.Empty) and (ToolImage.Width > 1) then
            begin
              if Caption = '' then
                Canvas.Draw(r.Left + Max(0, (w - ImgW) div 2), r.Top + Max(0, (h - ImgH) div 2), ToolImage)
              else
                Canvas.Draw(ImgX, ImgY, ToolImage); }
          end;
    end;


    Canvas.Brush.Style := bsClear;

    if DropDownButton then
    begin
      if DrawDwLine and DropDownSplit then
      begin
        Canvas.Pen.Color := ColorToRGB(PC);
        if (DropDownPos = dpRight) then
        begin
          Canvas.MoveTo(DwR.Left, DwR.Top);
          Canvas.LineTo(DwR.Left, DwR.Bottom);
        end
        else
        begin
          Canvas.MoveTo(DwR.Left, DwR.Top);
          Canvas.LineTo(DwR.Right, DwR.Top);
        end;
      end;

      AP.X := DwR.Left + ((DwR.Right - DwR.Left - 5) div 2);
      AP.Y := DwR.Top + ((DwR.Bottom - DwR.Top - 3) div 2) + 1;
      
      if not Enabled then
        DrawArrow(Canvas, AP, clGray, clWhite, DropDir)
      else
        DrawArrow(Canvas, AP, clBlack, clWhite, DropDir);
    end;
  end;

  graphics.Free;
end;

//------------------------------------------------------------------------------

procedure DrawMaximize(Canvas: TCanvas; R: TRect; Clr: TColor; HorzDir: Boolean);
var
  x, y: Integer;
begin
  with Canvas do
  begin
    x := (R.Right - R.Left - 8) div 3;
    y := (R.Bottom - R.Top - 8) div 3;

    Pen.Color := Clr;

    if HorzDir then
    begin
      MoveTo(R.Left + 2+x, R.Top+y);
      LineTo(R.Left + 8+x, R.Top+y);
      MoveTo(R.Left + 2+x, R.Top + 1+y);
      LineTo(R.Left + 8+x, R.Top + 1+y);
      MoveTo(R.Left + 8+x, R.Top+y);
      LineTo(R.Left + 8+x, R.Top + 6+y);

      MoveTo(R.Left+x, R.Top + 3+y);
      LineTo(R.Left + 7+x, R.Top + 3+y);
      MoveTo(R.Left+x, R.Top + 4+y);
      LineTo(R.Left + 7+x, R.Top + 4+y);
      MoveTo(R.Left+x, R.Top + 4+y);
      LineTo(R.Left+x, R.Top + 8+y);
      LineTo(R.Left + 6+x, R.Top + 8+y);
      LineTo(R.Left + 6+x, R.Top + 4+y);
    end
    else   // TODO: update Center pos below
    begin
      MoveTo(R.Right - 5, R.Top + 2);
      LineTo(R.Right - 5, R.Top + 8);
      MoveTo(R.Right - 6, R.Top + 2);
      LineTo(R.Right - 6, R.Top + 8);
      MoveTo(R.Right - 5, R.Top + 8);
      LineTo(R.Right - 11, R.Top + 8);

      MoveTo(R.Right - 8, R.Top);
      LineTo(R.Right - 8, R.Top + 7);
      MoveTo(R.Right - 9, R.Top);
      LineTo(R.Right - 9, R.Top + 7);
      MoveTo(R.Right - 9, R.Top);
      LineTo(R.Right - 13, R.Top);
      LineTo(R.Right - 13, R.Top + 6);
      LineTo(R.Right - 9, R.Top + 6);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure DrawNormalIcon(Canvas: TCanvas; R: TRect; Clr: TColor; HorzDir: Boolean);
var
  x, y: Integer;
begin
  with Canvas do
  begin
    x := (R.Right - R.Left - 8) div 3;
    y := (R.Bottom - R.Top - 8) div 3;

    Pen.Color := Clr;

    if HorzDir then
    begin
      MoveTo(R.Left+x, R.Top+1+y);
      LineTo(R.Left + 9+x, R.Top+1+y);
      MoveTo(R.Left+x, R.Top + 2+y);
      LineTo(R.Left + 9+x, R.Top + 2+y);
      MoveTo(R.Left+x, R.Top + 2+y);
      LineTo(R.Left+x, R.Top + 8+y);
      LineTo(R.Left + 8+x, R.Top + 8+y);
      LineTo(R.Left + 8+x, R.Top + 2+y);
    end
    else   // TODO: update Center pos below
    begin
      MoveTo(R.Right - 8, R.Top);
      LineTo(R.Right - 8, R.Top + 7);
      MoveTo(R.Right - 9, R.Top);
      LineTo(R.Right - 9, R.Top + 7);
      MoveTo(R.Right - 9, R.Top);
      LineTo(R.Right - 13, R.Top);
      LineTo(R.Right - 13, R.Top + 6);
      LineTo(R.Right - 9, R.Top + 6);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure DrawMinimize(Canvas: TCanvas; R: TRect; Clr: TColor; HorzDir: Boolean);
var
  x, y: Integer;
begin
  with Canvas do
  begin
    x := (R.Right - R.Left - 6) div 3;
    y := (R.Bottom - R.Top) div 2;

    Pen.Color := Clr;

    if HorzDir then
    begin
      MoveTo(R.Left+x, R.Top+y);
      LineTo(R.Left + 6+x, R.Top+y);
      MoveTo(R.Left+x, R.Top + 1+y);
      LineTo(R.Left + 6+x, R.Top + 1+y);
    end
    else
    begin
      MoveTo(R.Left, R.Top);
      LineTo(R.Left, R.Top + 6);
      MoveTo(R.Left + 1, R.Top);
      LineTo(R.Left + 1, R.Top + 6);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure RemoveNonFocusCtrlFromList(aList: TList);
var
  i: Integer;
begin
  if not Assigned(aList) then
    Exit;
  i := 0;
  while i < aList.Count do
  begin
    if (TControl(aList.Items[i]) is THintWindow) or (TControl(aList.Items[i]) is TAdvToolBarContainer)
       or ((TControl(aList.Items[i]) is TWinControl) and (not TWinControl(aList.Items[i]).CanFocus)) then
    begin
      aList.Delete(i);
    end
    else
      Inc(i);
  end;
end;

//------------------------------------------------------------------------------

{ TCustomAdvToolBarStyler }

procedure TCustomAdvToolBarStyler.AddControl(AControl: TCustomControl);
begin
  if Assigned(AControl) then
  begin
    FControlList.Add(AControl);
    aControl.FreeNotification(self);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.Assign(Source: TPersistent);
begin
  if Source is TCustomAdvToolBarStyler then
  begin
    if Assigned(FCurrentAdvMenuStyler) and Assigned(TCustomAdvToolBarStyler(Source).AdvMenuStyler) then
      FCurrentAdvMenuStyler.Assign(TCustomAdvToolBarStyler(Source).AdvMenuStyler);

    Color.Assign(TCustomAdvToolBarStyler(Source).Color);
    DockColor.Assign(TCustomAdvToolBarStyler(Source).DockColor);
    
    BackGround.Assign(TCustomAdvToolBarStyler(Source).BackGround);
    BackGroundTransparent := TCustomAdvToolBarStyler(Source).BackGroundTransparent;
    BackGroundDisplay := TCustomAdvToolBarStyler(Source).BackGroundDisplay;
    Font.Assign(TCustomAdvToolBarStyler(Source).Font);

    DragGripStyle := TCustomAdvToolBarStyler(Source).DragGripStyle;
    DragGripImage.Assign(TCustomAdvToolBarStyler(Source).DragGripImage);

    RightHandleImage.Assign(TCustomAdvToolBarStyler(Source).RightHandleImage);

    FloatingWindowBorderColor := TCustomAdvToolBarStyler(Source).FloatingWindowBorderColor;
    FloatingWindowBorderWidth := TCustomAdvToolBarStyler(Source).FloatingWindowBorderWidth;
    CaptionAppearance.Assign(TCustomAdvToolBarStyler(Source).CaptionAppearance);
    {CaptionColor := TCustomAdvToolBarStyler(Source).CaptionColor;
    CaptionColorTo := TCustomAdvToolBarStyler(Source).CaptionColorTo;
    CaptionTextColor := TCustomAdvToolBarStyler(Source).CaptionTextColor;
    CaptionBorderColor := TCustomAdvToolBarStyler(Source).CaptionBorderColor;}

    //Style := TCustomAdvToolBarStyler(Source).Style;
    ButtonAppearance := TCustomAdvToolBarStyler(Source).ButtonAppearance;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

constructor TCustomAdvToolBarStyler.Create(AOwner: TComponent);
begin
  inherited;
  FControlList := TDbgList.Create;
  FBackGround := TBitMap.Create;
  FBackGroundTransparent := true;
  FBackGroundDisplay := bdTile;
  FFont := TFont.Create;
  FDragGripStyle := dsDots;
  FDragGripImage := TBitMap.Create;
  //FPopupIndicatorStyle:= psOffice2003;
  FRightHandleImage := TBitMap.Create;
  //FToolBarStyle := bsCustom;
  FTransparent := False;
  FRoundEdges := True;
  FRightHandleColor := RGB(158, 158, 158); //RGB(141, 141, 141);
  FRightHandleColorHot := RGB(182, 189, 210);
  FRightHandleColorDown := $76C1FF;
  FRightHandleColorDownTo:= RGB(255, 160, 45);
  FFloatingWindowBorderColor := RGB(109, 109, 109); ;
  FFloatingWindowBorderWidth := 2;
  FCaptionAppearance := TCaptionAppearance.Create;
  FCaptionAppearance.OnChange := OnCaptionAppearanceChanged;
 { FCaptionColor := RGB(128, 128, 128); //clGray;
  FCaptionColorTo := clNone;
  FCaptionTextColor := clWhite;
  FCaptionBorderColor := clNone;
  FCaptionBorderColorHot := clNone;
  FCaptionColorHot := clNone;
  FCaptionColorHotTo := clNone;
  FCaptionTextColorHot := clWhite; }

  FBevel:= bvNone;

  FColor := TVistaGradientBackground.Create;
  FDockColor := TGradientBackground.Create;

  FColor.OnChange := BackgroundChanged;
  FDockColor.OnChange := BackgroundChanged;

  FButtonAppearance := TButtonAppearance.Create;

  FInternalAdvMenuStyler := TAdvMenuStyler.Create(self);
  FInternalAdvMenuStyler.Name := 'InternalMenuStyler';
  //FAdvMenuStyler := FInternalAdvMenuStyler;
  FAdvMenuStyler := nil;
  FCurrentAdvMenuStyler := FInternalAdvMenuStyler;

  FBorderColor := clNone;
  FBorderColorHot := clNone;
  FColorHot := TVistaGradientBackground.Create;
  FColorHot.Color := clNone;
  FColorHot.ColorTo := clNone;

  FCaptionFont := TFont.Create;

  FContainerAppearance := TContainerAppearance.Create;
  FContainerAppearance.OnChange := OnContainerAppearanceChanged;

  FGlowButtonAppearance := TGlowButtonAppearance.Create;
  FGlowButtonAppearance.onChange := OnGlowButtonAppearanceChanged;

  FCompactGlowButtonAppearance := TGlowButtonAppearance.Create;
  FCompactGlowButtonAppearance.OnChange := OnGlowButtonAppearanceChanged;

  FPagerCaption := TVistaTextBackground.Create;
  FPagerCaption.OnChange := OnPagerCaptionChanged;
  FTabAppearance := TTabAppearance.Create;
  FTabAppearance.OnChange := OnTabAppearanceChanged;
  FPageAppearance := TVistaPageBackground.Create;
  FPageAppearance.OnChange := OnPageAppearanceChanged;
  FGroupAppearance := TGroupAppearance.Create;
  FGroupAppearance.OnChange := OnGroupAppearanceChanged;

  FQATAppearance := TQATAppearance.Create;
  FQATAppearance.OnChange := OnQATAppearanceChanged;
  //Style := bsOffice2003Blue;
  //FTransparent:= true;

  FSystemFont := true;
  if IsVista then
  begin
    FFont.Name := 'Segoe UI';
    FCaptionFont.Name := 'Segoe UI';
  end
  else
  begin
    FFont.Name := 'Tahoma';
    FCaptionFont.Name := 'Tahoma';
  end;
end;

//------------------------------------------------------------------------------

destructor TCustomAdvToolBarStyler.Destroy;
begin
  {$IFDEF DELPHI2006_LVL}
  ReleaseAllControls;
  {$ENDIF}
  FFont.Free;
  FBackGround.Free;
  FDragGripImage.Free;
  FRightHandleImage.Free;
  FControlList.Free;
  FButtonAppearance.Free;
  FInternalAdvMenuStyler.Free;
  FColor.Free;
  FDockColor.Free;
  FColorHot.Free;
  FCaptionFont.Free;
  FContainerAppearance.Free;
  FGlowButtonAppearance.Free;
  FCompactGlowButtonAppearance.Free;
  FPagerCaption.Free;
  FTabAppearance.Free;
  FPageAppearance.Free;
  FGroupAppearance.Free;
  FCaptionAppearance.Free;
  FQATAppearance.Free;  
  inherited;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.ReleaseAllControls;
var
  i, j, c: Integer;
  ctrl : TCustomControl;
begin
  i := 0;
  c := FControlList.Count;
  j := 0;
  while (i < FControlList.Count) do
  begin
    ctrl := TCustomControl(FControlList[i]);
    if not (ctrl is TCustomControl) then
    begin
      Inc(i);
      Continue;
    end;

    if ctrl is TAdvDockPanel then
    begin
      if not (csDestroying in TAdvDockPanel(ctrl).ComponentState) and (TAdvDockPanel(ctrl).ToolBarStyler = self) then
        TAdvDockPanel(ctrl).ToolBarStyler := nil
      else
        Inc(i);
    end
    else if (ctrl is TAdvToolBarPager) then
    begin
      if not (csDestroying in TAdvToolBarPager(ctrl).ComponentState) and (TAdvToolBarPager(ctrl).ToolBarStyler = Self) then
        TAdvToolBarPager(ctrl).ToolBarStyler := nil
      else
        Inc(i);
    end
    else
      Inc(i);
    Inc(j);
    if (j >= c) then
      Break;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.UpdateStyle;
begin
  Change(2);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.Change(PropID: integer);
var
  i: integer;
begin
  for i := 0 to FControlList.Count - 1 do
  begin
    if not (TObject(FControlList[i]) is TCustomControl) then
      Continue;

    if TCustomControl(FControlList[i]) is TAdvDockPanel then
      TAdvDockPanel(FControlList[i]).UpdateMe(PropID)
    else if TCustomControl(FControlList[i]) is TAdvToolBar then
    begin
      if TAdvToolBar(FControlList[i]).Compact then
      begin
        TAdvToolBar(FControlList[i]).FCompactWindow.AdvToolBar.UpdateMe(PropID);
        TAdvToolBar(FControlList[i]).UpdateMe(PropID);
      end
      else
        TAdvToolBar(FControlList[i]).UpdateMe(PropID)
    end
    else if (TCustomControl(FControlList[i]) is TAdvToolBarPager) then
      TAdvToolBarPager(FControlList[i]).UpdateMe(PropID);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.Notification(AComponent: TComponent;
  Operation: TOperation);
var
  i: integer;
begin
  inherited;
  if not (csDestroying in ComponentState) and (Operation = opRemove) then
  begin
    if AComponent = AdvMenuStyler then
      AdvMenuStyler := nil
    else
    begin
      i := FControlList.IndexOf(AComponent);
      if i >= 0 then
        FControlList.Remove(AComponent);
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.RemoveControl(AControl: TCustomControl);
var
  i: integer;
begin
  i := FControlList.IndexOf(AControl);
  if i >= 0 then
    FControlList.Delete(i);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetAdvMenuStyler(
  const Value: TCustomAdvMenuStyler);
begin
  FAdvMenuStyler := Value;
  if FAdvMenuStyler = nil then
    FCurrentAdvMenuStyler := FInternalAdvMenuStyler
  else
    FCurrentAdvMenuStyler := FAdvMenuStyler;
    
  Change(6);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetBackGround(const Value: TBitMap);
begin
  FBackGround.Assign(Value);
  Change(1);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetBackGroundDisplay(
  const Value: TBackGroundDisplay);
begin
  if FBackGroundDisplay <> Value then
  begin
    FBackGroundDisplay := Value;
    Change(1);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetBackGroundTransparent(
  const Value: Boolean);
begin
  if FBackGroundTransparent <> Value then
  begin
    FBackGroundTransparent := Value;
    Change(1);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetColor(const Value: TVistaGradientBackground);
begin
  FColor.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetDragGripImage(const Value: TBitMap);
begin
  FDragGripImage.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetDragGripStyle(
  const Value: TDragGripStyle);
begin
  if FDragGripStyle <> Value then
  begin
    FDragGripStyle := Value;
    Change(5);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetFont(const Value: TFont);
begin
  FFont.Assign(Value);
  Change(1);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetRightHandleImage(
  const Value: TBitmap);
begin
  FRightHandleImage.Assign(Value);
  Change(2);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetTransparent(const Value: Boolean);
begin
  if FTransparent <> Value then
  begin
    FTransparent := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetRoundEdges(const Value: boolean);
begin
  FRoundEdges := Value;
  Change(2);
end;

procedure TCustomAdvToolBarStyler.SetSystemFont(const Value: boolean);
begin
  if (FSystemFont <> Value) then
  begin
    FSystemFont := Value;

    if Value then
    begin
      if IsVista then
      begin
        FFont.Name := 'Segoe UI';
        FCaptionFont.Name := 'Segoe UI';
      end
      else
      begin
        FFont.Name := 'Tahoma';
        FCaptionFont.Name := 'Tahoma';
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetRightHandleColor(const Value: TColor);
begin
  if FRightHandleColor <> Value then
  begin
    FRightHandleColor := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetRightHandleColorHot(const Value: TColor);
begin
  if FRightHandleColorHot <> Value then
  begin
    FRightHandleColorHot := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetRightHandleColorTo(const Value: TColor);
begin
  if (FRightHandleColorTo <> Value) then
  begin
    FRightHandleColorTo := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetRightHandleColorHotTo(const Value: TColor);
begin
  if (FRightHandleColorHotTo <> Value) then
  begin
    FRightHandleColorHotTo := Value;
    Change(2);
  end;  
end;

//------------------------------------------------------------------------------
{
procedure TCustomAdvToolBarStyler.SetCaptionBorderColor(
  const Value: TColor);
begin
  if FCaptionBorderColor <> Value then
  begin
    FCaptionBorderColor := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCaptionColor(const Value: TColor);
begin
  if FCaptionColor <> Value then
  begin
    FCaptionColor := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCaptionColorTo(const Value: TColor);
begin
  if FCaptionColorTo <> Value then
  begin
    FCaptionColorTo := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCaptionTextColor(const Value: TColor);
begin
  if FCaptionTextColor <> Value then
  begin
    FCaptionTextColor := Value;
    Change(2);
  end;
end;
}
//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetFloatingWindowBorderColor(
  const Value: TColor);
begin
  if FFloatingWindowBorderColor <> Value then
  begin
    FFloatingWindowBorderColor := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetFloatingWindowBorderWidth(
  const Value: integer);
begin
  if FFloatingWindowBorderWidth <> Value then
  begin
    FFloatingWindowBorderWidth := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetTButtonAppearance(
  const Value: TButtonAppearance);
begin
  FButtonAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetDockColor(
  const Value: TGradientBackground);
begin
  FDockColor.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.Loaded;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.BackgroundChanged(Sender: TObject);
begin
  Change(2);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetRightHandleColorDown(
  const Value: TColor);
begin
  if FRightHandleColorDown <> Value then
  begin
    FRightHandleColorDown := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetRightHandleColorDownTo(
  const Value: TColor);
begin
  if FRightHandleColorDownTo <> Value then
  begin
    FRightHandleColorDownTo := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetBevel(const Value: TPanelBevel);
begin
  if FBevel <> Value then
  begin
    FBevel := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetUseBevel(const Value: Boolean);
begin
  if FUseBevel <> Value then
  begin
    FUseBevel := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SavePropToFile(var F: TextFile);
var
  s: String;
  sl: TStringList;
begin
  sl:= TStringList.Create;

  if AutoThemeAdapt then
    s := 'True'
  else
    s := 'False';
  sl.Values['AutoThemeAdapt'] := s;
  Writeln(F, sl.CommaText);

  //AdvMenuStyler: TCustomAdvMenuStyler read FAdvMenuStyler write SetAdvMenuStyler; // PropID: 0
  //---- ButtonAppearance
  sl.Clear;
  with ButtonAppearance do
  begin
    s := 'ButtonAppearance.Color=' + ColorToString(Color);                                      Writeln(F, s);
    s := 'ButtonAppearance.ColorTo=' + ColorToString(ColorTo);                                  Writeln(F, s);
    s := 'ButtonAppearance.ColorChecked=' + ColorToString(ColorChecked);                        Writeln(F, s);
    s := 'ButtonAppearance.ColorCheckedTo=' + ColorToString(ColorCheckedTo);                    Writeln(F, s);
    s := 'ButtonAppearance.ColorDown=' + ColorToString(ColorDown);                              Writeln(F, s);
    s := 'ButtonAppearance.ColorDownTo=' + ColorToString(ColorDownTo);                          Writeln(F, s);
    s := 'ButtonAppearance.ColorHot=' + ColorToString(ColorHot);                                Writeln(F, s);
    s := 'ButtonAppearance.ColorHotTo=' + ColorToString(ColorHotTo);                            Writeln(F, s);
    s := 'ButtonAppearance.CaptionTextColor=' + ColorToString(CaptionTextColor);                Writeln(F, s);
    s := 'ButtonAppearance.CaptionTextColorHot=' + ColorToString(CaptionTextColorHot);          Writeln(F, s);
    s := 'ButtonAppearance.CaptionTextColorDown=' + ColorToString(CaptionTextColorDown);        Writeln(F, s);
    s := 'ButtonAppearance.CaptionTextColorChecked=' + ColorToString(CaptionTextColorChecked);  Writeln(F, s);

    if GradientDirection = gdHorizontal then
      s := 'ButtonAppearance.GradientDirection=' + 'gdHorizontal'
    else
      s := 'ButtonAppearance.GradientDirection=' + 'gdVertical';
    Writeln(F, s);

    if GradientDirectionHot = gdHorizontal then
      s := 'ButtonAppearance.GradientDirectionHot=' + 'gdHorizontal'
    else
      s := 'ButtonAppearance.GradientDirectionHot=' + 'gdVertical';
    Writeln(F, s);

    if GradientDirectionDown = gdHorizontal then
      s := 'ButtonAppearance.GradientDirectionDown=' + 'gdHorizontal'
    else
      s := 'ButtonAppearance.GradientDirectionDown=' + 'gdVertical';
    Writeln(F, s);

    if GradientDirectionChecked = gdHorizontal then
      s := 'ButtonAppearance.GradientDirectionChecked=' + 'gdHorizontal'
    else
      s := 'ButtonAppearance.GradientDirectionChecked=' + 'gdVertical';
    Writeln(F, s);

    s := 'ButtonAppearance.BorderColor=' + ColorToString(BorderColor);               Writeln(F, s);
    s := 'ButtonAppearance.BorderDownColor=' + ColorToString(BorderDownColor);       Writeln(F, s);
    s := 'ButtonAppearance.BorderHotColor=' + ColorToString(BorderHotColor);         Writeln(F, s);
    s := 'ButtonAppearance.BorderCheckedColor=' + ColorToString(BorderCheckedColor); Writeln(F, s);

    //--- Caption Font
    s := 'ButtonAppearance.CaptionFont.Color=' + ColorToString(CaptionFont.Color);  Writeln(F, s);
    sl.Clear;
    if fsBold in CaptionFont.Style then       sl.Add('fsBold');
    if fsItalic in CaptionFont.Style then     sl.Add('fsItalic');
    if fsUnderline in CaptionFont.Style then  sl.Add('fsUnderline');
    if fsStrikeOut in CaptionFont.Style then  sl.Add('fsStrikeOut');
    s := 'ButtonAppearance.CaptionFont.Style=' + sl.CommaText;
    Writeln(F, s);
    s := 'ButtonAppearance.CaptionFont.Size=' + InttoStr(CaptionFont.Size);    Writeln(F, s);

    sl.Clear;
    sl.Values['ButtonAppearance.CaptionFont.Name'] := CaptionFont.Name;
    s := sl.CommaText; {'ButtonAppearance.CaptionFont.Name=' + CaptionFont.Name; }             Writeln(F, s);
  end;

  //--- Color
  s := 'Color.Color=' + ColorToString(Color.Color);        Writeln(F, s);
  s := 'Color.ColorTo=' + ColorToString(Color.ColorTo);    Writeln(F, s);
  if Color.Direction = gdHorizontal then
    s := 'Color.Direction=gdHorizontal'
  else
    s := 'Color.Direction=gdVertical';
  Writeln(F, s);
  s := 'Color.Steps=' + InttoStr(Color.Steps);             Writeln(F, s);

  s := 'DockColor.Color=' + ColorToString(DockColor.Color);      Writeln(F, s);
  s := 'DockColor.ColorTo=' + ColorToString(DockColor.ColorTo);  Writeln(F, s);
  if DockColor.Direction = gdHorizontal then
    s := 'DockColor.Direction=gdHorizontal'
  else
    s := 'DockColor.Direction=gdVertical';
  Writeln(F, s);
  s := 'DockColor.Steps=' + InttoStr(DockColor.Steps);           Writeln(F, s);

  {property BackGround: TBitMap read FBackGround write SetBackGround;
  property BackGroundTransparent: Boolean read FBackGroundTransparent write SetBackGroundTransparent default true;
  property BackGroundDisplay: TBackGroundDisplay read FBackGroundDisplay write SetBackGroundDisplay default bdTile;
  }
  s := 'Font.Color=' + ColorToString(Font.Color);  Writeln(F, s);
  sl.Clear;
  if fsBold in Font.Style then       sl.Add('fsBold');
  if fsItalic in Font.Style then     sl.Add('fsItalic');
  if fsUnderline in Font.Style then  sl.Add('fsUnderline');
  if fsStrikeOut in Font.Style then  sl.Add('fsStrikeOut');
  s := 'Font.Style=' + sl.CommaText;
  Writeln(F, s);
  s := 'Font.Size=' + InttoStr(Font.Size);       Writeln(F, s);

  sl.Clear;
  sl.Values['Font.Name'] := Font.Name;
  s := sl.CommaText; {'Font.Name="' + Font.Name+'"'; }                Writeln(F, s);

  {===== AdvToolBar Properties -PropID: 2- =====}
  case DragGripStyle of
    dsDots:        s := 'DragGripStyle=dsDots';
    dsSingleLine:  s := 'DragGripStyle=dsSingleLine';
    dsDoubleLine:  s := 'DragGripStyle=dsDoubleLine';
    dsFlatDots:    s := 'DragGripStyle=dsFlatDots';
    dsNone:        s := 'DragGripStyle=dsNone';
  end;
  Writeln(F, s);
  //property DragGripImage: TBitMap read FDragGripImage write SetDragGripImage;

  //property RightHandleImage: TBitmap read FRightHandleImage write SetRightHandleImage;
  s := 'RightHandleColor=' + ColorToString(RightHandleColor);                   Writeln(F, s);
  s := 'RightHandleColorHot=' + ColorToString(RightHandleColorHot);             Writeln(F, s);
  s := 'RightHandleColorTo=' + ColorToString(RightHandleColorTo);               Writeln(F, s);
  s := 'RightHandleColorHotTo=' + ColorToString(RightHandleColorHotTo);         Writeln(F, s);
  s := 'RightHandleColorDown=' + ColorToString(RightHandleColorDown);           Writeln(F, s);
  s := 'RightHandleColorDownTo=' + ColorToString(RightHandleColorDownTo);       Writeln(F, s);

  s := 'FloatingWindowBorderColor=' + ColorToString(FloatingWindowBorderColor); Writeln(F, s);
  s := 'FloatingWindowBorderWidth=' + IntToStr(FloatingWindowBorderWidth);      Writeln(F, s);
  s := 'CaptionAppearance.CaptionColor=' + ColorToString(CaptionAppearance.CaptionColor);         Writeln(F, s);
  s := 'CaptionAppearance.CaptionColorTo=' + ColorToString(CaptionAppearance.CaptionColorTo);     Writeln(F, s);
  s := 'CaptionAppearance.CaptionTextColor=' + ColorToString(CaptionAppearance.CaptionTextColor); Writeln(F, s);
  s := 'CaptionAppearance.CaptionBorderColor=' + ColorToString(CaptionAppearance.CaptionBorderColor); Writeln(F, s);
  s := 'CaptionAppearance.CaptionColorHot=' + ColorToString(CaptionAppearance.CaptionColorHot);         Writeln(F, s);
  s := 'CaptionAppearance.CaptionColorHotTo=' + ColorToString(CaptionAppearance.CaptionColorHotTo);     Writeln(F, s);
  s := 'CaptionAppearance.CaptionTextColorHot=' + ColorToString(CaptionAppearance.CaptionTextColorHot); Writeln(F, s);
  s := 'CaptionAppearance.CaptionBorderColorHot=' + ColorToString(CaptionAppearance.CaptionBorderColorHot); Writeln(F, s);

  
  s := 'BorderColor=' + ColorToString(BorderColor);                             Writeln(F, s);
  s := 'BorderColorHot=' + ColorToString(BorderColorHot);                       Writeln(F, s);

  //--- ColorHot
  s := 'ColorHot.Color=' + ColorToString(ColorHot.Color);        Writeln(F, s);
  s := 'ColorHot.ColorTo=' + ColorToString(ColorHot.ColorTo);    Writeln(F, s);
  if ColorHot.Direction = gdHorizontal then
    s := 'ColorHot.Direction=gdHorizontal'
  else
    s := 'ColorHot.Direction=gdVertical';
  Writeln(F, s);
  s := 'ColorHot.Steps=' + InttoStr(Color.Steps);                Writeln(F, s);

  s := 'CaptionFont.Color=' + ColorToString(CaptionFont.Color);  Writeln(F, s);
  sl.Clear;
  if fsBold in CaptionFont.Style then       sl.Add('fsBold');
  if fsItalic in CaptionFont.Style then     sl.Add('fsItalic');
  if fsUnderline in CaptionFont.Style then  sl.Add('fsUnderline');
  if fsStrikeOut in CaptionFont.Style then  sl.Add('fsStrikeOut');
  s := 'CaptionFont.Style=' + sl.CommaText;
  Writeln(F, s);
  s := 'CaptionFont.Size=' + InttoStr(CaptionFont.Size);       Writeln(F, s);

  {========== AdvContainer ==========}
  s := 'ContainerAppearance.LineColor=' + ColorToString(ContainerAppearance.LineColor);     Writeln(F, s);
  sl.Clear;
  if ContainerAppearance.Line3D then
    s := 'True'
  else
    s := 'False';
  sl.Values['ContainerAppearance.Line3D'] := s;
  Writeln(F, sl.CommaText);

  {========== AdvGlowButton ===========}
  s := 'GlowButtonAppearance.BorderColor=' + ColorToString(GlowButtonAppearance.BorderColor);   Writeln(F, s);
  s := 'GlowButtonAppearance.BorderColorHot=' + ColorToString(GlowButtonAppearance.BorderColorHot);  Writeln(F, s);
  s := 'GlowButtonAppearance.BorderColorDown=' + ColorToString(GlowButtonAppearance.BorderColorDown);  Writeln(F, s);
  s := 'GlowButtonAppearance.BorderColorChecked=' + ColorToString(GlowButtonAppearance.BorderColorChecked);  Writeln(F, s);
  s := 'GlowButtonAppearance.BorderColorDisabled=' + ColorToString(GlowButtonAppearance.BorderColorDisabled);  Writeln(F, s);
  s := 'GlowButtonAppearance.Color=' + ColorToString(GlowButtonAppearance.Color);              Writeln(F, s);
  s := 'GlowButtonAppearance.ColorTo=' + ColorToString(GlowButtonAppearance.ColorTo);          Writeln(F, s);
  s := 'GlowButtonAppearance.ColorChecked=' + ColorToString(GlowButtonAppearance.ColorChecked);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorCheckedTo=' + ColorToString(GlowButtonAppearance.ColorCheckedTo);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorDisabled=' + ColorToString(GlowButtonAppearance.ColorDisabled);    Writeln(F, s);
  s := 'GlowButtonAppearance.ColorDisabledTo=' + ColorToString(GlowButtonAppearance.ColorDisabledTo); Writeln(F, s);
  s := 'GlowButtonAppearance.ColorDown=' + ColorToString(GlowButtonAppearance.ColorDown);      Writeln(F, s);
  s := 'GlowButtonAppearance.ColorDownTo=' + ColorToString(GlowButtonAppearance.ColorDownTo);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorHot=' + ColorToString(GlowButtonAppearance.ColorHot);        Writeln(F, s);
  s := 'GlowButtonAppearance.ColorHotTo=' + ColorToString(GlowButtonAppearance.ColorHotTo);    Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirror=' + ColorToString(GlowButtonAppearance.ColorMirror);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorTo=' + ColorToString(GlowButtonAppearance.ColorMirrorTo);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorHot=' + ColorToString(GlowButtonAppearance.ColorMirrorHot);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorHotTo=' + ColorToString(GlowButtonAppearance.ColorMirrorHotTo);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorDown=' + ColorToString(GlowButtonAppearance.ColorMirrorDown);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorDownTo=' + ColorToString(GlowButtonAppearance.ColorMirrorDownTo);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorChecked=' + ColorToString(GlowButtonAppearance.ColorMirrorChecked);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorCheckedTo=' + ColorToString(GlowButtonAppearance.ColorMirrorCheckedTo);    Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorDisabled=' + ColorToString(GlowButtonAppearance.ColorMirrorDisabled);  Writeln(F, s);
  s := 'GlowButtonAppearance.ColorMirrorDisabledTo=' + ColorToString(GlowButtonAppearance.ColorMirrorDisabledTo);    Writeln(F, s);

  case GlowButtonAppearance.Gradient of
    ggRadial:  s := 'GlowButtonAppearance.Gradient=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.Gradient=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.Gradient=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.Gradient=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientMirror of
    ggRadial:  s := 'GlowButtonAppearance.GradientMirror=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientMirror=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientMirror=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientMirror=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientHot of
    ggRadial:  s := 'GlowButtonAppearance.GradientHot=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientHot=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientHot=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientHot=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientMirrorHot of
    ggRadial:  s := 'GlowButtonAppearance.GradientMirrorHot=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientMirrorHot=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientMirrorHot=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientMirrorHot=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientDown of
    ggRadial:  s := 'GlowButtonAppearance.GradientDown=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientDown=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientDown=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientDown=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientMirrorDown of
    ggRadial:  s := 'GlowButtonAppearance.GradientMirrorDown=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientMirrorDown=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientMirrorDown=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientMirrorDown=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientChecked of
    ggRadial:  s := 'GlowButtonAppearance.GradientChecked=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientChecked=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientChecked=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientChecked=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientMirrorChecked of
    ggRadial:  s := 'GlowButtonAppearance.GradientMirrorChecked=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientMirrorChecked=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientMirrorChecked=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientMirrorChecked=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientDisabled of
    ggRadial:  s := 'GlowButtonAppearance.GradientDisabled=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientDisabled=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientDisabled=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientDisabled=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case GlowButtonAppearance.GradientMirrorDisabled of
    ggRadial:  s := 'GlowButtonAppearance.GradientMirrorDisabled=ggRadial';
    ggVertical: s := 'GlowButtonAppearance.GradientMirrorDisabled=ggVertical';
    ggDiagonalForward: s := 'GlowButtonAppearance.GradientMirrorDisabled=ggDiagonalForward';
    ggDiagonalBackward: s := 'GlowButtonAppearance.GradientMirrorDisabled=ggDiagonalBackward';
  end;
  Writeln(F, s);

  {========== AdvToolBarPager ===========}
  with PagerCaption do{TVistaTextBackground}
  begin
    s := 'PagerCaption.BorderColor=' + ColorToString(PagerCaption.BorderColor);      Writeln(F, s);
    s := 'PagerCaption.Color=' + ColorToString(PagerCaption.Color);      Writeln(F, s);
    s := 'PagerCaption.ColorTo=' + ColorToString(PagerCaption.ColorTo);      Writeln(F, s);
    s := 'PagerCaption.ColorMirror=' + ColorToString(PagerCaption.ColorMirror);      Writeln(F, s);
    s := 'PagerCaption.ColorMirrorTo=' + ColorToString(PagerCaption.ColorMirrorTo);      Writeln(F, s);

    case PagerCaption.Gradient of
      ggRadial:  s := 'PagerCaption.Gradient=ggRadial';
      ggVertical: s := 'PagerCaption.Gradient=ggVertical';
      ggDiagonalForward: s := 'PagerCaption.Gradient=ggDiagonalForward';
      ggDiagonalBackward: s := 'PagerCaption.Gradient=ggDiagonalBackward';
    end;
    Writeln(F, s);
    
    case PagerCaption.GradientMirror of
      ggRadial:  s := 'PagerCaption.GradientMirror=ggRadial';
      ggVertical: s := 'PagerCaption.GradientMirror=ggVertical';
      ggDiagonalForward: s := 'PagerCaption.GradientMirror=ggDiagonalForward';
      ggDiagonalBackward: s := 'PagerCaption.GradientMirror=ggDiagonalBackward';
    end;
    Writeln(F, s);

    s := 'PagerCaption.Steps=' + InttoStr(PagerCaption.Steps);       Writeln(F, s);

    s := 'PagerCaption.TextColor=' + ColorToString(PagerCaption.TextColor);      Writeln(F, s);

    // PagerCaption.Font
    s := 'PagerCaption.Font.Color=' + ColorToString(PagerCaption.Font.Color);  Writeln(F, s);
    sl.Clear;
    if fsBold in PagerCaption.Font.Style then       sl.Add('fsBold');
    if fsItalic in PagerCaption.Font.Style then     sl.Add('fsItalic');
    if fsUnderline in PagerCaption.Font.Style then  sl.Add('fsUnderline');
    if fsStrikeOut in PagerCaption.Font.Style then  sl.Add('fsStrikeOut');
    s := 'PagerCaption.Font.Style=' + sl.CommaText;
    Writeln(F, s);
    s := 'PagerCaption.Font.Size=' + InttoStr(PagerCaption.Font.Size);    Writeln(F, s);

    sl.Clear;
    sl.Values['PagerCaption.Font.Name'] := PagerCaption.Font.Name;
    s := sl.CommaText;                  Writeln(F, s);
  end;

  with TabAppearance do {TTabAppearance}
  begin
       {TGradientBackground}
    s := 'TabAppearance.BackGround.Color=' + ColorToString(TabAppearance.BackGround.Color);        Writeln(F, s);
    s := 'TabAppearance.BackGround.ColorTo=' + ColorToString(TabAppearance.BackGround.ColorTo);    Writeln(F, s);
    if TabAppearance.BackGround.Direction = gdHorizontal then
      s := 'TabAppearance.BackGround.Direction=gdHorizontal'
    else
      s := 'TabAppearance.BackGround.Direction=gdVertical';
    Writeln(F, s);
    s := 'TabAppearance.BackGround.Steps=' + InttoStr(TabAppearance.BackGround.Steps);             Writeln(F, s);

    s := 'TabAppearance.BorderColor=' + ColorToString(TabAppearance.BorderColor);      Writeln(F, s);
    s := 'TabAppearance.BorderColorHot=' + ColorToString(TabAppearance.BorderColorHot);      Writeln(F, s);
    s := 'TabAppearance.BorderColorSelected=' + ColorToString(TabAppearance.BorderColorSelected);      Writeln(F, s);
    s := 'TabAppearance.BorderColorSelectedHot=' + ColorToString(TabAppearance.BorderColorSelectedHot);      Writeln(F, s);
    s := 'TabAppearance.BorderColorDown=' + ColorToString(TabAppearance.BorderColorDown);      Writeln(F, s);
    s := 'TabAppearance.BorderColorDisabled=' + ColorToString(TabAppearance.BorderColorDisabled);      Writeln(F, s);
    s := 'TabAppearance.Color=' + ColorToString(TabAppearance.Color);      Writeln(F, s);
    s := 'TabAppearance.ColorTo=' + ColorToString(TabAppearance.ColorTo);      Writeln(F, s);
    s := 'TabAppearance.ColorSelected=' + ColorToString(TabAppearance.ColorSelected);      Writeln(F, s);
    s := 'TabAppearance.ColorSelectedTo=' + ColorToString(TabAppearance.ColorSelectedTo);      Writeln(F, s);
    s := 'TabAppearance.ColorDisabled=' + ColorToString(TabAppearance.ColorDisabled);      Writeln(F, s);
    s := 'TabAppearance.ColorDisabledTo=' + ColorToString(TabAppearance.ColorDisabledTo);      Writeln(F, s);
    s := 'TabAppearance.ColorHot=' + ColorToString(TabAppearance.ColorHot);      Writeln(F, s);
    s := 'TabAppearance.ColorHotTo=' + ColorToString(TabAppearance.ColorHotTo);      Writeln(F, s);
    s := 'TabAppearance.ColorMirror=' + ColorToString(TabAppearance.ColorMirror);      Writeln(F, s);
    s := 'TabAppearance.ColorMirrorTo=' + ColorToString(TabAppearance.ColorMirrorTo);      Writeln(F, s);
    s := 'TabAppearance.ColorMirrorHot=' + ColorToString(TabAppearance.ColorMirrorHot);      Writeln(F, s);
    s := 'TabAppearance.ColorMirrorHotTo=' + ColorToString(TabAppearance.ColorMirrorHotTo);      Writeln(F, s);
    s := 'TabAppearance.ColorMirrorSelected=' + ColorToString(TabAppearance.ColorMirrorSelected);      Writeln(F, s);
    s := 'TabAppearance.ColorMirrorSelectedTo=' + ColorToString(TabAppearance.ColorMirrorSelectedTo);      Writeln(F, s);
    s := 'TabAppearance.ColorMirrorDisabled=' + ColorToString(TabAppearance.ColorMirrorDisabled);      Writeln(F, s);
    s := 'TabAppearance.ColorMirrorDisabledTo=' + ColorToString(TabAppearance.ColorMirrorDisabledTo);      Writeln(F, s);

    // TabAppearance.Font
    s := 'TabAppearance.Font.Color=' + ColorToString(TabAppearance.Font.Color);  Writeln(F, s);
    sl.Clear;
    if fsBold in TabAppearance.Font.Style then       sl.Add('fsBold');
    if fsItalic in TabAppearance.Font.Style then     sl.Add('fsItalic');
    if fsUnderline in TabAppearance.Font.Style then  sl.Add('fsUnderline');
    if fsStrikeOut in TabAppearance.Font.Style then  sl.Add('fsStrikeOut');
    s := 'TabAppearance.Font.Style=' + sl.CommaText;
    Writeln(F, s);
    s := 'TabAppearance.Font.Size=' + InttoStr(TabAppearance.Font.Size);    Writeln(F, s);

    sl.Clear;
    sl.Values['TabAppearance.Font.Name'] := TabAppearance.Font.Name;
    s := sl.CommaText;                  Writeln(F, s);

    case TabAppearance.Gradient of
      ggRadial:  s := 'TabAppearance.Gradient=ggRadial';
      ggVertical: s := 'TabAppearance.Gradient=ggVertical';
      ggDiagonalForward: s := 'TabAppearance.Gradient=ggDiagonalForward';
      ggDiagonalBackward: s := 'TabAppearance.Gradient=ggDiagonalBackward';
    end;
    Writeln(F, s);
    
    case TabAppearance.GradientMirror of
      ggRadial:  s := 'TabAppearance.GradientMirror=ggRadial';
      ggVertical: s := 'TabAppearance.GradientMirror=ggVertical';
      ggDiagonalForward: s := 'TabAppearance.GradientMirror=ggDiagonalForward';
      ggDiagonalBackward: s := 'TabAppearance.GradientMirror=ggDiagonalBackward';
    end;
    Writeln(F, s);
    
    case TabAppearance.GradientHot of
      ggRadial:  s := 'TabAppearance.GradientHot=ggRadial';
      ggVertical: s := 'TabAppearance.GradientHot=ggVertical';
      ggDiagonalForward: s := 'TabAppearance.GradientHot=ggDiagonalForward';
      ggDiagonalBackward: s := 'TabAppearance.GradientHot=ggDiagonalBackward';
    end;
    Writeln(F, s);

    case TabAppearance.GradientMirrorHot of
      ggRadial:  s := 'TabAppearance.GradientMirrorHot=ggRadial';
      ggVertical: s := 'TabAppearance.GradientMirrorHot=ggVertical';
      ggDiagonalForward: s := 'TabAppearance.GradientMirrorHot=ggDiagonalForward';
      ggDiagonalBackward: s := 'TabAppearance.GradientMirrorHot=ggDiagonalBackward';
    end;
    Writeln(F, s);
    
    case TabAppearance.GradientSelected of
      ggRadial:  s := 'TabAppearance.GradientSelected=ggRadial';
      ggVertical: s := 'TabAppearance.GradientSelected=ggVertical';
      ggDiagonalForward: s := 'TabAppearance.GradientSelected=ggDiagonalForward';
      ggDiagonalBackward: s := 'TabAppearance.GradientSelected=ggDiagonalBackward';
    end;
    Writeln(F, s);

    case TabAppearance.GradientMirrorSelected of
      ggRadial:  s := 'TabAppearance.GradientMirrorSelected=ggRadial';
      ggVertical: s := 'TabAppearance.GradientMirrorSelected=ggVertical';
      ggDiagonalForward: s := 'TabAppearance.GradientMirrorSelected=ggDiagonalForward';
      ggDiagonalBackward: s := 'TabAppearance.GradientMirrorSelected=ggDiagonalBackward';
    end;
    Writeln(F, s);

    case TabAppearance.GradientDisabled of
      ggRadial:  s := 'TabAppearance.GradientDisabled=ggRadial';
      ggVertical: s := 'TabAppearance.GradientDisabled=ggVertical';
      ggDiagonalForward: s := 'TabAppearance.GradientDisabled=ggDiagonalForward';
      ggDiagonalBackward: s := 'TabAppearance.GradientDisabled=ggDiagonalBackward';
    end;
    Writeln(F, s);
    
    case TabAppearance.GradientMirrorDisabled of
      ggRadial:  s := 'TabAppearance.GradientMirrorDisabled=ggRadial';
      ggVertical: s := 'TabAppearance.GradientMirrorDisabled=ggVertical';
      ggDiagonalForward: s := 'TabAppearance.GradientMirrorDisabled=ggDiagonalForward';
      ggDiagonalBackward: s := 'TabAppearance.GradientMirrorDisabled=ggDiagonalBackward';
    end;
    Writeln(F, s);

    s := 'TabAppearance.TextColor=' + ColorToString(TabAppearance.TextColor);      Writeln(F, s);
    s := 'TabAppearance.TextColorHot=' + ColorToString(TabAppearance.TextColorHot);      Writeln(F, s);
    s := 'TabAppearance.TextColorSelected=' + ColorToString(TabAppearance.TextColorSelected);      Writeln(F, s);
    s := 'TabAppearance.TextColorDisabled=' + ColorToString(TabAppearance.TextColorDisabled);      Writeln(F, s);
  end;

  with PageAppearance do {TVistaBackground}
  begin
    s := 'PageAppearance.BorderColor=' + ColorToString(PageAppearance.BorderColor);      Writeln(F, s);
    s := 'PageAppearance.Color=' + ColorToString(PageAppearance.Color);      Writeln(F, s);
    s := 'PageAppearance.ColorTo=' + ColorToString(PageAppearance.ColorTo);      Writeln(F, s);
    s := 'PageAppearance.ColorMirror=' + ColorToString(PageAppearance.ColorMirror);      Writeln(F, s);
    s := 'PageAppearance.ColorMirrorTo=' + ColorToString(PageAppearance.ColorMirrorTo);      Writeln(F, s);

    case PageAppearance.Gradient of
      ggRadial:  s := 'PageAppearance.Gradient=ggRadial';
      ggVertical: s := 'PageAppearance.Gradient=ggVertical';
      ggDiagonalForward: s := 'PageAppearance.Gradient=ggDiagonalForward';
      ggDiagonalBackward: s := 'PageAppearance.Gradient=ggDiagonalBackward';
    end;
    Writeln(F, s);
    
    case PageAppearance.GradientMirror of
      ggRadial:  s := 'PageAppearance.GradientMirror=ggRadial';
      ggVertical: s := 'PageAppearance.GradientMirror=ggVertical';
      ggDiagonalForward: s := 'PageAppearance.GradientMirror=ggDiagonalForward';
      ggDiagonalBackward: s := 'PageAppearance.GradientMirror=ggDiagonalBackward';
    end;
    Writeln(F, s);

    s := 'PageAppearance.Steps=' + InttoStr(PageAppearance.Steps);       Writeln(F, s);
  end;

  with GroupAppearance do {TGroupAppearance}
  begin
    s := 'GroupAppearance.BorderColor=' + ColorToString(GroupAppearance.BorderColor);      Writeln(F, s);
    s := 'GroupAppearance.Color=' + ColorToString(GroupAppearance.Color);      Writeln(F, s);
    s := 'GroupAppearance.ColorTo=' + ColorToString(GroupAppearance.ColorTo);      Writeln(F, s);
    s := 'GroupAppearance.ColorMirror=' + ColorToString(GroupAppearance.ColorMirror);      Writeln(F, s);
    s := 'GroupAppearance.ColorMirrorTo=' + ColorToString(GroupAppearance.ColorMirrorTo);      Writeln(F, s);

    // GroupAppearance.Font
    s := 'GroupAppearance.Font.Color=' + ColorToString(GroupAppearance.Font.Color);  Writeln(F, s);
    sl.Clear;
    if fsBold in GroupAppearance.Font.Style then       sl.Add('fsBold');
    if fsItalic in GroupAppearance.Font.Style then     sl.Add('fsItalic');
    if fsUnderline in GroupAppearance.Font.Style then  sl.Add('fsUnderline');
    if fsStrikeOut in GroupAppearance.Font.Style then  sl.Add('fsStrikeOut');
    s := 'GroupAppearance.Font.Style=' + sl.CommaText;
    Writeln(F, s);
    s := 'GroupAppearance.Font.Size=' + InttoStr(GroupAppearance.Font.Size);    Writeln(F, s);

    sl.Clear;
    sl.Values['GroupAppearance.Font.Name'] := GroupAppearance.Font.Name;
    s := sl.CommaText;                  Writeln(F, s);

    case GroupAppearance.Gradient of
      ggRadial:  s := 'GroupAppearance.Gradient=ggRadial';
      ggVertical: s := 'GroupAppearance.Gradient=ggVertical';
      ggDiagonalForward: s := 'GroupAppearance.Gradient=ggDiagonalForward';
      ggDiagonalBackward: s := 'GroupAppearance.Gradient=ggDiagonalBackward';
    end;
    Writeln(F, s);

    case GroupAppearance.GradientMirror of
      ggRadial:  s := 'GroupAppearance.GradientMirror=ggRadial';
      ggVertical: s := 'GroupAppearance.GradientMirror=ggVertical';
      ggDiagonalForward: s := 'GroupAppearance.GradientMirror=ggDiagonalForward';
      ggDiagonalBackward: s := 'GroupAppearance.GradientMirror=ggDiagonalBackward';
    end;
    Writeln(F, s);

    s := 'GroupAppearance.TextColor=' + ColorToString(GroupAppearance.TextColor);      Writeln(F, s);

    with GroupAppearance.CaptionAppearance do {TCaptionAppearance}
    begin
      s := 'GroupAppearance.CaptionAppearance.CaptionColor=' + ColorToString(GroupAppearance.CaptionAppearance.CaptionColor);      Writeln(F, s);
      s := 'GroupAppearance.CaptionAppearance.CaptionColorTo=' + ColorToString(GroupAppearance.CaptionAppearance.CaptionColorTo);      Writeln(F, s);
      s := 'GroupAppearance.CaptionAppearance.CaptionTextColor=' + ColorToString(GroupAppearance.CaptionAppearance.CaptionTextColor);      Writeln(F, s);
      s := 'GroupAppearance.CaptionAppearance.CaptionBorderColor=' + ColorToString(GroupAppearance.CaptionAppearance.CaptionBorderColor);      Writeln(F, s);
      s := 'GroupAppearance.CaptionAppearance.CaptionColorHot=' + ColorToString(GroupAppearance.CaptionAppearance.CaptionColorHot);      Writeln(F, s);
      s := 'GroupAppearance.CaptionAppearance.CaptionColorHotTo=' + ColorToString(GroupAppearance.CaptionAppearance.CaptionColorHotTo);      Writeln(F, s);
      s := 'GroupAppearance.CaptionAppearance.CaptionTextColorHot=' + ColorToString(GroupAppearance.CaptionAppearance.CaptionTextColorHot);      Writeln(F, s);
      s := 'GroupAppearance.CaptionAppearance.CaptionBorderColorHot=' + ColorToString(GroupAppearance.CaptionAppearance.CaptionBorderColorHot);      Writeln(F, s);
    end;

    with GroupAppearance.PageAppearance do {TVistaBackground}
    begin
      s := 'GroupAppearance.PageAppearance.BorderColor=' + ColorToString(GroupAppearance.PageAppearance.BorderColor);      Writeln(F, s);
      s := 'GroupAppearance.PageAppearance.Color=' + ColorToString(GroupAppearance.PageAppearance.Color);      Writeln(F, s);
      s := 'GroupAppearance.PageAppearance.ColorTo=' + ColorToString(GroupAppearance.PageAppearance.ColorTo);      Writeln(F, s);
      s := 'GroupAppearance.PageAppearance.ColorMirror=' + ColorToString(GroupAppearance.PageAppearance.ColorMirror);      Writeln(F, s);
      s := 'GroupAppearance.PageAppearance.ColorMirrorTo=' + ColorToString(GroupAppearance.PageAppearance.ColorMirrorTo);      Writeln(F, s);

      case GroupAppearance.PageAppearance.Gradient of
        ggRadial:  s := 'GroupAppearance.PageAppearance.Gradient=ggRadial';
        ggVertical: s := 'GroupAppearance.PageAppearance.Gradient=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.PageAppearance.Gradient=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.PageAppearance.Gradient=ggDiagonalBackward';
      end;
      Writeln(F, s);

      case GroupAppearance.PageAppearance.GradientMirror of
        ggRadial:  s := 'GroupAppearance.PageAppearance.GradientMirror=ggRadial';
        ggVertical: s := 'GroupAppearance.PageAppearance.GradientMirror=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.PageAppearance.GradientMirror=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.PageAppearance.GradientMirror=ggDiagonalBackward';
      end;
      Writeln(F, s);

      s := 'GroupAppearance.PageAppearance.Steps=' + InttoStr(GroupAppearance.PageAppearance.Steps);       Writeln(F, s);
    end;

    with GroupAppearance.TabAppearance do {TCustomTabAppearance}
    begin
      s := 'GroupAppearance.TabAppearance.BorderColor=' + ColorToString(GroupAppearance.TabAppearance.BorderColor);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.BorderColorHot=' + ColorToString(GroupAppearance.TabAppearance.BorderColorHot);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.BorderColorSelected=' + ColorToString(GroupAppearance.TabAppearance.BorderColorSelected);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.BorderColorSelectedHot=' + ColorToString(GroupAppearance.TabAppearance.BorderColorSelectedHot);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.BorderColorDown=' + ColorToString(GroupAppearance.TabAppearance.BorderColorDown);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.BorderColorDisabled=' + ColorToString(GroupAppearance.TabAppearance.BorderColorDisabled);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.Color=' + ColorToString(GroupAppearance.TabAppearance.Color);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorTo=' + ColorToString(GroupAppearance.TabAppearance.ColorTo);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorSelected=' + ColorToString(GroupAppearance.TabAppearance.ColorSelected);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorSelectedTo=' + ColorToString(GroupAppearance.TabAppearance.ColorSelectedTo);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorDisabled=' + ColorToString(GroupAppearance.TabAppearance.ColorDisabled);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorDisabledTo=' + ColorToString(GroupAppearance.TabAppearance.ColorDisabledTo);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorHot=' + ColorToString(GroupAppearance.TabAppearance.ColorHot);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorHotTo=' + ColorToString(GroupAppearance.TabAppearance.ColorHotTo);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorMirror=' + ColorToString(GroupAppearance.TabAppearance.ColorMirror);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorMirrorTo=' + ColorToString(GroupAppearance.TabAppearance.ColorMirrorTo);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorMirrorHot=' + ColorToString(GroupAppearance.TabAppearance.ColorMirrorHot);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorMirrorHotTo=' + ColorToString(GroupAppearance.TabAppearance.ColorMirrorHotTo);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorMirrorSelected=' + ColorToString(GroupAppearance.TabAppearance.ColorMirrorSelected);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorMirrorSelectedTo=' + ColorToString(GroupAppearance.TabAppearance.ColorMirrorSelectedTo);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorMirrorDisabled=' + ColorToString(GroupAppearance.TabAppearance.ColorMirrorDisabled);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.ColorMirrorDisabledTo=' + ColorToString(GroupAppearance.TabAppearance.ColorMirrorDisabledTo);      Writeln(F, s);

      // GroupAppearance.TabAppearance.Font
      s := 'GroupAppearance.TabAppearance.Font.Color=' + ColorToString(GroupAppearance.TabAppearance.Font.Color);  Writeln(F, s);
      sl.Clear;
      if fsBold in GroupAppearance.TabAppearance.Font.Style then       sl.Add('fsBold');
      if fsItalic in GroupAppearance.TabAppearance.Font.Style then     sl.Add('fsItalic');
      if fsUnderline in GroupAppearance.TabAppearance.Font.Style then  sl.Add('fsUnderline');
      if fsStrikeOut in GroupAppearance.TabAppearance.Font.Style then  sl.Add('fsStrikeOut');
      s := 'GroupAppearance.TabAppearance.Font.Style=' + sl.CommaText;
      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.Font.Size=' + InttoStr(GroupAppearance.TabAppearance.Font.Size);    Writeln(F, s);

      sl.Clear;
      sl.Values['GroupAppearance.TabAppearance.Font.Name'] := GroupAppearance.TabAppearance.Font.Name;
      s := sl.CommaText;                  Writeln(F, s);

      case GroupAppearance.TabAppearance.Gradient of
        ggRadial:  s := 'GroupAppearance.TabAppearance.Gradient=ggRadial';
        ggVertical: s := 'GroupAppearance.TabAppearance.Gradient=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.TabAppearance.Gradient=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.TabAppearance.Gradient=ggDiagonalBackward';
      end;
      Writeln(F, s);

      case GroupAppearance.TabAppearance.GradientMirror of
        ggRadial:  s := 'GroupAppearance.TabAppearance.GradientMirror=ggRadial';
        ggVertical: s := 'GroupAppearance.TabAppearance.GradientMirror=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.TabAppearance.GradientMirror=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.TabAppearance.GradientMirror=ggDiagonalBackward';
      end;
      Writeln(F, s);

      case GroupAppearance.TabAppearance.GradientHot of
        ggRadial:  s := 'GroupAppearance.TabAppearance.GradientHot=ggRadial';
        ggVertical: s := 'GroupAppearance.TabAppearance.GradientHot=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.TabAppearance.GradientHot=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.TabAppearance.GradientHot=ggDiagonalBackward';
      end;
      Writeln(F, s);

      case GroupAppearance.TabAppearance.GradientMirrorHot of
        ggRadial:  s := 'GroupAppearance.TabAppearance.GradientMirrorHot=ggRadial';
        ggVertical: s := 'GroupAppearance.TabAppearance.GradientMirrorHot=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.TabAppearance.GradientMirrorHot=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.TabAppearance.GradientMirrorHot=ggDiagonalBackward';
      end;
      Writeln(F, s);

      case GroupAppearance.TabAppearance.GradientSelected of
        ggRadial:  s := 'GroupAppearance.TabAppearance.GradientSelected=ggRadial';
        ggVertical: s := 'GroupAppearance.TabAppearance.GradientSelected=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.TabAppearance.GradientSelected=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.TabAppearance.GradientSelected=ggDiagonalBackward';
      end;
      Writeln(F, s);

      case GroupAppearance.TabAppearance.GradientMirrorSelected of
        ggRadial:  s := 'GroupAppearance.TabAppearance.GradientMirrorSelected=ggRadial';
        ggVertical: s := 'GroupAppearance.TabAppearance.GradientMirrorSelected=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.TabAppearance.GradientMirrorSelected=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.TabAppearance.GradientMirrorSelected=ggDiagonalBackward';
      end;
      Writeln(F, s);

      case GroupAppearance.TabAppearance.GradientDisabled of
        ggRadial:  s := 'GroupAppearance.TabAppearance.GradientDisabled=ggRadial';
        ggVertical: s := 'GroupAppearance.TabAppearance.GradientDisabled=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.TabAppearance.GradientDisabled=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.TabAppearance.GradientDisabled=ggDiagonalBackward';
      end;
      Writeln(F, s);

      case GroupAppearance.TabAppearance.GradientMirrorDisabled of
        ggRadial:  s := 'GroupAppearance.TabAppearance.GradientMirrorDisabled=ggRadial';
        ggVertical: s := 'GroupAppearance.TabAppearance.GradientMirrorDisabled=ggVertical';
        ggDiagonalForward: s := 'GroupAppearance.TabAppearance.GradientMirrorDisabled=ggDiagonalForward';
        ggDiagonalBackward: s := 'GroupAppearance.TabAppearance.GradientMirrorDisabled=ggDiagonalBackward';
      end;
      Writeln(F, s);

      s := 'GroupAppearance.TabAppearance.TextColor=' + ColorToString(GroupAppearance.TabAppearance.TextColor);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.TextColorHot=' + ColorToString(GroupAppearance.TabAppearance.TextColorHot);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.TextColorSelected=' + ColorToString(GroupAppearance.TabAppearance.TextColorSelected);      Writeln(F, s);
      s := 'GroupAppearance.TabAppearance.TextColorDisabled=' + ColorToString(GroupAppearance.TabAppearance.TextColorDisabled);      Writeln(F, s);
    end;

    with GroupAppearance.ToolBarAppearance do {TToolBarAppearance}
    begin
      s := 'GroupAppearance.ToolBarAppearance.BorderColor=' + ColorToString(GroupAppearance.ToolBarAppearance.BorderColor);      Writeln(F, s);
      s := 'GroupAppearance.ToolBarAppearance.BorderColorHot=' + ColorToString(GroupAppearance.ToolBarAppearance.BorderColorHot);      Writeln(F, s);
        {TGradientBackground}
      s := 'GroupAppearance.ToolBarAppearance.Color.Color=' + ColorToString(GroupAppearance.ToolBarAppearance.Color.Color);      Writeln(F, s);
      s := 'GroupAppearance.ToolBarAppearance.Color.ColorTo=' + ColorToString(GroupAppearance.ToolBarAppearance.Color.ColorTo);    Writeln(F, s);
      if GroupAppearance.ToolBarAppearance.Color.Direction = gdHorizontal then
        s := 'GroupAppearance.ToolBarAppearance.Color.Direction=gdHorizontal'
      else
        s := 'GroupAppearance.ToolBarAppearance.Color.Direction=gdVertical';
      Writeln(F, s);
      s := 'GroupAppearance.ToolBarAppearance.Color.Steps=' + InttoStr(GroupAppearance.ToolBarAppearance.Color.Steps);       Writeln(F, s);
        {TGradientBackground}
      s := 'GroupAppearance.ToolBarAppearance.ColorHot.Color=' + ColorToString(GroupAppearance.ToolBarAppearance.ColorHot.Color);        Writeln(F, s);
      s := 'GroupAppearance.ToolBarAppearance.ColorHot.ColorTo=' + ColorToString(GroupAppearance.ToolBarAppearance.ColorHot.ColorTo);    Writeln(F, s);
      if GroupAppearance.ToolBarAppearance.ColorHot.Direction = gdHorizontal then
        s := 'GroupAppearance.ToolBarAppearance.ColorHot.Direction=gdHorizontal'
      else
        s := 'GroupAppearance.ToolBarAppearance.ColorHot.Direction=gdVertical';
      Writeln(F, s);
      s := 'GroupAppearance.ToolBarAppearance.ColorHot.Steps=' + InttoStr(GroupAppearance.ToolBarAppearance.ColorHot.Steps);             Writeln(F, s);
    end;
  end;

  {========== CompactGlowButtonAppearance ===========}
  s := 'CompactGlowButtonAppearance.BorderColor=' + ColorToString(CompactGlowButtonAppearance.BorderColor);   Writeln(F, s);
  s := 'CompactGlowButtonAppearance.BorderColorHot=' + ColorToString(CompactGlowButtonAppearance.BorderColorHot);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.BorderColorDown=' + ColorToString(CompactGlowButtonAppearance.BorderColorDown);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.BorderColorChecked=' + ColorToString(CompactGlowButtonAppearance.BorderColorChecked);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.BorderColorDisabled=' + ColorToString(CompactGlowButtonAppearance.BorderColorDisabled);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.Color=' + ColorToString(CompactGlowButtonAppearance.Color);              Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorTo=' + ColorToString(CompactGlowButtonAppearance.ColorTo);          Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorChecked=' + ColorToString(CompactGlowButtonAppearance.ColorChecked);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorCheckedTo=' + ColorToString(CompactGlowButtonAppearance.ColorCheckedTo);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorDisabled=' + ColorToString(CompactGlowButtonAppearance.ColorDisabled);    Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorDisabledTo=' + ColorToString(CompactGlowButtonAppearance.ColorDisabledTo); Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorDown=' + ColorToString(CompactGlowButtonAppearance.ColorDown);      Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorDownTo=' + ColorToString(CompactGlowButtonAppearance.ColorDownTo);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorHot=' + ColorToString(CompactGlowButtonAppearance.ColorHot);        Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorHotTo=' + ColorToString(CompactGlowButtonAppearance.ColorHotTo);    Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirror=' + ColorToString(CompactGlowButtonAppearance.ColorMirror);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorTo=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorTo);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorHot=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorHot);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorHotTo=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorHotTo);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorDown=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorDown);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorDownTo=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorDownTo);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorChecked=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorChecked);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorCheckedTo=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorCheckedTo);    Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorDisabled=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorDisabled);  Writeln(F, s);
  s := 'CompactGlowButtonAppearance.ColorMirrorDisabledTo=' + ColorToString(CompactGlowButtonAppearance.ColorMirrorDisabledTo);    Writeln(F, s);

  case CompactGlowButtonAppearance.Gradient of
    ggRadial:  s := 'CompactGlowButtonAppearance.Gradient=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.Gradient=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.Gradient=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.Gradient=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientMirror of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientMirror=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientMirror=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientMirror=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientMirror=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientHot of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientHot=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientHot=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientHot=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientHot=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientMirrorHot of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientMirrorHot=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientMirrorHot=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientMirrorHot=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientMirrorHot=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientDown of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientDown=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientDown=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientDown=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientDown=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientMirrorDown of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientMirrorDown=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientMirrorDown=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientMirrorDown=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientMirrorDown=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientChecked of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientChecked=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientChecked=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientChecked=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientChecked=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientMirrorChecked of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientMirrorChecked=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientMirrorChecked=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientMirrorChecked=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientMirrorChecked=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientDisabled of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientDisabled=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientDisabled=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientDisabled=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientDisabled=ggDiagonalBackward';
  end;
  Writeln(F, s);

  case CompactGlowButtonAppearance.GradientMirrorDisabled of
    ggRadial:  s := 'CompactGlowButtonAppearance.GradientMirrorDisabled=ggRadial';
    ggVertical: s := 'CompactGlowButtonAppearance.GradientMirrorDisabled=ggVertical';
    ggDiagonalForward: s := 'CompactGlowButtonAppearance.GradientMirrorDisabled=ggDiagonalForward';
    ggDiagonalBackward: s := 'CompactGlowButtonAppearance.GradientMirrorDisabled=ggDiagonalBackward';
  end;
  Writeln(F, s);

  

  sl.free;
  {
  case Bevel of
    bvNone:     s := 'bvNone';
    bvLowered:  s := 'bvLowered';
    bvRaised:   s := 'bvRaised';
    bvSpace:    s := 'bvSpace';
  end;
  Writeln(F, s);

  if RoundEdges then
    s := 'True'
  else
  Transparent: Boolean
  UseBevel: Boolean
  }
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.LoadPropFromFile(var F: TextFile);
var
  s: String;
  sl: TStringList;

  function GetValue(Name: String): String;
  var
    P: Integer;
  begin
    Result := '';
    P := Pos('=', Name);
    if P > 0 then
      Result := Copy(Name, P+1, Length(Name) - P);
  end;

begin
  sl:= TStringList.Create;

  try
    Readln(F, s);
    Sl.CommaText := s;
    if UpperCase(sl.Values['AutoThemeAdapt']) = 'TRUE' then
      AutoThemeAdapt := True
    else
      AutoThemeAdapt := False;

    //AdvMenuStyler: TCustomAdvMenuStyler read FAdvMenuStyler write SetAdvMenuStyler; // PropID: 0
    //---- ButtonAppearance
    sl.Clear;
    with ButtonAppearance do
    begin
      Readln(F, s);    Sl.CommaText := s;
      ButtonAppearance.Color := StringToColor(sl.Values['ButtonAppearance.Color']);

      Readln(F, s);    Sl.CommaText := s;
      ButtonAppearance.ColorTo := StringToColor(sl.Values['ButtonAppearance.ColorTo']);

      Readln(F, s);    Sl.CommaText := s;
      ButtonAppearance.ColorChecked := StringToColor(sl.Values['ButtonAppearance.ColorChecked']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.ColorCheckedTo := StringToColor(sl.Values['ButtonAppearance.ColorCheckedTo']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.ColorDown := StringToColor(sl.Values['ButtonAppearance.ColorDown']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.ColorDownTo := StringToColor(sl.Values['ButtonAppearance.ColorDownTo']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.ColorHot := StringToColor(sl.Values['ButtonAppearance.ColorHot']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.ColorHotTo := StringToColor(sl.Values['ButtonAppearance.ColorHotTo']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.CaptionTextColor := StringToColor(sl.Values['ButtonAppearance.CaptionTextColor']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.CaptionTextColorHot := StringToColor(sl.Values['ButtonAppearance.CaptionTextColorHot']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.CaptionTextColorDown := StringToColor(sl.Values['ButtonAppearance.CaptionTextColorDown']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.CaptionTextColorChecked := StringToColor(sl.Values['ButtonAppearance.CaptionTextColorChecked']);

      Readln(F, s);  Sl.CommaText := s;
      if UpperCase(sl.Values['ButtonAppearance.GradientDirection']) = UpperCase('gdHorizontal') then
        ButtonAppearance.GradientDirection := gdHorizontal
      else
        ButtonAppearance.GradientDirection := gdVertical;

      Readln(F, s);  Sl.CommaText := s;
      if UpperCase(sl.Values['ButtonAppearance.GradientDirectionHot']) = UpperCase('gdHorizontal') then
        ButtonAppearance.GradientDirectionHot := gdHorizontal
      else
        ButtonAppearance.GradientDirectionHot := gdVertical;

      Readln(F, s);  Sl.CommaText := s;
      if UpperCase(sl.Values['ButtonAppearance.GradientDirectionDown']) = UpperCase('gdHorizontal') then
        ButtonAppearance.GradientDirectionDown := gdHorizontal
      else
        ButtonAppearance.GradientDirectionDown := gdVertical;

      Readln(F, s);  Sl.CommaText := s;
      if UpperCase(sl.Values['ButtonAppearance.GradientDirectionChecked']) = UpperCase('gdHorizontal') then
        ButtonAppearance.GradientDirectionChecked := gdHorizontal
      else
        ButtonAppearance.GradientDirectionChecked := gdVertical;

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.BorderColor := StringToColor(sl.Values['ButtonAppearance.BorderColor']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.BorderDownColor := StringToColor(sl.Values['ButtonAppearance.BorderDownColor']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.BorderHotColor := StringToColor(sl.Values['ButtonAppearance.BorderHotColor']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.BorderCheckedColor := StringToColor(sl.Values['ButtonAppearance.BorderCheckedColor']);

      //--- Caption Font
      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.CaptionFont.Color := StringToColor(sl.Values['ButtonAppearance.CaptionFont.Color']);

      sl.Clear;
      Readln(F, s);   Sl.CommaText := s;
      sl.CommaText := GetValue(s); // sl.Values['ButtonAppearance.CaptionFont.Style'];

      ButtonAppearance.CaptionFont.Style := [];
      if (sl.IndexOf('fsBold') >= 0) then ButtonAppearance.CaptionFont.Style := ButtonAppearance.CaptionFont.Style + [fsBold];
      if (sl.IndexOf('fsItalic') >= 0) then ButtonAppearance.CaptionFont.Style := ButtonAppearance.CaptionFont.Style + [fsItalic];
      if (sl.IndexOf('fsUnderline') >= 0) then ButtonAppearance.CaptionFont.Style := ButtonAppearance.CaptionFont.Style + [fsUnderline];
      if (sl.IndexOf('fsStrikeOut') >= 0) then ButtonAppearance.CaptionFont.Style := ButtonAppearance.CaptionFont.Style + [fsStrikeOut];

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.CaptionFont.Size := StrToInt(sl.Values['ButtonAppearance.CaptionFont.Size']);

      Readln(F, s);   Sl.CommaText := s;
      ButtonAppearance.CaptionFont.Name := sl.Values['ButtonAppearance.CaptionFont.Name'];
    end;

    //--- Color
    Readln(F, s);   Sl.CommaText := s;
    Color.Color := StringToColor(sl.Values['Color.Color']);

    Readln(F, s);   Sl.CommaText := s;
    Color.ColorTo := StringToColor(sl.Values['Color.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['Color.Direction']) = UpperCase('gdHorizontal') then
      Color.Direction := gdHorizontal
    else
      Color.Direction := gdVertical;

    Readln(F, s);   Sl.CommaText := s;
    Color.Steps := StrToInt(sl.Values['Color.Steps']);

    Readln(F, s);   Sl.CommaText := s;
    DockColor.Color := StringToColor(sl.Values['DockColor.Color']);

    Readln(F, s);   Sl.CommaText := s;
    DockColor.ColorTo := StringToColor(sl.Values['DockColor.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['DockColor.Direction']) = UpperCase('gdHorizontal') then
      DockColor.Direction := gdHorizontal
    else
      DockColor.Direction := gdVertical;

    Readln(F, s);   Sl.CommaText := s;
    DockColor.Steps := StrToInt(sl.Values['DockColor.Steps']);

    {property BackGround: TBitMap read FBackGround write SetBackGround;
    property BackGroundTransparent: Boolean read FBackGroundTransparent write SetBackGroundTransparent default true;
    property BackGroundDisplay: TBackGroundDisplay read FBackGroundDisplay write SetBackGroundDisplay default bdTile;
    }

    Readln(F, s);   Sl.CommaText := s;
    Font.Color := StringToColor(sl.Values['Font.Color']);

    sl.Clear;
    Readln(F, s);   Sl.CommaText := s;
    sl.CommaText := GetValue(s);  //sl.Values['Font.Style'];
    Font.Style := [];
    if (sl.IndexOf('fsBold') >= 0) then Font.Style := Font.Style + [fsBold];
    if (sl.IndexOf('fsItalic') >= 0) then Font.Style := Font.Style + [fsItalic];
    if (sl.IndexOf('fsUnderline') >= 0) then Font.Style := Font.Style + [fsUnderline];
    if (sl.IndexOf('fsStrikeOut') >= 0) then Font.Style := Font.Style + [fsStrikeOut];


    Readln(F, s);   Sl.CommaText := s;
    Font.Size := StrToInt(sl.Values['Font.Size']);

    Readln(F, s);   Sl.CommaText := s;
    Font.Name := sl.Values['Font.Name'];

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['DragGripStyle']) = UpperCase('dsDots') then
      DragGripStyle := dsDots
    else if UpperCase(sl.Values['DragGripStyle']) = UpperCase('dsSingleLine') then
      DragGripStyle := dsSingleLine
    else if UpperCase(sl.Values['DragGripStyle']) = UpperCase('dsDoubleLine') then
      DragGripStyle := dsDoubleLine
    else if UpperCase(sl.Values['DragGripStyle']) = UpperCase('dsFlatDots') then
      DragGripStyle := dsFlatDots
    else if UpperCase(sl.Values['DragGripStyle']) = UpperCase('dsNone') then
      DragGripStyle := dsNone;

    //property DragGripImage: TBitMap read FDragGripImage write SetDragGripImage;

    //property RightHandleImage: TBitmap read FRightHandleImage write SetRightHandleImage;
    Readln(F, s);   Sl.CommaText := s;
    RightHandleColor := StringToColor(sl.Values['RightHandleColor']);

    Readln(F, s);   Sl.CommaText := s;
    RightHandleColorHot := StringToColor(sl.Values['RightHandleColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    RightHandleColorTo := StringToColor(sl.Values['RightHandleColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    RightHandleColorHotTo := StringToColor(sl.Values['RightHandleColorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    RightHandleColorDown := StringToColor(sl.Values['RightHandleColorDown']);

    Readln(F, s);   Sl.CommaText := s;
    RightHandleColorDownTo := StringToColor(sl.Values['RightHandleColorDownTo']);

    Readln(F, s);   Sl.CommaText := s;
    FloatingWindowBorderColor := StringToColor(sl.Values['FloatingWindowBorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    FloatingWindowBorderWidth := StrToInt(sl.Values['FloatingWindowBorderWidth']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionAppearance.CaptionColor := StringToColor(sl.Values['CaptionAppearance.CaptionColor']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionAppearance.CaptionColorTo := StringToColor(sl.Values['CaptionAppearance.CaptionColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionAppearance.CaptionTextColor := StringToColor(sl.Values['CaptionAppearance.CaptionTextColor']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionAppearance.CaptionBorderColor := StringToColor(sl.Values['CaptionAppearance.CaptionBorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionAppearance.CaptionColorHot := StringToColor(sl.Values['CaptionAppearance.CaptionColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionAppearance.CaptionColorHotTo := StringToColor(sl.Values['CaptionAppearance.CaptionColorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionAppearance.CaptionTextColorHot := StringToColor(sl.Values['CaptionAppearance.CaptionTextColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionAppearance.CaptionBorderColorHot := StringToColor(sl.Values['CaptionAppearance.CaptionBorderColorHot']);


    Readln(F, s);   Sl.CommaText := s;
    BorderColor := StringToColor(sl.Values['BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    BorderColorHot := StringToColor(sl.Values['BorderColorHot']);
    
    //--- ColorHot
    Readln(F, s);   Sl.CommaText := s;
    ColorHot.Color := StringToColor(sl.Values['ColorHot.Color']);

    Readln(F, s);   Sl.CommaText := s;
    ColorHot.ColorTo := StringToColor(sl.Values['ColorHot.ColorTo']);

    Readln(F, s);  Sl.CommaText := s;
    if UpperCase(sl.Values['ColorHot.Direction']) = UpperCase('gdHorizontal') then
      ColorHot.Direction := gdHorizontal
    else
      ColorHot.Direction := gdVertical;

    Readln(F, s);   Sl.CommaText := s;
    ColorHot.Steps := StrToInt(sl.Values['ColorHot.Steps']);

    Readln(F, s);   Sl.CommaText := s;
    CaptionFont.Color := StringToColor(sl.Values['CaptionFont.Color']);

    sl.Clear;
    Readln(F, s);   Sl.CommaText := s;
    sl.CommaText := GetValue(s); //sl.Values['CaptionFont.Style'];
    CaptionFont.Style := [];
    if (sl.IndexOf('fsBold') >= 0) then CaptionFont.Style := CaptionFont.Style + [fsBold];
    if (sl.IndexOf('fsItalic') >= 0) then CaptionFont.Style := CaptionFont.Style + [fsItalic];
    if (sl.IndexOf('fsUnderline') >= 0) then CaptionFont.Style := CaptionFont.Style + [fsUnderline];
    if (sl.IndexOf('fsStrikeOut') >= 0) then CaptionFont.Style := CaptionFont.Style + [fsStrikeOut];

    Readln(F, s);   Sl.CommaText := s;
    CaptionFont.Size := StrToInt(sl.Values['CaptionFont.Size']);

    {========== AdvContainer ==========}
    Readln(F, s);   Sl.CommaText := s;
    ContainerAppearance.LineColor := StringToColor(sl.Values['ContainerAppearance.LineColor']);

    Readln(F, s);    Sl.CommaText := s;
    if UpperCase(sl.Values['ContainerAppearance.Line3D']) = 'TRUE' then
      ContainerAppearance.Line3D := True
    else
      ContainerAppearance.Line3D := False;

    {========== AdvGlowButton ===========}
    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.BorderColor := StringToColor(sl.Values['GlowButtonAppearance.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.BorderColorHot := StringToColor(sl.Values['GlowButtonAppearance.BorderColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.BorderColorDown := StringToColor(sl.Values['GlowButtonAppearance.BorderColorDown']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.BorderColorChecked := StringToColor(sl.Values['GlowButtonAppearance.BorderColorChecked']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.BorderColorDisabled := StringToColor(sl.Values['GlowButtonAppearance.BorderColorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.Color := StringToColor(sl.Values['GlowButtonAppearance.Color']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorTo := StringToColor(sl.Values['GlowButtonAppearance.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorChecked := StringToColor(sl.Values['GlowButtonAppearance.ColorChecked']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorCheckedTo := StringToColor(sl.Values['GlowButtonAppearance.ColorCheckedTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorDisabled := StringToColor(sl.Values['GlowButtonAppearance.ColorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorDisabledTo := StringToColor(sl.Values['GlowButtonAppearance.ColorDisabledTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorDown := StringToColor(sl.Values['GlowButtonAppearance.ColorDown']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorDownTo := StringToColor(sl.Values['GlowButtonAppearance.ColorDownTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorHot := StringToColor(sl.Values['GlowButtonAppearance.ColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorHotTo := StringToColor(sl.Values['GlowButtonAppearance.ColorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirror := StringToColor(sl.Values['GlowButtonAppearance.ColorMirror']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorTo := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorHot := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorHotTo := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorDown := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorDown']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorDownTo := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorDownTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorChecked := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorChecked']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorCheckedTo := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorCheckedTo']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorDisabled := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    GlowButtonAppearance.ColorMirrorDisabledTo := StringToColor(sl.Values['GlowButtonAppearance.ColorMirrorDisabledTo']);

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.Gradient']) = UpperCase('ggRadial') then
      GlowButtonAppearance.Gradient := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.Gradient']) = UpperCase('ggVertical') then
      GlowButtonAppearance.Gradient := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.Gradient']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.Gradient := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.Gradient']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.Gradient := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientMirror']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientMirror := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirror']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientMirror := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirror']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientMirror := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirror']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientMirror := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientHot']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientHot := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientHot']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientHot := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientHot']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientHot := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientHot']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientHot := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorHot']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientMirrorHot := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorHot']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientMirrorHot := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorHot']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientMirrorHot := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorHot']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientMirrorHot := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientDown']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientDown := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientDown']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientDown := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientDown']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientDown := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientDown']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientDown := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorDown']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientMirrorDown := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorDown']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientMirrorDown := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorDown']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientMirrorDown := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorDown']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientMirrorDown := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientChecked']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientChecked := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientChecked']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientChecked := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientChecked']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientChecked := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientChecked']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientChecked := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorChecked']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientMirrorChecked := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorChecked']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientMirrorChecked := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorChecked']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientMirrorChecked := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorChecked']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientMirrorChecked := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientDisabled']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientDisabled := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientDisabled']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientDisabled := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientDisabled']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientDisabled := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientDisabled']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientDisabled := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorDisabled']) = UpperCase('ggRadial') then
      GlowButtonAppearance.GradientMirrorDisabled := ggRadial
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorDisabled']) = UpperCase('ggVertical') then
      GlowButtonAppearance.GradientMirrorDisabled := ggVertical
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorDisabled']) = UpperCase('ggDiagonalForward') then
      GlowButtonAppearance.GradientMirrorDisabled := ggDiagonalForward
    else if UpperCase(sl.Values['GlowButtonAppearance.GradientMirrorDisabled']) = UpperCase('ggDiagonalBackward') then
      GlowButtonAppearance.GradientMirrorDisabled := ggDiagonalBackward;


  {========== AdvToolBarPager ===========}
    {PagerCaption: TVistaTextBackground}
    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.BorderColor := StringToColor(sl.Values['PagerCaption.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.Color := StringToColor(sl.Values['PagerCaption.Color']);

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.ColorTo := StringToColor(sl.Values['PagerCaption.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.ColorMirror := StringToColor(sl.Values['PagerCaption.ColorMirror']);

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.ColorMirrorTo := StringToColor(sl.Values['PagerCaption.ColorMirrorTo']);

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['PagerCaption.Gradient']) = UpperCase('ggRadial') then
      PagerCaption.Gradient := ggRadial
    else if UpperCase(sl.Values['PagerCaption.Gradient']) = UpperCase('ggVertical') then
      PagerCaption.Gradient := ggVertical
    else if UpperCase(sl.Values['PagerCaption.Gradient']) = UpperCase('ggDiagonalForward') then
      PagerCaption.Gradient := ggDiagonalForward
    else if UpperCase(sl.Values['PagerCaption.Gradient']) = UpperCase('ggDiagonalBackward') then
      PagerCaption.Gradient := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['PagerCaption.GradientMirror']) = UpperCase('ggRadial') then
      PagerCaption.GradientMirror := ggRadial
    else if UpperCase(sl.Values['PagerCaption.GradientMirror']) = UpperCase('ggVertical') then
      PagerCaption.GradientMirror := ggVertical
    else if UpperCase(sl.Values['PagerCaption.GradientMirror']) = UpperCase('ggDiagonalForward') then
      PagerCaption.GradientMirror := ggDiagonalForward
    else if UpperCase(sl.Values['PagerCaption.GradientMirror']) = UpperCase('ggDiagonalBackward') then
      PagerCaption.GradientMirror := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.Steps := StrToInt(sl.Values['PagerCaption.Steps']);

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.TextColor := StringToColor(sl.Values['PagerCaption.TextColor']);

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.Font.Color := StringToColor(sl.Values['PagerCaption.Font.Color']);

    sl.Clear;
    Readln(F, s);   Sl.CommaText := s;
    sl.CommaText := GetValue(s);
    PagerCaption.Font.Style := [];
    if (sl.IndexOf('fsBold') >= 0) then PagerCaption.Font.Style := PagerCaption.Font.Style + [fsBold];
    if (sl.IndexOf('fsItalic') >= 0) then PagerCaption.Font.Style := PagerCaption.Font.Style + [fsItalic];
    if (sl.IndexOf('fsUnderline') >= 0) then PagerCaption.Font.Style := PagerCaption.Font.Style + [fsUnderline];
    if (sl.IndexOf('fsStrikeOut') >= 0) then PagerCaption.Font.Style := PagerCaption.Font.Style + [fsStrikeOut];

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.Font.Size := StrToInt(sl.Values['PagerCaption.Font.Size']);

    Readln(F, s);   Sl.CommaText := s;
    PagerCaption.Font.Name := sl.Values['PagerCaption.Font.Name'];

      {TabAppearance: TTabAppearance}
         {TGradientBackground}
    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BackGround.Color := StringToColor(sl.Values['TabAppearance.BackGround.Color']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BackGround.ColorTo := StringToColor(sl.Values['TabAppearance.BackGround.ColorTo']);

    Readln(F, s);  Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.BackGround.Direction']) = UpperCase('gdHorizontal') then
      TabAppearance.BackGround.Direction := gdHorizontal
    else
      TabAppearance.BackGround.Direction := gdVertical;

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BackGround.Steps := StrToInt(sl.Values['TabAppearance.BackGround.Steps']);


    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BorderColor := StringToColor(sl.Values['TabAppearance.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BorderColorHot := StringToColor(sl.Values['TabAppearance.BorderColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BorderColorSelected := StringToColor(sl.Values['TabAppearance.BorderColorSelected']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BorderColorSelectedHot := StringToColor(sl.Values['TabAppearance.BorderColorSelectedHot']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BorderColorDown := StringToColor(sl.Values['TabAppearance.BorderColorDown']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.BorderColorDisabled := StringToColor(sl.Values['TabAppearance.BorderColorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.Color := StringToColor(sl.Values['TabAppearance.Color']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorTo := StringToColor(sl.Values['TabAppearance.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorSelected := StringToColor(sl.Values['TabAppearance.ColorSelected']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorSelectedTo := StringToColor(sl.Values['TabAppearance.ColorSelectedTo']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorDisabled := StringToColor(sl.Values['TabAppearance.ColorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorDisabledTo := StringToColor(sl.Values['TabAppearance.ColorDisabledTo']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorHot := StringToColor(sl.Values['TabAppearance.ColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorHotTo := StringToColor(sl.Values['TabAppearance.ColorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorMirror := StringToColor(sl.Values['TabAppearance.ColorMirror']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorMirrorTo := StringToColor(sl.Values['TabAppearance.ColorMirrorTo']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorMirrorHot := StringToColor(sl.Values['TabAppearance.ColorMirrorHot']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorMirrorHotTo := StringToColor(sl.Values['TabAppearance.ColorMirrorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorMirrorSelected := StringToColor(sl.Values['TabAppearance.ColorMirrorSelected']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorMirrorSelectedTo := StringToColor(sl.Values['TabAppearance.ColorMirrorSelectedTo']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorMirrorDisabled := StringToColor(sl.Values['TabAppearance.ColorMirrorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.ColorMirrorDisabledTo := StringToColor(sl.Values['TabAppearance.ColorMirrorDisabledTo']);

    //-- Font
    Readln(F, s);   Sl.CommaText := s;
    tabAppearance.Font.Color := StringToColor(sl.Values['tabAppearance.Font.Color']);
    sl.Clear;
    Readln(F, s);   Sl.CommaText := s;
    sl.CommaText := GetValue(s);
    tabAppearance.Font.Style := [];
    if (sl.IndexOf('fsBold') >= 0) then tabAppearance.Font.Style := tabAppearance.Font.Style + [fsBold];
    if (sl.IndexOf('fsItalic') >= 0) then tabAppearance.Font.Style := tabAppearance.Font.Style + [fsItalic];
    if (sl.IndexOf('fsUnderline') >= 0) then tabAppearance.Font.Style := tabAppearance.Font.Style + [fsUnderline];
    if (sl.IndexOf('fsStrikeOut') >= 0) then tabAppearance.Font.Style := tabAppearance.Font.Style + [fsStrikeOut];

    Readln(F, s);   Sl.CommaText := s;
    tabAppearance.Font.Size := StrToInt(sl.Values['tabAppearance.Font.Size']);

    Readln(F, s);   Sl.CommaText := s;
    tabAppearance.Font.Name := sl.Values['tabAppearance.Font.Name'];
    // end Font
    
    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.Gradient']) = UpperCase('ggRadial') then
      TabAppearance.Gradient := ggRadial
    else if UpperCase(sl.Values['TabAppearance.Gradient']) = UpperCase('ggVertical') then
      TabAppearance.Gradient := ggVertical
    else if UpperCase(sl.Values['TabAppearance.Gradient']) = UpperCase('ggDiagonalForward') then
      TabAppearance.Gradient := ggDiagonalForward
    else if UpperCase(sl.Values['TabAppearance.Gradient']) = UpperCase('ggDiagonalBackward') then
      TabAppearance.Gradient := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.GradientMirror']) = UpperCase('ggRadial') then
      TabAppearance.GradientMirror := ggRadial
    else if UpperCase(sl.Values['TabAppearance.GradientMirror']) = UpperCase('ggVertical') then
      TabAppearance.GradientMirror := ggVertical
    else if UpperCase(sl.Values['TabAppearance.GradientMirror']) = UpperCase('ggDiagonalForward') then
      TabAppearance.GradientMirror := ggDiagonalForward
    else if UpperCase(sl.Values['TabAppearance.GradientMirror']) = UpperCase('ggDiagonalBackward') then
      TabAppearance.GradientMirror := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.GradientHot']) = UpperCase('ggRadial') then
      TabAppearance.GradientHot := ggRadial
    else if UpperCase(sl.Values['TabAppearance.GradientHot']) = UpperCase('ggVertical') then
      TabAppearance.GradientHot := ggVertical
    else if UpperCase(sl.Values['TabAppearance.GradientHot']) = UpperCase('ggDiagonalForward') then
      TabAppearance.GradientHot := ggDiagonalForward
    else if UpperCase(sl.Values['TabAppearance.GradientHot']) = UpperCase('ggDiagonalBackward') then
      TabAppearance.GradientHot := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.GradientMirrorHot']) = UpperCase('ggRadial') then
      TabAppearance.GradientMirrorHot := ggRadial
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorHot']) = UpperCase('ggVertical') then
      TabAppearance.GradientMirrorHot := ggVertical
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorHot']) = UpperCase('ggDiagonalForward') then
      TabAppearance.GradientMirrorHot := ggDiagonalForward
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorHot']) = UpperCase('ggDiagonalBackward') then
      TabAppearance.GradientMirrorHot := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.GradientSelected']) = UpperCase('ggRadial') then
      TabAppearance.GradientSelected := ggRadial
    else if UpperCase(sl.Values['TabAppearance.GradientSelected']) = UpperCase('ggVertical') then
      TabAppearance.GradientSelected := ggVertical
    else if UpperCase(sl.Values['TabAppearance.GradientSelected']) = UpperCase('ggDiagonalForward') then
      TabAppearance.GradientSelected := ggDiagonalForward
    else if UpperCase(sl.Values['TabAppearance.GradientSelected']) = UpperCase('ggDiagonalBackward') then
      TabAppearance.GradientSelected := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.GradientMirrorSelected']) = UpperCase('ggRadial') then
      TabAppearance.GradientMirrorSelected := ggRadial
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorSelected']) = UpperCase('ggVertical') then
      TabAppearance.GradientMirrorSelected := ggVertical
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorSelected']) = UpperCase('ggDiagonalForward') then
      TabAppearance.GradientMirrorSelected := ggDiagonalForward
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorSelected']) = UpperCase('ggDiagonalBackward') then
      TabAppearance.GradientMirrorSelected := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.GradientDisabled']) = UpperCase('ggRadial') then
      TabAppearance.GradientDisabled := ggRadial
    else if UpperCase(sl.Values['TabAppearance.GradientDisabled']) = UpperCase('ggVertical') then
      TabAppearance.GradientDisabled := ggVertical
    else if UpperCase(sl.Values['TabAppearance.GradientDisabled']) = UpperCase('ggDiagonalForward') then
      TabAppearance.GradientDisabled := ggDiagonalForward
    else if UpperCase(sl.Values['TabAppearance.GradientDisabled']) = UpperCase('ggDiagonalBackward') then
      TabAppearance.GradientDisabled := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['TabAppearance.GradientMirrorDisabled']) = UpperCase('ggRadial') then
      TabAppearance.GradientMirrorDisabled := ggRadial
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorDisabled']) = UpperCase('ggVertical') then
      TabAppearance.GradientMirrorDisabled := ggVertical
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorDisabled']) = UpperCase('ggDiagonalForward') then
      TabAppearance.GradientMirrorDisabled := ggDiagonalForward
    else if UpperCase(sl.Values['TabAppearance.GradientMirrorDisabled']) = UpperCase('ggDiagonalBackward') then
      TabAppearance.GradientMirrorDisabled := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.TextColor := StringToColor(sl.Values['TabAppearance.TextColor']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.TextColorHot := StringToColor(sl.Values['TabAppearance.TextColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.TextColorSelected := StringToColor(sl.Values['TabAppearance.TextColorSelected']);

    Readln(F, s);   Sl.CommaText := s;
    TabAppearance.TextColorDisabled := StringToColor(sl.Values['TabAppearance.TextColorDisabled']);


    {PageAppearance: TVistaBackground}
    Readln(F, s);   Sl.CommaText := s;
    PageAppearance.BorderColor := StringToColor(sl.Values['PageAppearance.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    PageAppearance.Color := StringToColor(sl.Values['PageAppearance.Color']);

    Readln(F, s);   Sl.CommaText := s;
    PageAppearance.ColorTo := StringToColor(sl.Values['PageAppearance.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    PageAppearance.ColorMirror := StringToColor(sl.Values['PageAppearance.ColorMirror']);

    Readln(F, s);   Sl.CommaText := s;
    PageAppearance.ColorMirrorTo := StringToColor(sl.Values['PageAppearance.ColorMirrorTo']);

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['PageAppearance.Gradient']) = UpperCase('ggRadial') then
      PageAppearance.Gradient := ggRadial
    else if UpperCase(sl.Values['PageAppearance.Gradient']) = UpperCase('ggVertical') then
      PageAppearance.Gradient := ggVertical
    else if UpperCase(sl.Values['PageAppearance.Gradient']) = UpperCase('ggDiagonalForward') then
      PageAppearance.Gradient := ggDiagonalForward
    else if UpperCase(sl.Values['PageAppearance.Gradient']) = UpperCase('ggDiagonalBackward') then
      PageAppearance.Gradient := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['PageAppearance.GradientMirror']) = UpperCase('ggRadial') then
      PageAppearance.GradientMirror := ggRadial
    else if UpperCase(sl.Values['PageAppearance.GradientMirror']) = UpperCase('ggVertical') then
      PageAppearance.GradientMirror := ggVertical
    else if UpperCase(sl.Values['PageAppearance.GradientMirror']) = UpperCase('ggDiagonalForward') then
      PageAppearance.GradientMirror := ggDiagonalForward
    else if UpperCase(sl.Values['PageAppearance.GradientMirror']) = UpperCase('ggDiagonalBackward') then
      PageAppearance.GradientMirror := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    PageAppearance.Steps := StrToInt(sl.Values['PageAppearance.Steps']);


    {GroupAppearance: TGroupAppearance}
    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.BorderColor := StringToColor(sl.Values['GroupAppearance.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.Color := StringToColor(sl.Values['GroupAppearance.Color']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ColorTo := StringToColor(sl.Values['GroupAppearance.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ColorMirror := StringToColor(sl.Values['GroupAppearance.ColorMirror']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ColorMirrorTo := StringToColor(sl.Values['GroupAppearance.ColorMirrorTo']);

    //-- Font
    Readln(F, s);   Sl.CommaText := s;
    groupAppearance.Font.Color := StringToColor(sl.Values['groupAppearance.Font.Color']);
    sl.Clear;
    Readln(F, s);   Sl.CommaText := s;
    sl.CommaText := GetValue(s);
    groupAppearance.Font.Style := [];
    if (sl.IndexOf('fsBold') >= 0) then groupAppearance.Font.Style := groupAppearance.Font.Style + [fsBold];
    if (sl.IndexOf('fsItalic') >= 0) then groupAppearance.Font.Style := groupAppearance.Font.Style + [fsItalic];
    if (sl.IndexOf('fsUnderline') >= 0) then groupAppearance.Font.Style := groupAppearance.Font.Style + [fsUnderline];
    if (sl.IndexOf('fsStrikeOut') >= 0) then groupAppearance.Font.Style := groupAppearance.Font.Style + [fsStrikeOut];

    Readln(F, s);   Sl.CommaText := s;
    groupAppearance.Font.Size := StrToInt(sl.Values['groupAppearance.Font.Size']);

    Readln(F, s);   Sl.CommaText := s;
    groupAppearance.Font.Name := sl.Values['groupAppearance.Font.Name'];
    // end Font
    
    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.Gradient']) = UpperCase('ggRadial') then
      GroupAppearance.Gradient := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.Gradient']) = UpperCase('ggVertical') then
      GroupAppearance.Gradient := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.Gradient']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.Gradient := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.Gradient']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.Gradient := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.GradientMirror']) = UpperCase('ggRadial') then
      GroupAppearance.GradientMirror := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.GradientMirror']) = UpperCase('ggVertical') then
      GroupAppearance.GradientMirror := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.GradientMirror']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.GradientMirror := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.GradientMirror']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.GradientMirror := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TextColor := StringToColor(sl.Values['GroupAppearance.TextColor']);

      {GroupAppearance.CaptionAppearance: TCaptionAppearance}
    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.CaptionAppearance.CaptionColor := StringToColor(sl.Values['GroupAppearance.CaptionAppearance.CaptionColor']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.CaptionAppearance.CaptionColorTo := StringToColor(sl.Values['GroupAppearance.CaptionAppearance.CaptionColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.CaptionAppearance.CaptionTextColor := StringToColor(sl.Values['GroupAppearance.CaptionAppearance.CaptionTextColor']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.CaptionAppearance.CaptionBorderColor := StringToColor(sl.Values['GroupAppearance.CaptionAppearance.CaptionBorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.CaptionAppearance.CaptionColorHot := StringToColor(sl.Values['GroupAppearance.CaptionAppearance.CaptionColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.CaptionAppearance.CaptionColorHotTo := StringToColor(sl.Values['GroupAppearance.CaptionAppearance.CaptionColorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.CaptionAppearance.CaptionTextColorHot := StringToColor(sl.Values['GroupAppearance.CaptionAppearance.CaptionTextColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.CaptionAppearance.CaptionBorderColorHot := StringToColor(sl.Values['GroupAppearance.CaptionAppearance.CaptionBorderColorHot']);

      {GroupAppearance.PageAppearance: TVistaBackground}
    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.PageAppearance.BorderColor := StringToColor(sl.Values['GroupAppearance.PageAppearance.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.PageAppearance.Color := StringToColor(sl.Values['GroupAppearance.PageAppearance.Color']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.PageAppearance.ColorTo := StringToColor(sl.Values['GroupAppearance.PageAppearance.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.PageAppearance.ColorMirror := StringToColor(sl.Values['GroupAppearance.PageAppearance.ColorMirror']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.PageAppearance.ColorMirrorTo := StringToColor(sl.Values['GroupAppearance.PageAppearance.ColorMirrorTo']);

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.PageAppearance.Gradient']) = UpperCase('ggRadial') then
      GroupAppearance.PageAppearance.Gradient := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.PageAppearance.Gradient']) = UpperCase('ggVertical') then
      GroupAppearance.PageAppearance.Gradient := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.PageAppearance.Gradient']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.PageAppearance.Gradient := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.PageAppearance.Gradient']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.PageAppearance.Gradient := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.PageAppearance.GradientMirror']) = UpperCase('ggRadial') then
      GroupAppearance.PageAppearance.GradientMirror := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.PageAppearance.GradientMirror']) = UpperCase('ggVertical') then
      GroupAppearance.PageAppearance.GradientMirror := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.PageAppearance.GradientMirror']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.PageAppearance.GradientMirror := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.PageAppearance.GradientMirror']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.PageAppearance.GradientMirror := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.PageAppearance.Steps := StrToInt(sl.Values['GroupAppearance.PageAppearance.Steps']);

      {GroupAppearance.TabAppearance: TCustomTabAppearance}
    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.BorderColor := StringToColor(sl.Values['GroupAppearance.TabAppearance.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.BorderColorHot := StringToColor(sl.Values['GroupAppearance.TabAppearance.BorderColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.BorderColorSelected := StringToColor(sl.Values['GroupAppearance.TabAppearance.BorderColorSelected']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.BorderColorSelectedHot := StringToColor(sl.Values['GroupAppearance.TabAppearance.BorderColorSelectedHot']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.BorderColorDown := StringToColor(sl.Values['GroupAppearance.TabAppearance.BorderColorDown']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.BorderColorDisabled := StringToColor(sl.Values['GroupAppearance.TabAppearance.BorderColorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.Color := StringToColor(sl.Values['GroupAppearance.TabAppearance.Color']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorTo := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorSelected := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorSelected']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorSelectedTo := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorSelectedTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorDisabled := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorDisabledTo := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorDisabledTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorHot := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorHotTo := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorMirror := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorMirror']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorMirrorTo := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorMirrorTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorMirrorHot := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorMirrorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorMirrorHotTo := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorMirrorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorMirrorSelected := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorMirrorSelected']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorMirrorSelectedTo := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorMirrorSelectedTo']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorMirrorDisabled := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorMirrorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.ColorMirrorDisabledTo := StringToColor(sl.Values['GroupAppearance.TabAppearance.ColorMirrorDisabledTo']);

    //-- Font
    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.Font.Color := StringToColor(sl.Values['GroupAppearance.TabAppearance.Font.Color']);
    sl.Clear;
    Readln(F, s);   Sl.CommaText := s;
    sl.CommaText := GetValue(s);
    GroupAppearance.TabAppearance.Font.Style := [];
    if (sl.IndexOf('fsBold') >= 0) then GroupAppearance.TabAppearance.Font.Style := GroupAppearance.TabAppearance.Font.Style + [fsBold];
    if (sl.IndexOf('fsItalic') >= 0) then GroupAppearance.TabAppearance.Font.Style := GroupAppearance.TabAppearance.Font.Style + [fsItalic];
    if (sl.IndexOf('fsUnderline') >= 0) then GroupAppearance.TabAppearance.Font.Style := GroupAppearance.TabAppearance.Font.Style + [fsUnderline];
    if (sl.IndexOf('fsStrikeOut') >= 0) then GroupAppearance.TabAppearance.Font.Style := GroupAppearance.TabAppearance.Font.Style + [fsStrikeOut];

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.Font.Size := StrToInt(sl.Values['GroupAppearance.TabAppearance.Font.Size']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.Font.Name := sl.Values['GroupAppearance.TabAppearance.Font.Name'];
    // end font

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.TabAppearance.Gradient']) = UpperCase('ggRadial') then
      GroupAppearance.TabAppearance.Gradient := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.Gradient']) = UpperCase('ggVertical') then
      GroupAppearance.TabAppearance.Gradient := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.Gradient']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.TabAppearance.Gradient := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.Gradient']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.TabAppearance.Gradient := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirror']) = UpperCase('ggRadial') then
      GroupAppearance.TabAppearance.GradientMirror := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirror']) = UpperCase('ggVertical') then
      GroupAppearance.TabAppearance.GradientMirror := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirror']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.TabAppearance.GradientMirror := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirror']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.TabAppearance.GradientMirror := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientHot']) = UpperCase('ggRadial') then
      GroupAppearance.TabAppearance.GradientHot := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientHot']) = UpperCase('ggVertical') then
      GroupAppearance.TabAppearance.GradientHot := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientHot']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.TabAppearance.GradientHot := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientHot']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.TabAppearance.GradientHot := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorHot']) = UpperCase('ggRadial') then
      GroupAppearance.TabAppearance.GradientMirrorHot := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorHot']) = UpperCase('ggVertical') then
      GroupAppearance.TabAppearance.GradientMirrorHot := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorHot']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.TabAppearance.GradientMirrorHot := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorHot']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.TabAppearance.GradientMirrorHot := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientSelected']) = UpperCase('ggRadial') then
      GroupAppearance.TabAppearance.GradientSelected := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientSelected']) = UpperCase('ggVertical') then
      GroupAppearance.TabAppearance.GradientSelected := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientSelected']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.TabAppearance.GradientSelected := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientSelected']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.TabAppearance.GradientSelected := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorSelected']) = UpperCase('ggRadial') then
      GroupAppearance.TabAppearance.GradientMirrorSelected := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorSelected']) = UpperCase('ggVertical') then
      GroupAppearance.TabAppearance.GradientMirrorSelected := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorSelected']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.TabAppearance.GradientMirrorSelected := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorSelected']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.TabAppearance.GradientMirrorSelected := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientDisabled']) = UpperCase('ggRadial') then
      GroupAppearance.TabAppearance.GradientDisabled := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientDisabled']) = UpperCase('ggVertical') then
      GroupAppearance.TabAppearance.GradientDisabled := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientDisabled']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.TabAppearance.GradientDisabled := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientDisabled']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.TabAppearance.GradientDisabled := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorDisabled']) = UpperCase('ggRadial') then
      GroupAppearance.TabAppearance.GradientMirrorDisabled := ggRadial
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorDisabled']) = UpperCase('ggVertical') then
      GroupAppearance.TabAppearance.GradientMirrorDisabled := ggVertical
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorDisabled']) = UpperCase('ggDiagonalForward') then
      GroupAppearance.TabAppearance.GradientMirrorDisabled := ggDiagonalForward
    else if UpperCase(sl.Values['GroupAppearance.TabAppearance.GradientMirrorDisabled']) = UpperCase('ggDiagonalBackward') then
      GroupAppearance.TabAppearance.GradientMirrorDisabled := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.TextColor := StringToColor(sl.Values['GroupAppearance.TabAppearance.TextColor']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.TextColorHot := StringToColor(sl.Values['GroupAppearance.TabAppearance.TextColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.TextColorSelected := StringToColor(sl.Values['GroupAppearance.TabAppearance.TextColorSelected']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.TabAppearance.TextColorDisabled := StringToColor(sl.Values['GroupAppearance.TabAppearance.TextColorDisabled']);


      {GroupAppearance.ToolBarAppearance: TToolBarAppearance}
    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ToolBarAppearance.BorderColor := StringToColor(sl.Values['GroupAppearance.ToolBarAppearance.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ToolBarAppearance.BorderColorHot := StringToColor(sl.Values['GroupAppearance.ToolBarAppearance.BorderColorHot']);

        {TGradientBackground}
    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ToolBarAppearance.Color.Color := StringToColor(sl.Values['GroupAppearance.ToolBarAppearance.Color.Color']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ToolBarAppearance.Color.ColorTo := StringToColor(sl.Values['GroupAppearance.ToolBarAppearance.Color.ColorTo']);

    Readln(F, s);  Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.ToolBarAppearance.Color.Direction']) = UpperCase('gdHorizontal') then
      GroupAppearance.ToolBarAppearance.Color.Direction := gdHorizontal
    else
      GroupAppearance.ToolBarAppearance.Color.Direction := gdVertical;

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ToolBarAppearance.Color.Steps := StrToInt(sl.Values['GroupAppearance.ToolBarAppearance.Color.Steps']);

        {TGradientBackground}
    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ToolBarAppearance.ColorHot.Color := StringToColor(sl.Values['GroupAppearance.ToolBarAppearance.ColorHot.Color']);

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ToolBarAppearance.ColorHot.ColorTo := StringToColor(sl.Values['GroupAppearance.ToolBarAppearance.ColorHot.ColorTo']);

    Readln(F, s);  Sl.CommaText := s;
    if UpperCase(sl.Values['GroupAppearance.ToolBarAppearance.ColorHot.Direction']) = UpperCase('gdHorizontal') then
      GroupAppearance.ToolBarAppearance.ColorHot.Direction := gdHorizontal
    else
      GroupAppearance.ToolBarAppearance.ColorHot.Direction := gdVertical;

    Readln(F, s);   Sl.CommaText := s;
    GroupAppearance.ToolBarAppearance.ColorHot.Steps := StrToInt(sl.Values['GroupAppearance.ToolBarAppearance.ColorHot.Steps']);


    {========== CompactGlowButtonAppearance ===========}
    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.BorderColor := StringToColor(sl.Values['CompactGlowButtonAppearance.BorderColor']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.BorderColorHot := StringToColor(sl.Values['CompactGlowButtonAppearance.BorderColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.BorderColorDown := StringToColor(sl.Values['CompactGlowButtonAppearance.BorderColorDown']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.BorderColorChecked := StringToColor(sl.Values['CompactGlowButtonAppearance.BorderColorChecked']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.BorderColorDisabled := StringToColor(sl.Values['CompactGlowButtonAppearance.BorderColorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.Color := StringToColor(sl.Values['CompactGlowButtonAppearance.Color']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorChecked := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorChecked']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorCheckedTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorCheckedTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorDisabled := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorDisabledTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorDisabledTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorDown := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorDown']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorDownTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorDownTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorHot := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorHot']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorHotTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirror := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirror']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorHot := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorHot']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorHotTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorHotTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorDown := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorDown']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorDownTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorDownTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorChecked := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorChecked']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorCheckedTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorCheckedTo']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorDisabled := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorDisabled']);

    Readln(F, s);   Sl.CommaText := s;
    CompactGlowButtonAppearance.ColorMirrorDisabledTo := StringToColor(sl.Values['CompactGlowButtonAppearance.ColorMirrorDisabledTo']);

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.Gradient']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.Gradient := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.Gradient']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.Gradient := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.Gradient']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.Gradient := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.Gradient']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.Gradient := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirror']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientMirror := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirror']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientMirror := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirror']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientMirror := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirror']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientMirror := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientHot']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientHot := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientHot']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientHot := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientHot']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientHot := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientHot']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientHot := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorHot']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientMirrorHot := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorHot']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientMirrorHot := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorHot']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientMirrorHot := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorHot']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientMirrorHot := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientDown']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientDown := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientDown']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientDown := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientDown']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientDown := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientDown']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientDown := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorDown']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientMirrorDown := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorDown']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientMirrorDown := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorDown']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientMirrorDown := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorDown']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientMirrorDown := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientChecked']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientChecked := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientChecked']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientChecked := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientChecked']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientChecked := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientChecked']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientChecked := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorChecked']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientMirrorChecked := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorChecked']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientMirrorChecked := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorChecked']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientMirrorChecked := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorChecked']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientMirrorChecked := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientDisabled']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientDisabled := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientDisabled']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientDisabled := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientDisabled']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientDisabled := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientDisabled']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientDisabled := ggDiagonalBackward;

    Readln(F, s);   Sl.CommaText := s;
    if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorDisabled']) = UpperCase('ggRadial') then
      CompactGlowButtonAppearance.GradientMirrorDisabled := ggRadial
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorDisabled']) = UpperCase('ggVertical') then
      CompactGlowButtonAppearance.GradientMirrorDisabled := ggVertical
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorDisabled']) = UpperCase('ggDiagonalForward') then
      CompactGlowButtonAppearance.GradientMirrorDisabled := ggDiagonalForward
    else if UpperCase(sl.Values['CompactGlowButtonAppearance.GradientMirrorDisabled']) = UpperCase('ggDiagonalBackward') then
      CompactGlowButtonAppearance.GradientMirrorDisabled := ggDiagonalBackward;

  except
    raise Exception.Create('Corrupt file');
  end;
  sl.free;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetBorderColor(const Value: TColor);
begin
  if (FBorderColor <> Value) then
  begin
    FBorderColor := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetBorderColorHot(const Value: TColor);
begin
  if (FBorderColorHot <> Value) then
  begin
    FBorderColorHot := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetColorHot(
  const Value: TVistaGradientBackground);
begin
  FColorHot.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCaptionFont(const Value: TFont);
begin
  FCaptionFont.Assign(Value);
  Change(2);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetContainerAppearance(
  const Value: TContainerAppearance);
begin
  FContainerAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.OnContainerAppearanceChanged(
  Sender: TObject);
begin
  Change(4);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.OnGlowButtonAppearanceChanged(Sender: TObject);
begin
  Change(7);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.OnPagerCaptionChanged(Sender: TObject);
begin
  Change(11);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.OnTabAppearanceChanged(Sender: TObject);
begin
  Change(10);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.OnPageAppearanceChanged(Sender: TObject);
begin
  Change(10);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.OnGroupAppearanceChanged(Sender: TObject);
begin
  Change(10);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetGlowButtonAppearance(
  const Value: TGlowButtonAppearance);
begin
  FGlowButtonAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetPagerCaption(
  const Value: TVistaTextBackground);
begin
  FPagerCaption.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetTabAppearance(
  const Value: TTabAppearance);
begin
  FTabAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetPageAppearance(
  const Value: TVistaPageBackground);
begin
  FPageAppearance.assign(Value);
end;

//------------------------------------------------------------------------------
{
procedure TCustomAdvToolBarStyler.SetCaptionBorderColorHot(
  const Value: TColor);
begin
  if (FCaptionBorderColorHot <> Value) then
  begin
    FCaptionBorderColorHot := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCaptionColorHot(const Value: TColor);
begin
  if (FCaptionColorHot <> Value) then
  begin
    FCaptionColorHot := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCaptionColorHotTo(
  const Value: TColor);
begin
  if (FCaptionColorHotTo <> Value) then
  begin
    FCaptionColorHotTo := Value;
    Change(2);
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCaptionTextColorHot(
  const Value: TColor);
begin
  if (FCaptionTextColorHot <> Value) then
  begin
    FCaptionTextColorHot := Value;
    Change(2);
  end;
end;
}
//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetGroupAppearance(
  const Value: TGroupAppearance);
begin
  FGroupAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCaptionAppearance(
  const Value: TCaptionAppearance);
begin
  FCaptionAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.OnCaptionAppearanceChanged(
  Sender: TObject);
begin
  Change(2);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetCompactGlowButtonAppearance(
  const Value: TGlowButtonAppearance);
begin
  FCompactGlowButtonAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.SetQATAppearance(
  const Value: TQATAppearance);
begin
  FQATAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomAdvToolBarStyler.OnQATAppearanceChanged(Sender: TObject);
begin
  Change(12);
end;

//------------------------------------------------------------------------------

{ TAdvDockPanel }

constructor TAdvDockPanel.Create(AOwner: TComponent);
begin
  inherited; //This csMenuEvents causes Atl+Key stack overflow problem
  ControlStyle := ControlStyle + [csAcceptsControls {, csMenuEvents}] - [csClickEvents, csCaptureMouse, csOpaque];

  FMyImage := TBitMap.Create;

  inherited Align := alTop;
  FDockAlign := daTop;

  FInternalToolBarStyler := TCustomAdvToolBarStyler.Create(self);
  FInternalToolBarStyler.Name := 'InternalStyler';
//  FInternalToolBarStyler.Color := RGB(212, 208, 200);
//  FInternalToolBarStyler.ColorTo := RGB(245, 245, 244);
//  FInternalToolBarStyler.GradientDirection := gdHorizontal;
  FToolBarStyler := nil;
  FCurrentToolBarStyler := FInternalToolBarStyler;
  FCurrentToolBarStyler.AddControl(self);
  {$IFDEF DELPHI6_LVL}
  FInternalToolBarStyler.SetSubComponent(True);
  {$ENDIF}

  FRows := TRowCollection.Create(self);
  FOffSetX := 1;
  FOffSetY := 0;

  FToolBars := TDbgList.Create;
  FHiddenToolBars := TDbgList.Create;

  FMinimumSize := MINDOCKPANELHEIGHT;

  FPersistence:= TPersistence.Create(self);
  FPersistence.OnChange:= OnPersistenceChange;

  FUseRunTimeHeight := False;
  
  DoubleBuffered := true;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.CreateParams(var Params: TCreateParams);
begin
  inherited;
  //if not (csDesigning in ComponentState) then
    //Params.WindowClass.Style:= Params.WindowClass.Style and not (CS_HREDRAW or CS_VREDRAW);
end;

//------------------------------------------------------------------------------

destructor TAdvDockPanel.Destroy;
begin
  if FPersistence.Enabled and not (csDesigning in ComponentState) then
    SaveToolBarsPosition;

  {$IFDEF DELPHI2006_LVL}
  if Assigned(FToolBarStyler) and (FToolBarStyler <> FInternalToolBarStyler) then
  begin
    FToolBarStyler.RemoveControl(self);
    FToolBarStyler := nil;
  end;
  {$ENDIF}
  FInternalToolBarStyler.Free;
  FRows.Free;
  FToolBars.Free;
  FHiddenToolBars.Free;
  FMyImage.Free;
  FPersistence.Free;
  inherited;
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.AddToolBar(aAdvToolBar: TAdvCustomToolBar): integer;
var
  i: Integer;
begin
  if LockHeight and not (csDesigning in ComponentState) and (FPropertiesLoaded) then
  begin
    Result := -1;
    i := IsAllowedInAnyRow(aAdvToolBar);
    if (i >= 0) then
    begin
      aAdvToolBar.FCurrentDock := nil;
      aAdvToolBar.Position := self.Align;
      aAdvToolBar.FCurrentDock := self;

      FToolBars.Add(aAdvToolBar);
      Result := FRows.Items[i].AddToolBar(aAdvToolBar);

      aAdvToolBar.Persistence.Enabled := self.Persistence.Enabled;
      aAdvToolBar.Persistence.Key := self.Persistence.Key;
      aAdvToolBar.Persistence.Location := Self.Persistence.Location;
    end;
  end
  else
  begin
    aAdvToolBar.FCurrentDock := nil;
    aAdvToolBar.Position := self.Align;
    aAdvToolBar.FCurrentDock := self;

    FToolBars.Add(aAdvToolBar);

    if not (csLoading in ComponentState) then
    begin
      with FRows.Add do
      begin
        //aAdvToolBar.Row:= Index;
        Result := AddToolBar(aAdvToolBar);
      end;
    end
    else
      Result:= 0;

    aAdvToolBar.Persistence.Enabled := self.Persistence.Enabled;
    aAdvToolBar.Persistence.Key := self.Persistence.Key;
    aAdvToolBar.Persistence.Location := Self.Persistence.Location;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.AlignControls(AControl: TControl;
  var ARect: TRect);
begin
  inherited;
 { if AControl is TAdvCustomToolBar then
    if not TAdvCustomToolBar(AControl).AllowBoundChange then
      FRows[TAdvCustomToolBar(AControl).Row].ArrangeToolBars;  }
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.GetAlign: TDockAlign;
begin
  Result := FDockAlign;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.Loaded;
var
  i, j, L, T: integer;
  TempToolBarList: TDbgList;
  Added: Boolean;
begin
  inherited;

  TempToolBarList := TDbgList.Create;
  for i := 0 to FToolBars.Count-1 do
  begin
    Added := false;
    for j := 0 to TempToolBarList.Count-1 do
    begin
      if Align in [daTop, daBottom] then
      begin
        if TAdvCustomToolBar(TempToolBarList[j]).Top > TAdvCustomToolBar(FToolBars[i]).Top then
        begin
          TempToolBarList.Insert(j, FToolBars[i]);
          Added := True;
          Break;
        end
        else if TAdvCustomToolBar(TempToolBarList[j]).Top = TAdvCustomToolBar(FToolBars[i]).Top then
        begin
          if TAdvCustomToolBar(TempToolBarList[j]).Left > TAdvCustomToolBar(FToolBars[i]).Left then
          begin
            TempToolBarList.Insert(j, FToolBars[i]);
            Added := True;
            Break;
          end;
        end;
      end
      else  // Position in [daLeft, daBottom] then
      begin
        if TAdvCustomToolBar(TempToolBarList[j]).Left > TAdvCustomToolBar(FToolBars[i]).Left then
        begin
          TempToolBarList.Insert(j, FToolBars[i]);
          Added := True;
          Break;
        end
        else if TAdvCustomToolBar(TempToolBarList[j]).Left = TAdvCustomToolBar(FToolBars[i]).Left then
        begin
          if TAdvCustomToolBar(TempToolBarList[j]).Top > TAdvCustomToolBar(FToolBars[i]).Top then
          begin
            TempToolBarList.Insert(j, FToolBars[i]);
            Added := True;
            Break;
          end;
        end;
      end;
    end;
    if not Added then
      TempToolBarList.Add(FToolBars[i]);
  end;

  for j := 0 to TempToolBarList.Count-1 do
  begin
    L := TAdvCustomToolBar(TempToolBarList[j]).Left;
    T := TAdvCustomToolBar(TempToolBarList[j]).Top;
    with FRows.Add do
      AddToolBar(TAdvCustomToolBar(TempToolBarList[j]));

    TAdvCustomToolBar(TempToolBarList[j]).Left := L;
    TAdvCustomToolBar(TempToolBarList[j]).Top := T;
  end;
  TempToolBarList.Free;

  if FPersistence.Enabled and not (csDesigning in ComponentState) then
    LoadToolBarsPosition;
{  for i:=0 to FRows.Count-1 do
    FRows.Items[i].ArrangeToolBars;  }

  FPropertiesLoaded := True;  
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  inherited;
  // Check remove for ToolBar, Styler
  if not (csDestroying in ComponentState) and (Operation = opRemove) then
  begin
    if AComponent = ToolBarStyler then
      ToolBarStyler := nil
    else if AComponent is TAdvCustomToolBar then
    begin
      if (TAdvCustomToolBar(AComponent).Row >= 0) and (TAdvCustomToolBar(AComponent).Row < FRows.Count) then
        RemoveToolBar(TAdvCustomToolBar(AComponent));
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.Paint;
var
  R: TRect;
  c, ro: integer;
begin
  inherited;

  FMyImage.Width := Width;
  FMyImage.Height := Height;

  R := ClientRect;
  with FCurrentToolBarStyler, FMyImage.Canvas do
  begin
    if DockColor.ColorTo <> clNone then
      DrawGradient(FMyImage.Canvas, DockColor.Color, DockColor.ColorTo, DockColor.Steps, R, DockColor.Direction = gdHorizontal)
    else
    begin
      Pen.Color := DockColor.Color;
      Brush.Color := DockColor.Color;
      Rectangle(R);
    end;

    if not BackGround.Empty then
    begin
       // have to shift to on change event
       //set color
     { if BackGroundTransparent then
      begin
        BackGround.Transparent:= true;
        BackGround.TransparentMode:= tmAuto;
      end;  }
      case BackGroundDisplay of
        bdTile:
          begin
            c := 1;
            ro := 1;
            while ro < Height - 2 do
            begin
              while c < width - 2 do
              begin
                Draw(c, ro, BackGround);
                c := c + BackGround.Width;
              end;
              c := 1;
              ro := ro + BackGround.Height;
            end;
          end;
        bdCenter:
          begin
            Draw((Width - BackGround.Width) div 2, (Height - BackGround.Height) div 2, BackGround);
          end;
        bdStretch:
          begin
            StretchDraw(Rect(R.Left + 2, R.Top + 2, R.Right - 2, R.Bottom - 2), BackGround);
          end;
      end;
    end;
  end;

  Canvas.Draw(0, 0, FMyImage);
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.RemoveToolBar(aAdvToolBar: TAdvCustomToolBar);
var
  i: integer;
begin
  if not (csLoading in ComponentState) then
    if FRows.Count > aAdvToolBar.Row then
      FRows.Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);

  i := FToolBars.IndexOf(aAdvToolBar);
  if i >= 0 then
    FToolBars.Delete(i);

  i := FHiddenToolBars.IndexOf(aAdvToolBar);
  if i >= 0 then
    FHiddenToolBars.Delete(i);
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetAlign(const Value: TDockAlign);
var
  i: integer;
begin
  if Value <> FDockAlign then
  begin
    FDockAlign := Value;
    case FDockAlign of
      daLeft: inherited Align := alLeft;
      daTop: inherited Align := alTop;
      daRight: inherited Align := alRight;
      daBottom: inherited Align := alBottom;
    end;

    for i := 0 to FToolBars.Count - 1 do
      TAdvCustomToolBar(FToolBars[i]).Position := FDockAlign;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetParent(AParent: TWinControl);
begin
  if (AParent is TAdvDockPanel) or (AParent is TAdvCustomToolBar) then
    raise Exception.Create('Invalid Parent');

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetToolBarStyler(const Value: TCustomAdvToolBarStyler);
var
  i: integer;
begin
  if (FToolBarStyler <> Value) or (Value = nil) then
  begin
    if Assigned(FToolBarStyler) and (FToolBarStyler <> FInternalToolBarStyler) then
      FToolBarStyler.RemoveControl(self);

    FToolBarStyler := Value;

    if FToolBarStyler = nil then
    begin
      //FToolBarStyler := FInternalToolBarStyler
      FCurrentToolBarStyler := FInternalToolBarStyler;
    end
    else
    begin
      FCurrentToolBarStyler := FToolBarStyler;
      FToolBarStyler.AddControl(self);
    end;

    if not (csDestroying in ComponentState) and not (csLoading in ComponentState) then
    begin
      for i := 0 to FToolBars.Count - 1 do
        TAdvCustomToolBar(FToolBars[i]).ParentStyler := TAdvCustomToolBar(FToolBars[i]).ParentStyler;
    end;

    PopupMenu := PopupMenu;   // Refresh Styler
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.UpdateMe(PropID: integer);
begin
  Color := FCurrentToolBarStyler.DockColor.Color;
  case PropID of
    6: PopupMenu := PopupMenu;
  end;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

function TAdvDockPanel.GetAdvToolBarCount: integer;
begin
  Result := FToolBars.Count;
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.GetAdvToolBars(index: integer): TAdvCustomToolBar;
begin
  Result := TAdvCustomToolBar(FToolBars[index]);
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.GetRowCount: integer;
begin
  Result := FRows.Count;
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.GetMyImage: TBitMap;
begin
  Result := FMyImage;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetToolBarBounds(aAdvToolBar: TAdvCustomToolBar;
  var ALeft, ATop, AWidth, AHeight: Integer);
begin                                  // FF: Btn.showCaption when not visible
  if (csLoading in ComponentState) or (not aAdvToolBar.Visible) then
    exit;

  if Align in [daTop, daBottom] then
  begin
    FRows.SetToolBarTopAndHeight(aAdvToolBar, ATop, AHeight);
    FRows.Items[aAdvToolBar.Row].SetToolBarLeftAndWidth(aAdvToolBar, ALeft, AWidth);
  end
  else // if Position in [daLeft, daRight] then
  begin
    FRows.SetToolBarLeftAndWidth(aAdvToolBar, ALeft, AWidth);
    FRows.Items[aAdvToolBar.Row].SetToolBarTopAndHeight(aAdvToolBar, ATop, AHeight);
    //OutputDebugString(pchar(aAdvToolBar.Name+' T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' H:'+inttostr(aAdvToolBar.Height)+' W:'+inttostr(aAdvToolBar.Width)));
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.UpdateToolBarVisibility(
  aAdvToolBar: TAdvCustomToolBar);
var
  I: Integer;
begin
  if aAdvToolBar.Visible then
  begin
    I := FHiddenToolBars.IndexOf(aAdvToolBar);
    if I >= 0 then
      FHiddenToolBars.Delete(i);
  end
  else
  begin
    I := FHiddenToolBars.IndexOf(aAdvToolBar);
    if I < 0 then
      FHiddenToolBars.Add(aAdvToolBar);
  end;
  FRows.UpdateToolBarVisibility(aAdvToolBar);
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetToolBarFullSize(aAdvToolBar: TAdvCustomToolBar);
begin
  FRows.SetToolBarFullSize(aAdvToolBar);
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.WMSize(var Message: TWMSize);
begin
  FRows.SetRowsPosition;
end;

//------------------------------------------------------------------------------

{ AdvToolbar menu support }

var
  ToolMenuHook: HHOOK;
  InitDone: Boolean = False;
  MenuToolBar , MenuToolBar2: TAdvCustomToolBar;
  MenuButtonIndex: Integer;
  LastMenuItem: TMenuItem;
  LastMousePos: TPoint;
  StillModal: Boolean;

function ToolMenuGetMsgHook(Code: Integer; WParam: Longint; var Msg: TMsg): Longint; stdcall;
const
  RightArrowKey: array[Boolean] of Word = (VK_LEFT, VK_RIGHT);
  LeftArrowKey: array[Boolean] of Word = (VK_RIGHT, VK_LEFT);
var
  P: TPoint;
  Target: TControl;
  Item: Integer;
  FindKind: TFindItemKind;
  ParentMenu: TMenu;
  MouseTarget: Boolean;

  function FindButton(Forward: Boolean): TAdvCustomToolBarButton;
  var
    ToolBar: TAdvCustomToolBar;
    I, J, Count: Integer;
  begin
    ToolBar := MenuToolBar;
    if ToolBar <> nil then
    begin
      J := MenuButtonIndex;
      I := J;
      Count := ToolBar.FATBControls.Count; // .ControlCount;
      if Forward then
        repeat
          if I = Count - 1 then
            I := 0
          else
            Inc(I);
          if TControl(ToolBar.FATBControls[I]) is TAdvCustomToolBarButton then
          begin
            Result := TAdvCustomToolBarButton(TControl(ToolBar.FATBControls[I]) {ToolBar.Controls[I]});
            if Result.Visible and Result.Enabled {and Result.Grouped} then Exit;
          end;
        until I = J
      else
        repeat
          if I = 0 then
            I := Count - 1
          else
            Dec(I);
          if TControl(ToolBar.FATBControls[I]) is TAdvCustomToolBarButton then
          begin
            Result := TAdvCustomToolBarButton(TControl(ToolBar.FATBControls[I]) {ToolBar.Controls[I]});
            if Result.Visible and Result.Enabled {and Result.Grouped} then Exit;
          end;
        until I = J;
    end;
    Result := nil;
  end;

begin
  MouseTarget := false;
  if LastMenuItem <> nil then
  begin
    ParentMenu := LastMenuItem.GetParentMenu;
    if ParentMenu <> nil then
    begin
      if ParentMenu.IsRightToLeft then
        if Msg.WParam = VK_LEFT then
          Msg.WParam := VK_RIGHT
        else if Msg.WParam = VK_RIGHT then
          Msg.WParam := VK_LEFT;
    end;
  end;
  Result := CallNextHookEx(ToolMenuHook, Code, WParam, Longint(@Msg));
  if Result <> 0 then Exit;
  if (Code = MSGF_MENU) then
  begin
    Target := nil;
    if not InitDone then
    begin
      InitDone := True;
      PostMessage(Msg.Hwnd, WM_KEYDOWN, VK_DOWN, 0);
    end;
    case Msg.Message of
      WM_MENUSELECT:
        begin
          if (HiWord(Msg.WParam) = $FFFF) and (Msg.LParam = 0) then
          begin
            if not StillModal then
              MenuToolBar.CancelMenu;
            Exit;
          end
          else
            StillModal := False;
          FindKind := fkCommand;
          if HiWord(Msg.WParam) and MF_POPUP <> 0 then FindKind := fkHandle;
          if FindKind = fkHandle then
            Item := GetSubMenu(Msg.LParam, LoWord(Msg.WParam))
          else
            Item := LoWord(Msg.WParam);
          LastMenuItem := MenuToolBar.FTempMenu.FindItem(Item, FindKind);
        end;
      WM_SYSKEYDOWN:
        if Msg.WParam = VK_MENU then
        begin
          MenuToolBar.CancelMenu;
          Exit;
        end;
      WM_KEYDOWN:
        if Msg.WParam = VK_RETURN then
          MenuToolBar.FMenuResult := True
        else if Msg.WParam = VK_ESCAPE then
          StillModal := True
        else if LastMenuItem <> nil then
        begin
          if (Msg.WParam = VK_RIGHT) and (LastMenuItem.Count = 0) then
            Target := FindButton(True)
          else if (Msg.WParam = VK_LEFT) and (LastMenuItem.GetParentComponent is TPopupMenu) then
            Target := FindButton(False)
          else
            Target := nil;
          if Target <> nil then
          begin
            P := Target.ClientToScreen(Point(0, 0));
            MouseTarget := false;
          end;
        end;
      WM_MOUSEMOVE:
        begin
          P := Msg.pt;
          if (P.X <> LastMousePos.X) or (P.Y <> LastMousePos.Y) then
          begin
            Target := FindDragTarget(P, False);
            LastMousePos := P;
            MouseTarget := true;
          end;
        end;
    end;
    if (Target <> nil) and (Target is TAdvCustomToolBarButton) and (TAdvCustomToolBarButton(Target).IsMenuButton) then
    begin
      with TAdvCustomToolBarButton(Target) do
        if (Index <> MenuButtonIndex) {and Grouped} and (Parent <> nil) and
          Parent.HandleAllocated then
        begin
          StillModal := True;
          MenuToolBar.FCaptureChangeCancels := False;
          MenuToolBar.ClickButton(TAdvCustomToolBarButton(Target), MouseTarget);
          //MenuToolBar.ClickButton(TAdvCustomToolBarButton(Target));
        end;
    end;
  end;
end;

procedure InitToolMenuHooks;
begin
  StillModal := False;
  GetCursorPos(LastMousePos);
  if ToolMenuHook = 0 then
    ToolMenuHook := SetWindowsHookEx(WH_MSGFILTER, @ToolMenuGetMsgHook, 0,
      GetCurrentThreadID);
end;

procedure ReleaseToolMenuHooks;
begin
  if ToolMenuHook <> 0 then
    UnhookWindowsHookEx(ToolMenuHook);
  ToolMenuHook := 0;
  LastMenuItem := nil;
  MenuToolBar := nil;
  MenuButtonIndex := -1;
  InitDone := False;
end;

//----------------------------------------------

var
  ToolMenuKeyHook: HHOOK;

procedure ReleaseToolMenuKeyHooks; forward;

function ToolMenuKeyMsgHook(Code: Integer; WParam: Longint; var Msg: TMsg): Longint; stdcall;
begin
  if (Code = HC_ACTION) then
  begin
    if Msg.Message = CM_DEACTIVATE then
      MenuToolBar2.CancelMenu
    else if Msg.message = WM_COMMAND then
      ReleaseToolMenuKeyHooks
    else if (ToolMenuHook = 0) and ((Msg.Message = WM_CHAR) or
      (Msg.Message = WM_KEYDOWN) or (Msg.Message = WM_KEYUP) or
      (Msg.Message = WM_SYSKEYDOWN) or (Msg.Message = WM_SYSKEYUP)) then
      Msg.hwnd := MenuToolBar2.Handle;
  end;
  Result := CallNextHookEx(ToolMenuKeyHook, Code, WParam, Longint(@Msg))
end;

procedure InitToolMenuKeyHooks;
begin
  if ToolMenuKeyHook = 0 then
    ToolMenuKeyHook := SetWindowsHookEx(WH_GETMESSAGE, @ToolMenuKeyMsgHook, 0,
      GetCurrentThreadID);
end;

procedure ReleaseToolMenuKeyHooks;
begin
  if ToolMenuKeyHook <> 0 then UnhookWindowsHookEx(ToolMenuKeyHook);
  ToolMenuKeyHook := 0;
  MenuToolBar2 := nil;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetPersistence(const Value: TPersistence);
begin
  FPersistence.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.LoadToolBarsPosition;
var
  i, j, ATBCount, RC, R, L, T, W, H, SV: integer;
  AToolBar: TAdvCustomToolBar;
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
  N: String;
  OldV: Boolean;
  TempToolBarList: TStringList;
  TempATBList: TDbgList;
  DockList: TDbgList;
  TempList: TDbgList;

  function GetToolBarByName(aName: String): TAdvCustomToolBar;
  var
    i: integer;
  begin
    Result:= nil;
    i:= TempToolBarList.IndexOf(N);
    if i >= 0 then
    begin
      Result:= TAdvCustomToolBar(TempToolBarList.Objects[i]);
      TempToolBarList.Delete(i);
    end;
  end;

 { function GetToolBarByName(aName: String): TAdvCustomToolBar;
  var
    r, i: integer;
  begin
    Result:= nil;
    for r:=0 to FRows.Count-1 do
      for i:= 0 to FRows.Items[r].ToolBarList.Count-1 do
        if UpperCase(aName) = UpperCase(TAdvCustomToolBar(FRows.Items[r].ToolBarList[i]).Name) then
        begin
          Result:= TAdvCustomToolBar(FRows.Items[r].ToolBarList[i]);
          Break;
        end;
  end;
  }

  function GetParentForm: TCustomForm;
  var
    ParentCtrl: TWinControl;
  begin
    Result := nil;
    ParentCtrl := self.Parent;
    while Assigned(ParentCtrl) do
    begin
      if ParentCtrl is TCustomForm then
      begin
        Result := TCustomForm(ParentCtrl);
        break;
      end;
      ParentCtrl := ParentCtrl.Parent;
    end;
  end;

  procedure BuildDockPanelList;
    procedure SearchChildForDockPanel(ParentCtrl: TWinControl);
    var
      i: integer;
    begin
      if (ParentCtrl = nil) or (ContainsControl(ParentCtrl)) {or (not ParentCtrl.Showing)} then
        exit;

      if not (ParentCtrl is TAdvDockPanel) and (ParentCtrl is TWinControl) then
      begin
        for i := 0 to ParentCtrl.ControlCount - 1 do
        begin
          if (ParentCtrl.Controls[i] is TWinControl) then
            SearchChildForDockPanel(TWinControl(ParentCtrl.Controls[i]));
        end;
      end;

      if (ParentCtrl is TAdvDockPanel) then
      begin
        if (DockList.IndexOf(ParentCtrl) < 0) then
          DockList.Add(ParentCtrl);
      end;
    end;

  begin
    SearchChildForDockPanel(GetParentForm);
  end;

  function SearchToolBarByName(aName: String): TAdvCustomToolBar;
  var
    i, j: integer;
  begin
    Result:= nil;
    for i:= 0 to DockList.Count-1 do
    begin
      for j:= 0 to TAdvDockPanel(DockList[i]).ToolBars.Count-1 do
      begin
        if UpperCase(aName) = UpperCase(TAdvCustomToolBar(TAdvDockPanel(DockList[i]).ToolBars[j]).Name) then
        begin
          Result:= TAdvCustomToolBar(TAdvDockPanel(DockList[i]).ToolBars[j]);
          break;
        end;
      end;
    end;
  end;

begin
  if (FPersistence.Enabled) and (FPersistence.Key <>'') and
     (FPersistence.Section<>'') and
     (not (csDesigning in ComponentState)) then
  begin
    {$IFDEF DELPHI4_LVL}
    if FPersistence.location = plRegistry then
      IniFile := TRegistryIniFile.Create(FPersistence.Key)
    else
    {$ENDIF}
      IniFile := TIniFile(tIniFile.Create(FPersistence.Key));

    //---- check and load AdvToolbar Persistence ( Added for manual setting )  
    TempATBList := TDbgList.Create;
    for j:=0 to FRows.Count-1 do
      for i:= 0 to FRows.Items[j].ToolBarList.Count-1 do
        TempATBList.Add(FRows.Items[j].ToolBarList[i]);

    for j:= 0 to TempATBList.Count-1 do
    begin
      if not TAdvCustomToolBar(TempATBList[j]).FPersistSettingLoaded then
        TAdvCustomToolBar(TempATBList[j]).LoadPosition;
    end;
    TempATBList.Free;
    //----

    TempToolBarList:= TStringList.Create;
    for j:=0 to FRows.Count-1 do
      for i:= 0 to FRows.Items[j].ToolBarList.Count-1 do
        TempToolBarList.AddObject(TAdvCustomToolBar(FRows.Items[j].ToolBarList[i]).name, FRows.Items[j].ToolBarList[i]);

    ATBCount:= 0;

    with IniFile do
    begin
      ATBCount:= ReadInteger(FPersistence.section,'ToolBarCount', ATBCount);

      if ATBCount > 0 then
      begin
        RC := ReadInteger(FPersistence.section,'RowCount', FRows.Count);
        FRows.Clear;
        for j:= 0 to RC-1 do
          FRows.Add;

        DockList:= TDbgList.Create;
        BuildDockPanelList;

        for i:= 1 to ATBCount do
        begin
          N := ReadString(FPersistence.section, 'Name'+inttostr(i), self.name);
          AToolBar := GetToolBarByName(N);
          if AToolBar = nil then // ToolBar not found
          begin
            // search and Add ToolBar
            AToolBar:= SearchToolBarByName(N);
            if AToolBar <> nil then
            begin
              AToolBar.Parent:= self;
              self.RemoveToolBar(AToolBar);
            end;
          end;

          if AToolBar <> nil then    // ToolBar Found
          begin
            R := ReadInteger(FPersistence.section, N+'.Row', AToolBar.FRow);
            L := ReadInteger(FPersistence.section, N+'.Left', AToolBar.Left);
            T := ReadInteger(FPersistence.section, N+'.Top', AToolBar.Top);
            W := ReadInteger(FPersistence.section, N+'.Width', AToolBar.Width);
            H := ReadInteger(FPersistence.section, N+'.Height', AToolBar.Height);
            SV := ReadInteger(FPersistence.section, N+'.Visible', Integer(AToolBar.Visible));

            if R < FRows.Count then
            begin
              FRows.Items[R].FToolBarList.Add(AToolBar);
              AToolBar.FRow:= R;
            end;

            OldV:= AToolBar.AllowBoundChange;
            AToolBar.AllowBoundChange:= true;

            if (W <> AToolBar.Width) then
              AToolBar.Width := W;

            if (L <> AToolBar.Left) then
              AToolBar.Left := L;

            if (T <> AToolBar.Top) then
              AToolBar.Top := T;

            if (H <> AToolBar.Height) then
              AToolBar.Height := H;

            AToolBar.AllowBoundChange:= OldV;

            if AToolBar.Visible <> Boolean(SV) then
              AToolBar.Visible := Boolean(SV);

            //if AToolBar.Visible <> Boolean(SV) then
              //AToolBar.Visible := Boolean(SV);
            //OutputDebugString(PChar(inttostr(R)));
          end;
        end;

        TempList := TDbgList.Create;
        for i:=0 to FRows.Count-1 do
          TempList.Add(FRows.Items[i]);

        for i:=0 to TempList.Count-1 do
          FRows.DeleteMeIfEmpty(TempList[i]);

        TempList.Free;
       { for i:=0 to FRows.Count-1 do
          FRows.DeleteMeIfEmpty(FRows.Items[i]);
        }

        for i:= 0 to TempToolBarList.Count-1 do
        begin
          with FRows.Add do
          begin
            AddToolBar(TAdvCustomToolBar(TempToolBarList.Objects[i]));
          end;
        end;

        FRows.SetRowsPosition;
        DockList.Free;
        for i := 0 to AdvToolBarCount - 1 do
        begin
          if AdvToolBars[i].Visible then
          begin
            AdvToolBars[i].SetControlsPosition;  // Fix: extra space iss
            AdvToolBars[i].UpdateRULists;
          end;
        end;
      end;

    end;
    IniFile.Free;
    TempToolBarList.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SaveToolBarsPosition;
var
  r, i, c: integer;
  AToolBar: TAdvCustomToolBar;
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
begin
  if (FPersistence.Enabled) and (FPersistence.Key <>'') and
     (FPersistence.Section <>'') and
     (not (csDesigning in ComponentState)) then
  begin
    {$IFDEF DELPHI4_LVL}
    if FPersistence.Location = plRegistry then
      IniFile := TRegistryIniFile.Create(FPersistence.Key)
    else
    {$ENDIF}
      IniFile := TIniFile.Create(FPersistence.Key);

    with IniFile do
    begin
      i:= 0;
      for r:=0 to FRows.Count-1 do
        i:= i + FRows.Items[r].ToolBarList.Count;

      i := i + FHiddenToolBars.Count;

      WriteInteger(FPersistence.section,'ToolBarCount', i);
      WriteInteger(FPersistence.section,'RowCount', FRows.Count);

      c:= 1;
      for r:=0 to FRows.Count-1 do
      begin
        for i:= 0 to FRows.Items[r].ToolBarList.Count-1 do
        begin
          AToolBar:= FRows.Items[r].ToolBarList[i];
          WriteString(FPersistence.section, 'Name'+inttostr(c), AToolBar.Name);
          WriteInteger(FPersistence.section, AToolBar.Name+'.Row', AToolBar.FRow);
          WriteInteger(FPersistence.section, AToolBar.Name+'.Left', AToolBar.Left);
          WriteInteger(FPersistence.section, AToolBar.Name+'.Top', AToolBar.Top);
          WriteInteger(FPersistence.section, AToolBar.Name+'.Width', AToolBar.Width);
          WriteInteger(FPersistence.section, AToolBar.Name+'.Height', AToolBar.Height);
          WriteInteger(FPersistence.section, AToolBar.Name+'.Visible', Integer(AToolBar.Visible));
          inc(c);
        end;
      end;
      
      // Saving Invisible ToolBars
      for i:= 0 to FHiddenToolBars.Count-1 do
      begin
        AToolBar:= FHiddenToolBars[i];
        WriteString(FPersistence.section, 'Name'+inttostr(c), AToolBar.Name);
        WriteInteger(FPersistence.section, AToolBar.Name+'.Row', AToolBar.FRow);
        WriteInteger(FPersistence.section, AToolBar.Name+'.Left', AToolBar.Left);
        WriteInteger(FPersistence.section, AToolBar.Name+'.Top', AToolBar.Top);
        WriteInteger(FPersistence.section, AToolBar.Name+'.Width', AToolBar.Width);
        WriteInteger(FPersistence.section, AToolBar.Name+'.Height', AToolBar.Height);
        WriteInteger(FPersistence.section, AToolBar.Name+'.Visible', Integer(AToolBar.Visible));
        inc(c);
      end;

    end;
    IniFile.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.CreateWnd;
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.OnPersistenceChange(Sender: TObject);
var
  i, j: integer;
begin
  for j:=0 to FRows.Count-1 do
    for i:= 0 to FRows.Items[j].ToolBarList.Count-1 do
    begin
      TAdvCustomToolBar(FRows.Items[j].ToolBarList[i]).Persistence.Enabled := self.Persistence.Enabled;
      TAdvCustomToolBar(FRows.Items[j].ToolBarList[i]).Persistence.Key := self.Persistence.Key;
      TAdvCustomToolBar(FRows.Items[j].ToolBarList[i]).Persistence.Location := self.Persistence.Location;
    end;
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.GetVersion: string;
var
  vn: Integer;
begin
  vn := GetVersionNr;
  Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn)));
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.GetVersionNr: integer;
begin
  Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetVersion(const Value: string);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetMinimumSize(const Value: Integer);
begin
  if (FMinimumSize <> Value) and (Value > 0) then
  begin
    FMinimumSize := Value;
    if not (csDesigning in ComponentState) then
      FRows.SetParentSize;
  end;
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.GetPopupMenuEx: TPopupMenu;
begin
  Result := Inherited PopupMenu;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetPopupMenuEx(const Value: TPopupMenu);
begin
  Inherited PopupMenu := Value;
  if Assigned(PopupMenu) and (PopupMenu is TAdvPopupMenu) and Assigned(FCurrentToolBarStyler) then
    TAdvPopupMenu(PopupMenu).MenuStyler := FCurrentToolBarStyler.CurrentAdvMenuStyler;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.CMShowingChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.CMVisibleChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetLockHeight(const Value: Boolean);
begin
  if FLockHeight <> Value then
  begin
    FLockHeight := Value;
  end;
end;

//------------------------------------------------------------------------------

function TAdvDockPanel.IsAllowedInAnyRow(
  aAdvToolBar: TAdvCustomToolBar): Integer;
var
  i: Integer;
begin
  Result := -1;
  case Align of
    daTop, daLeft:
    begin
      for i:= FRows.Count-1 downto 0 do
      begin
        if FRows.Items[i].IsAllowed(aAdvToolBar) then
        begin
          Result := i;
          Break;
        end;
      end;
    end;
    daBottom, daRight:
    begin
      for i:= 0 to FRows.Count-1 do
      begin
        if FRows.Items[i].IsAllowed(aAdvToolBar) then
        begin
          Result := i;
          Break;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvDockPanel.SetUseRunTimeHeight(const Value: Boolean);
begin
  if FUseRunTimeHeight <> Value then
  begin
    FUseRunTimeHeight := Value;
    FRows.SetRowsPosition;
  end;
end;

//------------------------------------------------------------------------------


procedure TAdvDockPanel.ArrangeToolBars;
begin
  FRows.ReArrangeAllToolBars;
end;

//------------------------------------------------------------------------------
{ TAdvCustomToolBar }

procedure TAdvCustomToolBar.AlignControls(AControl: TControl;
  var ARect: TRect);
begin
  inherited;

  if AControl <> nil then
    //if FindControlItem(AControl)<> nil then
    //begin
      //FItems.AddNewControlItem(AControl);
      //SetItemsPosition;
    //end;

    if not FInternalControlPositioning then
    begin
      if (AControl <> nil) then
        AdjustControl(AControl)
      else
        SetControlsPosition;

      { Update on Control's visibility changed 
      if not FCompact and not (csLoading in ComponentState) and not (csDesigning in ComponentState) and Assigned(FSelfClone) and
         FSelfClone.FOldAutoPosition and FSelfClone.FOldAutoSize and (FSelfClone.Parent is TAdvPage) and not FCompactChanging and not FSelfClone.FCompactChanging then
      begin
        // First check for ScrollSelector if it has then show smallest variant other wise largest
        if FSelfClone.FCompactSmallest then
        begin
          GetSequenceControlList(FSeqControlList);
          AutoPositionControls := FSelfClone.FOldAutoPosition;
          AutoSize := FSelfClone.FOldAutoSize;
          SendMessage(FSelfClone.Parent.Handle,WM_SIZE,0,0);
        end;
      end;}

    end;
end;

//------------------------------------------------------------------------------

constructor TAdvCustomToolBar.Create(AOwner: TComponent);
begin
  inherited;
  ControlStyle := ControlStyle + [csAcceptsControls] - [csOpaque];
  FAutoSize := True;
  FAutoPositionControls := True;
  Height := DEFAULT_TOOLBARHEIGHT;
  FMinLength := DEFAULT_MINLENGTH;
  Constraints.MinWidth := FMinLength;
  FOwner := AOwner;

  FTimer := nil;
  FAntiAlias := aaClearType;

  FInternalToolBarStyler := TCustomAdvToolBarStyler.Create(self);
  FInternalToolBarStyler.Name := 'InternalStyler';
  //FInternalToolBarStyler.GradientDirection:= gdVertical;
  //FToolBarStyler := FInternalToolBarStyler;
  FToolBarStyler := nil;
  FCurrentToolBarStyler := FInternalToolBarStyler;
  FInternalToolBarStyler.AddControl(self);
  {$IFDEF DELPHI6_LVL}
  FInternalToolBarStyler.SetSubComponent(True);
  {$ENDIF}

  FATBControls := TDbgList.Create;
  FRUControls := TDbgList.Create;
  FLUHidedControls := TDbgList.Create;
  FAutoRUL := true;

  FSeqControlList := TDbgList.Create;

  FParentStyler := True;
  FDragGripWidth := 7;
  FPopupIndicatorWidth := DEFAULT_POPUPINDICATORWIDTH;//14;
  FCurrentDock := nil;
  FPosition := daTop;
  FRow := -1;
  FToolBarState := tsDocked;

  FDockableTo := [daLeft, daTop, daRight, daBottom];
  FFloatingWindow := nil;

  FCaption := '';
  FCaptionFont := TFont.Create;
  ShowPopupIndicator := true;
  ShowOptionIndicator := true;
  FShowClose := true;
  FCaptionHeight := DEFAULT_CAPTIONHEIGHT;

  FFloatingRows := 1;
  FSizeAtDock := Height;

  FShowRightHandle := true;
  FMaxLength := Constraints.MinWidth;

  FPersistence:= TPersistence.Create(self);
  FPersistence.Section:= TOOLBAR_SECTION;
  FPersistSettingLoaded := False;
  //----
  Constraints.MaxWidth := Constraints.MinWidth;
  //----

  ShowHint := True;

  FTempMenuItemCount := 0;
  FHotButton := nil;

  FAllowFloating := True;
  FLocked := False;

  DoubleBuffered := true;

  FAutoOptionMenu := False;
  FOptionWindow := nil;
  FOptionWindowPanel := nil;

  FTextAutoOptionMenu := 'Add or Remove Buttons';
  FTextOptionMenu := 'Options';

  FAutoArrangeButtons := True;
  FTimerID := 0;

  FMergedMenu := nil;

  FAutoMDIButtons := False;
  FMDIChildForm := nil;

  FMenuItemTimer := TTimer.Create(self);
  FMenuItemTimer.Interval := 1;
  FMenuItemTimer.Enabled := False;
  FMenuItemTimer.OnTimer := MenuItemTimerOnTime;

  FNextMenuHotButton := nil;

  FCaptionPosition := cpTop;
  FCaptionAlignment := taLeftJustify;
  FShowCaption := False;

  FIOptionPicture := TGDIPPicture.Create;
  FIOptionPicture.OnChange := OnOptionPictureChanged;

  FIOptionDisabledPicture := TGDIPPicture.Create;
  FIOptionDisabledPicture.OnChange := OnOptionPictureChanged;

  FOptionTimer := nil;

  FMDIChildMenuSL := TStringList.Create;
  FMDIChildMenuList := TList.Create;

  FCompact := False;
  FCompactMode := FCompact;
  FICompactPicture := TGDIPPicture.Create;
  FICompactPicture.OnChange := OnCompactPictureChanged;
  FCompactCaption := '';
  FWideCompactCaption := '';
  FSelfClone := nil;
  FCompactWindow := nil;
  FCompactMinWidth := 45;

  FCompactBtn := nil;

  FOfficeHint := TAdvHintInfo.Create;

  FParentOptionPicture := True;
  FCompactImageIndex := -1;
  FDockMode := dmAll;

  FButtonRows[1] := -100;
  FButtonRows[2] := -100;
  FButtonRows[3] := -100;
end;

//------------------------------------------------------------------------------

destructor TAdvCustomToolBar.Destroy;
begin
  if FPersistence.Enabled and not (csDesigning in ComponentState) then
    SavePosition;

  {$IFDEF DELPHI2006_LVL}
  if not (csDesigning in ComponentState) and Assigned(FToolBarStyler) and (FToolBarStyler <> FInternalToolBarStyler) then
  begin
    FToolBarStyler.RemoveControl(self);
    FToolBarStyler := nil;
  end;
  {$ENDIF}

  FInternalToolBarStyler.Free;
  FCaptionFont.Free;

  FLUHidedControls.Free;
  FRUControls.Free;
  FPersistence.Free;

  //if Assigned(FOptionWindowPanel) then   // do not destroy, parent is responsible to destroy
  //  FOptionWindowPanel.Free;

  if Assigned(FOptionWindow) then
  begin
    FOptionWindow.Free;
    FOptionWindow := nil;
  end;

  FMenuItemTimer.Free;

  FMDIChildMenuSL.Free;
  FMDIChildMenuList.Free;

  FIOptionPicture.Free;
  FIOptionDisabledPicture.Free;

  FICompactPicture.Free;

  if (FCompactWindow <> nil) then
  begin
    FCompactWindow.Free;
    FCompactWindow := nil;
  end;

  FOfficeHint.Free;
  
  FSeqControlList.Free;

  FATBControls.Free;
  FATBControls := nil;
  
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.BuildSequenceControlList;
var
  i, j, ToIndex: integer;
begin
  if FATBControls = nil then
    FATBControls := TDbgList.Create;

  FATBControls.Clear;
  for i := 0 to self.ControlCount - 1 do
  begin
    ToIndex := 0;
    for j := FATBControls.Count - 1 downto 0 do
    begin
      if Position in [daTop, daBottom] then
      begin
        if self.Controls[i].Left >= TControl(FATBControls[j]).Left then
        begin
          ToIndex := j + 1;
          break;
        end;
      end
      else //Position in [daLeft, daRight] then
      begin
        if self.Controls[i].Top >= TControl(FATBControls[j]).Top then
        begin
          ToIndex := j + 1;
          break;
        end;
      end;
    end;
    FATBControls.Insert(ToIndex, self.Controls[i]);
  end;

  if FAutoRUL then
  begin
    FRUControls.Clear;
    {$IFDEF DELPHI6_LVL}
    FRUControls.Assign(FATBControls, laCopy);
    {$ELSE}
    FRUControls.AssignList(FATBControls);
    {$ENDIF}
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.GetSequenceControlList(aList: TDbgList; CheckVisibility: Boolean = True);
var
  i, j, k, ToIndex: integer;
begin
  if not Assigned(aList) then
    Exit;
    
  aList.Clear;
  for i := 0 to self.ControlCount - 1 do
  begin
    if ((not CheckVisibility) or (CheckVisibility and Controls[i].Visible)) then
    begin
      ToIndex := 0;
      for j := aList.Count - 1 downto 0 do
      begin
        if Position in [daTop, daBottom] then
        begin
          if self.Controls[i].Left > TControl(aList[j]).Left then
          begin
            ToIndex := j + 1;
            break;
          end
          else if self.Controls[i].Left = TControl(aList[j]).Left then
          begin
            for k := j downto 0 do
            begin
              ToIndex := j;
              if (self.Controls[i].Left = TControl(aList[k]).Left) and
                 (self.Controls[i].Top >= TControl(aList[k]).Top) then
              begin
                ToIndex := k + 1;
                break;
              end;
            end;
            break;
          end;
        end;
      end;
      aList.Insert(ToIndex, self.Controls[i]);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.Resize;
begin
  inherited;

  if (Parent is TAdvPage) and (AutoPositionControls) and (csDesigning in ComponentState) then
    SetControlsPosition(false);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.Loaded;
var
  i: Integer;
begin
  inherited;
  FOldCursor := Cursor;

  BuildSequenceControlList;
  SetControlsPosition;
  GetSequenceControlList(FSeqControlList);

  if FPersistence.Enabled and not (csDesigning in ComponentState) then
    LoadPosition;

  if (csDesigning in ComponentState) then
  begin
    if Assigned(FMenu) then
      FMenuImages := FMenu.Images;
    FTempMenuItemCount := 0;
  end;

  if Assigned(FMenu) then
  begin
    for i := 0 to FATBControls.Count - 1 do
    begin
      if TControl(FATBControls[i]) is TAdvToolBarMenuButton then
        TAdvToolBarMenuButton(FAtbControls[i]).AdjustSize;
    end;

    UpdateMenu;
  end;

  if AutoMDIButtons then
  begin
    FAutoMDIButtons := False;
    AutoMDIButtons := True;
  end;

  if Assigned(Customizer) then
  begin
    Customizer.SaveInitialState;
    Customizer.UpdateAdvToolBar;
  end;

  UpdateAllGlowButtons;
  FPropertiesLoaded := True;

  if Assigned(Parent) and (Parent is TAdvPage) and Assigned(Parent.Parent) and (Parent.Parent is TAdvToolBarPager) then
  begin
    ParentStyler := ParentStyler;
    if not (csDesigning in ComponentState) then
      UpdateButtonRowCount;
  end;

  if (ParentStyler = false) and ((FToolBarStyler = FInternalToolBarStyler) or ((Assigned(FLastDock) and Assigned(FLastDock.FCurrentToolBarStyler)) and (FToolBarStyler = FLastDock.FCurrentToolBarStyler) )) and (csDesigning in ComponentState) then
    ToolBarStyler := nil;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  inherited;

  if (Operation = opInsert) then
  begin
   { if AComponent is TControl then
      if TControl(AComponent).Parent = self then
        Caption:= 'ddd'+ TControl(AComponent).Name;
      }
  end;

  if not (csDestroying in ComponentState) and (Operation = opRemove) then
  begin
    if (AComponent = FImages) then
    begin
      Images := nil;
      Invalidate;
    end;

    if (AComponent = FDisabledImages) then
    begin
      DisabledImages := nil;
      Invalidate;
    end;

    if (AComponent = FMenu) then
    begin
      Menu := nil; 
    end;

    if (AComponent = ToolBarStyler) then
      ToolBarStyler := nil;
      
    if (AComponent = OptionMenu) then
      FOptionMenu := nil;

    if (AComponent is TControl) then
      RemoveControl(TControl(AComponent));

    if (AComponent is TMainMenu) and (AComponent = FMergedMenu) then
      UnmergeMenu(FMergedMenu);

    if (AComponent is TAdvToolBarCustomizer) and (AComponent = FCustomizer) then
      Customizer := nil;  
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.FWCloseBtnRect: TRect;
begin
  Result := Rect(0, 0, 0, 0);
  if (ToolBarState = tsFloating) and ShowClose then
  begin
    Result := GetCaptionRect;
    //Result := Rect(Result.Right - CaptionHeight - 1, Result.Top, Result.Right - 1, Result.Bottom);
    Result := Rect(Result.Right - CaptionHeight - 1, Result.Top+1, Result.Right - 1, Result.Bottom-1);
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.FWCustomizedBtnRect: TRect;
begin
  Result := Rect(0, 0, 0, 0);
  if (ToolBarState = tsFloating) and ShowOptionIndicator then
  begin
    if ShowClose then
    begin
      Result := FWCloseBtnRect;
      Result := Rect(Result.Left - CaptionHeight - 2, Result.Top, Result.Left - 2, Result.Bottom);
    end
    else
    begin
      Result := GetCaptionRect;
      //Result := Rect(Result.Right - CaptionHeight - 1, Result.Top, Result.Right - 1, Result.Bottom);
      Result := Rect(Result.Right - CaptionHeight - 1, Result.Top+1, Result.Right - 1, Result.Bottom-1);
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetCaptionRect: TRect;
begin
  Result := Rect(0, 0, 0, 0);
  if ToolBarState = tsFloating then
  begin
    Result := ClientRect;
    Result.Bottom := Result.Top + CaptionHeight;
  end
  else if (ToolBarState in [tsDocked, tsFixed]) and ShowCaption then
  begin
    Result := ClientRect;
    if Position in [daTop, daBottom] then
    begin
      if CaptionPosition = cpTop then
        Result.Bottom := Result.Top + CaptionHeight
      else
        Result.Top := Result.Bottom - CaptionHeight;
    end
    else  // Position in [daLeft, daRight] then
    begin
      if CaptionPosition = cpTop then
        Result.Right := Result.Left + CaptionHeight
      else
        Result.Left := Result.Right - CaptionHeight;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetMyClientRect: TRect;
begin
  Result := ClientRect;
  if ToolBarState = tsFloating then
    Result.Top := GetCaptionRect.Bottom {+1}
  else if (ToolBarState in [tsDocked, tsFixed]) and ShowCaption then
  begin
    if Position in [daTop, daBottom] then
    begin
      if CaptionPosition = cpTop then
        Result.Top := GetCaptionRect.Bottom
      else
        Result.Bottom := GetCaptionRect.Top;
    end
    else  // Position in [daLeft, daRight] then
    begin
      if CaptionPosition = cpTop then
        Result.Left := GetCaptionRect.Right
      else
        Result.Right := GetCaptionRect.Left;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.Paint;
var
  R, CapR, TextR, SegR: TRect;
  c, ro, i: integer;
  //rgn1: HRGN;
  HorzGradient: boolean;
 { SaveIndex: integer;
  aDC: HDC;
  R2: TRect; }
  GSteps, GStepsHot: Integer;
  GRounded: Boolean;
  GColorFrom, GColorHotFrom: TColor;
  GColorTo, GColorHotTo, BrClr, BrClrHot: TColor;
  GColorMirrorFrom, GColorMirrorTo, GColorMirrorHotFrom, GColorMirrorHotTo: TColor;
  GCaptionClr, GCaptionClrTo, GCaptionBrClr, GCaptionTxtClr: TColor;
  GCaptionClrHot, GCaptionClrHotTo, GCaptionBrClrHot, GCaptionTxtClrHot: TColor;
  CP: TPoint;
  tf: TFont;
  lf: TLogFont;
  dgs: TDragGripStyle;
  ParentCtrl: TControl;
  ctw: integer;
  ctr: TRect;
  IsOnGroupPage: Boolean;
begin
  if (FUpdateCount > 0) then
    Exit;

  inherited;

  R := GetMyClientRect; // ClientRect;
  CapR := GetCaptionRect;

  IsOnGroupPage := False;

  ParentCtrl := self.Parent;
  if (ParentCtrl is TCompactWindow) and Assigned(FSelfClone) then
    ParentCtrl := FSelfClone.Parent;
  if (ParentCtrl is TAdvPage) and not (ParentCtrl.Parent is TAdvToolBarPager) and Assigned(TAdvPage(ParentCtrl).FSelfClone) then
    ParentCtrl := TAdvPage(ParentCtrl).FSelfClone;

  with FCurrentToolBarStyler, Canvas do
  begin
    // float style painting
    if ToolBarState = tsFloating then
    begin
      if (CaptionAppearance.CaptionColor <> clNone) or (CaptionAppearance.CaptionColorTo <> clNone) then
      begin
        if (CaptionAppearance.CaptionColor <> clNone) and (CaptionAppearance.CaptionColorTo <> clNone) then
          DrawGradient(Canvas, CaptionAppearance.CaptionColor, CaptionAppearance.CaptionColorTo, 80, CapR, false)
        else
        begin
          Pen.Color := CaptionAppearance.CaptionColor;
          Brush.Color := CaptionAppearance.CaptionColor;
          Rectangle(CapR);
        end;
      end;

      if CaptionAppearance.CaptionBorderColor <> clNone then
      begin
        Pen.Color := CaptionAppearance.CaptionBorderColor;
        Brush.Style := bsClear;
        Rectangle(CapR);
      end;

      if (Caption <> '') or (WideCaption <> '') then
      begin
        if ParentStyler then
          Canvas.Font.Assign(FCurrentToolBarStyler.CaptionFont)
        else
          Canvas.Font.Assign(Self.CaptionFont);

        Canvas.Font.Color := CaptionAppearance.CaptionTextColor;
        if ShowOptionIndicator then
          TextR := Rect(CapR.Left + 3, CapR.Top, FWCustomizedBtnRect.Left, CapR.Bottom)
        else if ShowClose then
          TextR := Rect(CapR.Left + 3, CapR.Top, FWCloseBtnRect.Left, CapR.Bottom)
        else
          TextR := Rect(CapR.Left + 3, CapR.Top, CapR.Right, CapR.Bottom);

        if Caption <> '' then
          DrawText(Canvas.Handle, PChar(Caption), -1, TextR, DT_SINGLELINE or DT_VCENTER)
        else
          DrawTextW(Canvas.Handle, PWideChar(WideCaption), -1, TextR, DT_SINGLELINE or DT_VCENTER);
      end;


      DrawCustomizedBtn;
      DrawCloseBtn;
    end
    else if (ToolBarState in [tsDocked, tsFixed]) and ShowCaption then
    begin
      GCaptionClr := CaptionAppearance.CaptionColor;
      GCaptionClrTo := CaptionAppearance.CaptionColorTo;
      GCaptionBrClr := CaptionAppearance.CaptionBorderColor;
      GCaptionTxtClr := CaptionAppearance.CaptionTextColor;

      GCaptionClrHot := CaptionAppearance.CaptionColorHot;
      GCaptionClrHotTo := CaptionAppearance.CaptionColorHotTo;
      GCaptionBrClrHot := CaptionAppearance.CaptionBorderColorHot;
      GCaptionTxtClrHot := CaptionAppearance.CaptionTextColorHot;

      if (ParentCtrl is TAdvPage) and (ParentCtrl.Parent is TAdvToolBarPager) then
      begin
        i := TAdvToolBarPager(parentctrl.Parent).GroupOfTab(TAdvToolBarPager(parentctrl.Parent).IndexOfPage(TAdvPage(parentctrl)));
        if (TAdvToolBarPager(parentctrl.Parent).ActivePage = TAdvPage(parentctrl)) and (i >= 0) then
        begin
          IsOnGroupPage := True;
          if not TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].DefaultAppearance then
          begin
            GCaptionClr := TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].GroupAppearance.CaptionAppearance.CaptionColor;
            GCaptionClrTo := TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].GroupAppearance.CaptionAppearance.CaptionColorTo;
            GCaptionBrClr := TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].GroupAppearance.CaptionAppearance.CaptionBorderColor;
            GCaptionTxtClr := TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].GroupAppearance.CaptionAppearance.CaptionTextColor;

            GCaptionClrHot := TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].GroupAppearance.CaptionAppearance.CaptionColorHot;
            GCaptionClrHotTo := TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].GroupAppearance.CaptionAppearance.CaptionColorHotTo;
            GCaptionBrClrHot := TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].GroupAppearance.CaptionAppearance.CaptionBorderColorHot;
            GCaptionTxtClrHot := TAdvToolBarPager(parentctrl.Parent).TabGroups.Items[i].GroupAppearance.CaptionAppearance.CaptionTextColorHot;
          end
          else
          begin
            GCaptionClr := FCurrentToolBarStyler.GroupAppearance.CaptionAppearance.CaptionColor;
            GCaptionClrTo := FCurrentToolBarStyler.GroupAppearance.CaptionAppearance.CaptionColorTo;
            GCaptionBrClr := FCurrentToolBarStyler.GroupAppearance.CaptionAppearance.CaptionBorderColor;
            GCaptionTxtClr := FCurrentToolBarStyler.GroupAppearance.CaptionAppearance.CaptionTextColor;

            GCaptionClrHot := FCurrentToolBarStyler.GroupAppearance.CaptionAppearance.CaptionColorHot;
            GCaptionClrHotTo := FCurrentToolBarStyler.GroupAppearance.CaptionAppearance.CaptionColorHotTo;
            GCaptionBrClrHot := FCurrentToolBarStyler.GroupAppearance.CaptionAppearance.CaptionBorderColorHot;
            GCaptionTxtClrHot := FCurrentToolBarStyler.GroupAppearance.CaptionAppearance.CaptionTextColorHot;
          end;
        end;
      end;


      if Assigned(FTimer) and (GCaptionClrHot <> clNone) and ((not FActive and (Parent is TAdvPage)) or not (Parent is TAdvPage)) then
      begin
        GCaptionClr := BlendColor(GCaptionClrHot , GCaptionClr, FStepHover);
        GCaptionClrTo := BlendColor(GCaptionClrHotTo, GCaptionClrTo, FStepHover);
        if (GCaptionBrClr <> clNone) or (GCaptionBrClrHot <> clNone) then
          GCaptionBrClr := BlendColor(GCaptionBrClrHot, GCaptionBrClr, FStepHover);
        if (GCaptionTxtClr <> clNone) or (GCaptionTxtClrHot <> clNone) then
          GCaptionTxtClr := BlendColor(GCaptionTxtClrHot, GCaptionTxtClr, FStepHover);
      end
      else if FHot then
      begin
        if (CaptionAppearance.CaptionColorHot <> clNone) then
          GCaptionClr := CaptionAppearance.CaptionColorHot;
        if (CaptionAppearance.CaptionColorHotTo <> clNone) then
          GCaptionClrTo := CaptionAppearance.CaptionColorHotTo;
        if (CaptionAppearance.CaptionBorderColorHot <> clNone) then
          GCaptionBrClr := CaptionAppearance.CaptionBorderColorHot;
        if (CaptionAppearance.CaptionTextColorHot <> clNone) then
          GCaptionTxtClr := CaptionAppearance.CaptionTextColorHot;
      end;

      // Set hot color when any child control has focus
      if Assigned(Parent) and ((Parent is TAdvPage) or (Parent is TCompactWindow)) and FActive and Enabled then
      begin
        if (CaptionAppearance.CaptionColorHot <> clNone) then
          GCaptionClr := CaptionAppearance.CaptionColorHot;
        if (CaptionAppearance.CaptionColorHotTo <> clNone) then
          GCaptionClrTo := CaptionAppearance.CaptionColorHotTo;
        if (CaptionAppearance.CaptionBorderColorHot <> clNone) then
          GCaptionBrClr := CaptionAppearance.CaptionBorderColorHot;
        if (CaptionAppearance.CaptionTextColorHot <> clNone) then
          GCaptionTxtClr := CaptionAppearance.CaptionTextColorHot;
      end;

      if (GCaptionClr <> clNone) or (GCaptionClrTo <> clNone) then
      begin
        if (GCaptionClr <> clNone) and (GCaptionClrTo <> clNone) then
          DrawGradient(Canvas, GCaptionClr, GCaptionClrTo, 80, CapR, false)
        else
        begin
          Pen.Color := GCaptionClr;
          Brush.Color := GCaptionClr;
          Rectangle(CapR);
        end;
      end;

      if GCaptionBrClr <> clNone then
      begin
        Pen.Color := GCaptionBrClr;
        Brush.Style := bsClear;
        Rectangle(CapR);
      end;

      if (Caption <> '') or (WideCaption <> '') then
      begin
        dgs := FCurrentToolBarStyler.DragGripStyle;

        if parentCtrl is TAdvPage then
          dgs := dsNone;

        TextR := Rect(CapR.Left, CapR.Top, CapR.Right, CapR.Bottom);
        if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
        begin
          if Position in [daTop, daBottom] then
            TextR.Left := TextR.Left + DragGripWidth + 3
          else
            TextR.Top := TextR.Top + DragGripWidth + 3;
        end
        else if (ToolBarState <> tsFloating) then
        begin
          if Position in [daTop, daBottom] then
            TextR.Left := TextR.Left + 3
          else
            TextR.Top := TextR.Top + 3;
        end;

        if ShowPopupIndicator and ShowRightHandle and (ToolBarState <> tsFloating) and not FullSize then
        begin
          if Position in [daTop, daBottom] then
            TextR.Right := TextR.Right - PopupIndicatorWidth - 2
          else
            TextR.Bottom := TextR.Bottom - PopupIndicatorWidth - 2;
        end;

        //if ParentStyler then
          Canvas.Font.Assign(FCurrentToolBarStyler.CaptionFont);
        //else
          //Canvas.Font.Assign(Self.CaptionFont);

        Canvas.Font.Color := GCaptionTxtClr;
        Canvas.Brush.Style := bsClear;

        if (Caption <> '') then
          ctw := Canvas.TextWidth(Caption)
        else
        begin
          ctr := Rect(0,0,1024,255);
          DrawTextW(Canvas.Handle, PWideChar(WideCaption), Length(WideCaption), ctr, DT_CALCRECT);
          ctw := ctr.Right - ctr.Left;
        end;

        if Position in [daLeft, daRight] then
        begin
          if Position = daLeft then
          begin
            case CaptionAlignment of
              taLeftJustify:
              begin
                CP.X := TextR.Left;
                CP.Y := TextR.Bottom - 2;
              end;
              taCenter:
              begin
                CP.X := TextR.Left;
                CP.Y := TextR.Bottom - ((TextR.Bottom - TextR.Top) - ctw) div 2;
              end;
              taRightJustify:
              begin
                CP.X := TextR.Left;
                CP.Y := TextR.Top + ctw + 2;
              end;
            end;
          end
          else
          begin
            case CaptionAlignment of
              taLeftJustify:
              begin
                CP.X := TextR.Right;
                CP.Y := TextR.Top;
              end;
              taCenter:
              begin
                CP.X := TextR.Right;// + Canvas.TextHeight(Caption);
                CP.Y := ((TextR.Bottom - TextR.Top) - ctw) div 2;
              end;
              taRightJustify:
              begin
                CP.X := TextR.Right;
                CP.Y := TextR.Bottom - ctw - 5;
              end;
            end;
          end;

          tf := TFont.Create;
          try
    {$IFNDEF TMSDOTNET}
            FillChar(lf, SizeOf(lf), 0);
    {$ENDIF}
            tf.Assign(Canvas.Font);
    {$IFNDEF TMSDOTNET}
            GetObject(tf.Handle, SizeOf(Lf), @Lf);
    {$ENDIF}
    {$IFDEF TMSDOTNET}
            GetObject(tf.Handle, Marshal.SizeOf(TypeOf(Lf)), Lf);
    {$ENDIF}

            if Position = daLeft then
              lf.lfEscapement := -2700
            else
              lf.lfEscapement := -900;
            lf.lfOrientation := 30;

            tf.Handle := CreateFontIndirect(Lf);
            Canvas.Font.Assign(tf);
          finally
            tf.Free;
          end;

          DrawVerticalText(Canvas, Caption, CP);
        end
        else // Position in [daTop, daBottom] then
        begin
          if (Caption <> '') then
          begin
            if ShowOptionIndicator and not ShowRightHandle and (ToolBarState <> tsFloating) and ShowCaption then
              TextR.Right := GetOptionIndicatorRect.Left;
            case CaptionAlignment of
              taLeftJustify: DrawText(Canvas.Handle, PChar(Caption), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_LEFT or DT_END_ELLIPSIS);
              taCenter: DrawText(Canvas.Handle, PChar(Caption), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_CENTER or DT_END_ELLIPSIS);
              taRightJustify: DrawText(Canvas.Handle, PChar(Caption), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_RIGHT or DT_END_ELLIPSIS);
            end;
          end
          else
          begin
            if ShowOptionIndicator and not ShowRightHandle and (ToolBarState <> tsFloating) and ShowCaption then
              TextR.Right := GetOptionIndicatorRect.Left;
            case CaptionAlignment of
              taLeftJustify: DrawTextW(Canvas.Handle, PWideChar(WideCaption), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_LEFT or DT_END_ELLIPSIS);
              taCenter: DrawTextW(Canvas.Handle, PWideChar(WideCaption), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_CENTER or DT_END_ELLIPSIS);
              taRightJustify: DrawTextW(Canvas.Handle, PWideChar(WideCaption), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_RIGHT or DT_END_ELLIPSIS);
            end;
          end;
        end;
      end;
    end;

    R := Rect(R.Left, R.Top, R.Right + 1, R.Bottom + 1);

    if RoundEdges then
    begin
     { rgn1 := CreateRoundRectRgn(R.Left, R.Top, R.Right, R.Bottom, 12, 12);
      SelectClipRgn(Canvas.Handle, rgn1); }
    end;

    HorzGradient := Color.Direction = gdHorizontal;

    if (Position in [daLeft, daRight]) and not ParentStyler then
      HorzGradient := not HorzGradient;

    GRounded := RoundEdges;
    GSteps := Color.Steps;
    if Assigned(Parent) and ((Parent is TAdvPage) or (Parent is TCompactWindow)) then
    begin
      GColorFrom := Color.Mirror.Color;
      GColorTo := Color.Mirror.ColorTo;
      GColorHotFrom := ColorHot.Mirror.Color;
      GColorHotTo := ColorHot.Mirror.ColorTo;
    end
    else
    begin
      GColorFrom := Color.Color;
      GColorTo := Color.ColorTo;
      GColorHotFrom := ColorHot.Color;
      GColorHotTo := ColorHot.ColorTo;
    end;
    BrClr := FCurrentToolBarStyler.BorderColor;
    GColorMirrorFrom := Color.Mirror.ColorMirror;
    GColorMirrorTo := Color.Mirror.ColorMirrorTo;

    GStepsHot := ColorHot.Steps;
    BrClrHot := BorderColorHot;
    GColorMirrorHotFrom := ColorHot.Mirror.ColorMirror;
    GColorMirrorHotTo := ColorHot.Mirror.ColorMirrorTo;

    if FullSize then
    begin
      //HorzGradient := not HorzGradient;
      GSteps := 256;
      GColorFrom := DockColor.Color;
      GColorTo := DockColor.ColorTo;
      HorzGradient := DockColor.FDirection = gdHorizontal;

      if ToolBarState = tsFloating then
      begin
        GColorTo := DockColor.Color;
        GColorFrom := DockColor.Color;
      end
      else  // do not show border for fullsize toolbars
        BrClr := clNone;

      GRounded := False;
    end;

    if (ToolBarState <> tsFloating) and (ParentCtrl is TAdvPage) and (ParentCtrl.Parent is TAdvToolBarPager) then
    begin
      i := TAdvToolBarPager(ParentCtrl.Parent).GroupOfTab(TAdvToolBarPager(ParentCtrl.Parent).IndexOfPage(TAdvPage(ParentCtrl)));
      if (TAdvToolBarPager(ParentCtrl.Parent).ActivePage = TAdvPage(ParentCtrl)) and (i >= 0) then
      begin
        IsOnGroupPage := True;
        
        if not TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].DefaultAppearance then
        begin
          GSteps := TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].GroupAppearance.ToolBarAppearance.Color.Steps;
          GColorFrom := TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].GroupAppearance.ToolBarAppearance.Color.Color;
          GColorTo := TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].GroupAppearance.ToolBarAppearance.Color.ColorTo;
          BrClr := TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].GroupAppearance.ToolBarAppearance.BorderColor;

          GStepsHot := TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].GroupAppearance.ToolBarAppearance.ColorHot.Steps;
          GColorHotFrom := TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].GroupAppearance.ToolBarAppearance.ColorHot.Color;
          GColorHotTo := TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].GroupAppearance.ToolBarAppearance.ColorHot.ColorTo;
          BrClrHot := TAdvToolBarPager(ParentCtrl.Parent).TabGroups.Items[i].GroupAppearance.ToolBarAppearance.BorderColorHot;
        end
        else
        begin
          GSteps := FCurrentToolBarStyler.GroupAppearance.ToolBarAppearance.Color.Steps;
          GColorFrom := FCurrentToolBarStyler.GroupAppearance.ToolBarAppearance.Color.Color;
          GColorTo := FCurrentToolBarStyler.GroupAppearance.ToolBarAppearance.Color.ColorTo;
          BrClr := FCurrentToolBarStyler.GroupAppearance.ToolBarAppearance.BorderColor;

          GStepsHot := FCurrentToolBarStyler.GroupAppearance.ToolBarAppearance.ColorHot.Steps;
          GColorHotFrom := FCurrentToolBarStyler.GroupAppearance.ToolBarAppearance.ColorHot.Color;
          GColorHotTo := FCurrentToolBarStyler.GroupAppearance.ToolBarAppearance.ColorHot.ColorTo;
          BrClrHot := FCurrentToolBarStyler.GroupAppearance.ToolBarAppearance.BorderColorHot;
        end;
      end;
    end;

    if Assigned(FTimer) and (GColorHotFrom <> clNone) and ((not FActive and (Parent is TAdvPage)) or not (Parent is TAdvPage)) then
    begin
      GColorFrom := BlendColor(GColorHotFrom , GColorFrom, FStepHover);
      GColorTo := BlendColor(GColorHotTo, GColorTo, FStepHover);
      GColorMirrorFrom := BlendColor(GColorMirrorHotFrom , GColorMirrorFrom, FStepHover);
      GColorMirrorTo := BlendColor(GColorMirrorHotTo, GColorMirrorTo, FStepHover);
      if (BrClr <> clNone) or (BrClrHot <> clNone) then
        BrClr := BlendColor(BrClrHot, BrClr, FStepHover);

      GSteps := GStepsHot;
    end
    else if FHot then
    begin
      if (GColorHotFrom <> clNone) then
        GColorFrom := GColorHotFrom;
      if (GColorHotTo <> clNone) then
        GColorTo := GColorHotTo;
      if (BrClr <> clNone) or (BrClrHot <> clNone) then
        BrClr := BrClrHot;
      GSteps := GStepsHot;
      if (GColorMirrorHotFrom <> clNone) then
        GColorMirrorFrom := GColorMirrorHotFrom;
      if (GColorMirrorHotTo <> clNone) then
        GColorMirrorTo := GColorMirrorHotTo;
    end;

    // Set hot color when any child control has focus
    if Assigned(Parent) and ((Parent is TAdvPage) or (Parent is TCompactWindow)) and FActive and Enabled then
    begin
      if (GColorHotFrom <> clNone) then
        GColorFrom := GColorHotFrom;
      if (GColorHotTo <> clNone) then
        GColorTo := GColorHotTo;
      if (BrClr <> clNone) or (BrClrHot <> clNone) then
        BrClr := BrClrHot;
      GSteps := GStepsHot;
      if (GColorMirrorHotFrom <> clNone) then
        GColorMirrorFrom := GColorMirrorHotFrom;
      if (GColorMirrorHotTo <> clNone) then
        GColorMirrorTo := GColorMirrorHotTo;
    end;

    if not Transparent then
    begin
      if GColorTo <> clNone then
      begin
        if (ToolBarState in [tsDocked, tsFixed]) or ((ToolBarState = tsFloating) and (FFloatingRows = 1)) then
        begin
          if Assigned(Parent) and ((Parent is TAdvPage) or (Parent is TCompactWindow)) and (ParentCtrl is TAdvPage) and (not IsOnGroupPage) then
             DrawVistaPageGradient(Canvas, R, PAGEGRAD_HEIGHT - Top, GColorFrom, GColorTo, GColorMirrorFrom, GColorMirrorTo, clNone, 3)
          else
            DrawGradient(Canvas, GColorFrom, GColorTo, GSteps, R, HorzGradient);
        end
        else
        begin
          SegR := Rect(R.Left, R.Top, R.Right, R.Top + FSizeAtDock);
          for i := 1 to FFloatingRows do
          begin
            DrawGradient(Canvas, GColorFrom, GColorTo, GSteps, SegR, HorzGradient);
            SegR.Top := SegR.Top + FSizeAtDock;
            SegR.Bottom := SegR.Bottom + FSizeAtDock;
          end;
        end;
      end
      else
      begin
        Pen.Color := GColorFrom;
        Brush.Color := GColorFrom;
        Rectangle(R);
      end;

      if not BackGround.Empty then
      begin
         // have to shift to on change event
         //set color
       { if BackGroundTransparent then
        begin
          BackGround.Transparent:= true;
          BackGround.TransparentMode:= tmAuto;
        end;  }

        case BackGroundDisplay of
          bdTile:
            begin
              c := 0;
              ro := 0;
              while ro < Height - 1 do
              begin
                while c < Width - 1 do
                begin
                  Canvas.Draw(c, ro, BackGround);
                  c := c + BackGround.Width;
                end;
                c := 1;
                ro := ro + BackGround.Height;
              end;
            end;
          bdCenter:
            begin
              Canvas.Draw((Width - BackGround.Width) div 2, (Height - BackGround.Height) div 2, BackGround);
            end;
          bdStretch:
            begin
              Canvas.StretchDraw(Rect(R.Left + 2, R.Top + 2, R.Right - 2, R.Bottom - 2), BackGround);
            end;
        end;
      end;
    end
    else // Transparent
    begin
      //Canvas.CopyRect(R, FcurrentDock.getMyImage.Canvas, Rect(Left, Top, Left+Width, Top+Height));
      (*  SaveIndex:= SaveDC(self.Canvas.Handle);
      if FcurrentDock.GetMyImage.Palette <> 0 then
      begin
        SelectPalette(self.Canvas.Handle, FcurrentDock.GetMyImage.Palette, true);
        RealizePalette(self.Canvas.Handle);
      end;
      aDC := CreateCompatibleDC(self.Canvas.Handle);
      SelectObject(aDC, FcurrentDock.GetMyImage.Handle);
      R2:= R;
      {while R2.Left < R2.Right do
      begin
        while R2.Top < R2.Bottom do
        begin  }
          BitBlt(self.Canvas.Handle, R2.Left, R2.Top, R2.Right-R2.Left, Height, aDc, Left, Top, SRCCOPY);
      {    Inc(R2.Top, 16);
        end;
        R2.Top:= R.Top;
        Inc(R2.Left, 16);
      end;  }
      if aDC <> 0 then
        DeleteDC(aDC);
      RestoreDC(self.Canvas.Handle, SaveIndex); *)
    end;

    if FUseBevel then
    begin
      if ToolbarState <> tsFloating then
      begin
        case FBevel of
          bvRaised, bvSpace:
          begin
            Pen.Color := clWhite;
            MoveTo(0, Height);
            LineTo(0, 0);
            LineTo(Width, 0);

            Pen.Color := clBtnShadow;
            MoveTo(Width-1, 0);
            LineTo(Width-1, Height-1);
            LineTo(0, Height-1);
          end;
          bvLowered:
          begin
            Pen.Color := clBtnShadow;
            MoveTo(1, Height);
            LineTo(1, 1);
            LineTo(Width, 1);

            Pen.Color := clWhite;
            MoveTo(Width-1, 1);
            LineTo(Width-1, Height-1);
            LineTo(1, Height-1);
          end;
          bvNone:
          begin
          end;
        end;
      end;
    end;

    DrawMDIButtons;
    DrawDragGrip;
    DrawPopupIndicator;

    if GRounded and (Bevel = bvNone) then
    begin

      if ShowCaption and (ToolBarState in [tsDocked, tsFixed]) then
      begin
        if Position in [daTop, daBottom] then
        begin
          if CaptionPosition = cpTop then
            R.Top := ClientRect.Top
          else
            R.Bottom := ClientRect.Bottom+1;
        end
        else // Position in [daLeft, daRight] then
        begin
          if CaptionPosition = cpTop then
            R.Left := ClientRect.Left
          else
            R.Right := ClientRect.Right+1;
        end;
      end;

      if Assigned(FCurrentDock) and (self.parent is TAdvDockPanel) then
      begin

        if Position in [daTop, daBottom] then
        begin
          Canvas.Pixels[R.Left, R.Top] := FCurrentDock.Canvas.Pixels[self.Left - 1, self.Top - 1];
          Canvas.Pixels[R.Left + 1, R.Top] := FCurrentDock.Canvas.Pixels[self.Left + 1, self.Top - 1];
          Canvas.Pixels[R.Left, R.Top + 1] := FCurrentDock.Canvas.Pixels[self.Left - 1, self.Top];

          Canvas.Pixels[R.Left, R.Bottom - 2] := FCurrentDock.Canvas.Pixels[self.Left - 1, self.Top + Height];
          Canvas.Pixels[R.Left + 1, R.Bottom - 2] := FCurrentDock.Canvas.Pixels[self.Left - 1, self.Top + Height];
          Canvas.Pixels[R.Left, R.Bottom - 3] := FCurrentDock.Canvas.Pixels[self.Left - 1, self.Top + Height];

          if not ShowRightHandle and (ToolBarState <> tsFloating) and not FullSize then
          begin
            Canvas.Pixels[R.Right - 2, R.Top] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top];
            Canvas.Pixels[R.Right - 3, R.Top] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 2, self.Top];
            Canvas.Pixels[R.Right - 2, R.Top + 1] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top];

            Canvas.Pixels[R.Right - 2, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top + Height];
            Canvas.Pixels[R.Right - 3, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 2, self.Top + Height];
            Canvas.Pixels[R.Right - 2, R.Bottom - 3] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top + Height];
          end;

        end
        else
        begin
          Canvas.Pixels[R.Left, R.Top] := FCurrentDock.Canvas.Pixels[self.Left - 1, self.Top - 1];
          Canvas.Pixels[R.Left + 1, R.Top] := FCurrentDock.Canvas.Pixels[self.Left + 1, self.Top - 1];
          Canvas.Pixels[R.Left, R.Top + 1] := FCurrentDock.Canvas.Pixels[self.Left - 1, self.Top];

          Canvas.Pixels[R.Right - 1, R.Top] := FCurrentDock.getmyImage.Canvas.Pixels[self.Left + Width, self.Top]; //FCurrentDock.Canvas.Pixels[self.Left+ Width+1, self.Top];
          Canvas.Pixels[R.Right - 2, R.Top] := FCurrentDock.getmyImage.Canvas.Pixels[self.Left + Width - 1, self.Top]; //FCurrentDock.Canvas.Pixels[self.Left+ Width+1, self.Top];
          Canvas.Pixels[R.Right - 1, R.Top + 1] := FCurrentDock.getmyImage.Canvas.Pixels[self.Left + Width, self.Top + 1]; //FCurrentDock.Canvas.Pixels[self.Left+ Width+1, self.Top];

          if not ShowRightHandle and (ToolBarState <> tsFloating) and not FullSize then
          begin
            Canvas.Pixels[R.Left, R.Bottom - 2] :=  FCurrentDock.GetMyImage.Canvas.Pixels[self.Left {-1} + 1, self.Top + Height];
            Canvas.Pixels[R.Left + 1, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left {-1} + 2, self.Top + Height];
            Canvas.Pixels[R.Left, R.Bottom - 3] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left {-1} + 1, self.Top + Height];

            Canvas.Pixels[R.Right - 2, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top + Height];
            Canvas.Pixels[R.Right - 3, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 2, self.Top + Height];
            Canvas.Pixels[R.Right - 2, R.Bottom - 3] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top + Height];
          end;

        end;

       {
        Canvas.Pixels[R.Right-2, R.Top]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top];
        Canvas.Pixels[R.Right-3, R.Top]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top];
        Canvas.Pixels[R.Right-2, R.Top+1]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top];

        Canvas.Pixels[R.Right-2, R.Bottom-2]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top + Height];
        Canvas.Pixels[R.Right-3, R.Bottom-2]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top + Height];
        Canvas.Pixels[R.Right-2, R.Bottom-3]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top + Height];
       }
      end;
     { SelectClipRgn(Canvas.Handle, 0);
      DeleteObject(rgn1);  }

      if Assigned(Parent) and (Self.Parent is TAdvPage) then
      begin

        if Position in [daTop, daBottom] then
        begin
          Canvas.Pixels[R.Left, R.Top] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top - 1];
          Canvas.Pixels[R.Left + 1, R.Top] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + 1, self.Top - 1];
          Canvas.Pixels[R.Left, R.Top + 1] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top];

          Canvas.Pixels[R.Left, R.Bottom - 2] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top + Height];
          Canvas.Pixels[R.Left + 1, R.Bottom - 2] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top + Height];
          Canvas.Pixels[R.Left, R.Bottom - 3] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top + Height];

          if not ShowRightHandle and (ToolBarState <> tsFloating) and not FullSize then
          begin
            Canvas.Pixels[R.Right - 2, R.Top] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width + 1, self.Top];
            Canvas.Pixels[R.Right - 3, R.Top] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width + 1, self.Top];
            Canvas.Pixels[R.Right - 2, R.Top + 1] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width + 1, self.Top];

            Canvas.Pixels[R.Right - 2, R.Bottom - 2] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width +1, self.Top + Height];
            Canvas.Pixels[R.Right - 3, R.Bottom - 2] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width +1, self.Top + Height];
            Canvas.Pixels[R.Right - 2, R.Bottom - 3] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width +1, self.Top + Height];
          end;

        end
        else
        begin
          Canvas.Pixels[R.Left, R.Top] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top - 1];
          Canvas.Pixels[R.Left + 1, R.Top] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + 1, self.Top - 1];
          Canvas.Pixels[R.Left, R.Top + 1] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top];

          Canvas.Pixels[R.Right - 1, R.Top] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width, self.Top]; //FCurrentDock.Canvas.Pixels[self.Left+ Width+1, self.Top];
          Canvas.Pixels[R.Right - 2, R.Top] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width - 1, self.Top]; //FCurrentDock.Canvas.Pixels[self.Left+ Width+1, self.Top];
          Canvas.Pixels[R.Right - 1, R.Top + 1] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width, self.Top + 1]; //FCurrentDock.Canvas.Pixels[self.Left+ Width+1, self.Top];

          if not ShowRightHandle and (ToolBarState <> tsFloating) and not FullSize then
          begin
            Canvas.Pixels[R.Left, R.Bottom - 2] :=  TAdvPage(Self.Parent).Canvas.Pixels[self.Left -1, self.Top + Height];
            Canvas.Pixels[R.Left + 1, R.Bottom - 2] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left -1, self.Top + Height];
            Canvas.Pixels[R.Left, R.Bottom - 3] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left -1, self.Top + Height];

            Canvas.Pixels[R.Right - 2, R.Bottom - 2] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width +1, self.Top + Height];
            Canvas.Pixels[R.Right - 3, R.Bottom - 2] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width +1, self.Top + Height];
            Canvas.Pixels[R.Right - 2, R.Bottom - 3] := TAdvPage(Self.Parent).Canvas.Pixels[self.Left + Width +1, self.Top + Height];
          end;

        end;

      end;

      if Assigned(Parent) and (self.parent is TCompactWindow) then
      begin
        if Position in [daTop, daBottom] then
        begin
          (* Canvas.Pixels[R.Left, R.Top] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top - 1];
          Canvas.Pixels[R.Left + 1, R.Top] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left + 1, self.Top - 1];
          Canvas.Pixels[R.Left, R.Top + 1] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top];

          Canvas.Pixels[R.Left, R.Bottom - 2] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top + Height];
          Canvas.Pixels[R.Left + 1, R.Bottom - 2] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top + Height];
          Canvas.Pixels[R.Left, R.Bottom - 3] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left - 1, self.Top + Height];

          if not ShowRightHandle and (ToolBarState <> tsFloating) and not FullSize then
          begin
            Canvas.Pixels[R.Right - 2, R.Top] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left + Width{+1}, self.Top];
            Canvas.Pixels[R.Right - 3, R.Top] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left + Width{+1}, self.Top];
            Canvas.Pixels[R.Right - 2, R.Top + 1] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left + Width{+1}, self.Top];

            Canvas.Pixels[R.Right - 2, R.Bottom - 2] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left + Width{+1}, self.Top + Height];
            Canvas.Pixels[R.Right - 3, R.Bottom - 2] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left + Width{+1}, self.Top + Height];
            Canvas.Pixels[R.Right - 2, R.Bottom - 3] := TCompactWindow(Self.Parent).Canvas.Pixels[self.Left + Width{+1}, self.Top + Height];
          end; *)

          Canvas.Pixels[R.Left, R.Top] := GColorFrom;
          Canvas.Pixels[R.Left + 1, R.Top] := GColorFrom;
          Canvas.Pixels[R.Left, R.Top + 1] := GColorFrom;

          Canvas.Pixels[R.Left, R.Bottom - 2] := GColorFrom;
          Canvas.Pixels[R.Left + 1, R.Bottom - 2] := GColorFrom;
          Canvas.Pixels[R.Left, R.Bottom - 3] := GColorFrom;

          if not ShowRightHandle and (ToolBarState <> tsFloating) and not FullSize then
          begin
            Canvas.Pixels[R.Right - 2, R.Top] := GColorFrom;
            Canvas.Pixels[R.Right - 3, R.Top] := GColorFrom;
            Canvas.Pixels[R.Right - 2, R.Top + 1] := GColorFrom;

            Canvas.Pixels[R.Right - 2, R.Bottom - 2] := GColorFrom;
            Canvas.Pixels[R.Right - 3, R.Bottom - 2] := GColorFrom;
            Canvas.Pixels[R.Right - 2, R.Bottom - 3] := GColorFrom;
          end;

        end
      end;

    end;

    if (BrClr <> clNone) and (ToolbarState <> tsFloating) then
    begin
      Pen.Color := BrClr;
      Brush.Style := bsClear;
      if GRounded and (Bevel = bvNone) then
      begin
        RoundRect(R.Left, R.Top, R.Right-1, R.Bottom-1, 6, 6);
        { TODO: 3d borders
        if (Parent is TCompactWindow) or (Parent is TAdvPage) then
        begin
          Pen.Color := BlendColor(BrClr, clWhite, 50);
          MoveTo(R.Left + 1, R.Bottom - 4);
          LineTo(R.Left + 1, R.Top + 2);
        end;}
      end
      else
        Rectangle(R);
    end;

  end; // with
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.DrawDragGrip;
var
  R: TRect;
  dgs: TDragGripStyle;

  procedure DrawDots(ARect: TRect);
  var
    i: integer;
  begin
    if Position in [daTop, daBottom] then
    begin
      ARect.Left := ARect.Left + 3;
      ARect.Top := ARect.Top + 4;
      for i := 1 to (ARect.Bottom - 8) div 4 do
      begin
        Canvas.Brush.Color := clWhite;
        Canvas.Pen.Color := clWhite;
        Canvas.Rectangle(ARect.Left + 1, ARect.Top + 1, ARect.Left + 3, ARect.Top + 3);

        Canvas.Brush.Color := clBtnShadow;
        Canvas.Pen.Color := clBtnShadow;
        Canvas.Rectangle(ARect.Left, ARect.Top, ARect.Left + 2, ARect.Top + 2);
        ARect.Top := ARect.Top + 4;
      end;
    end
    else //if Position in [daLeft, daRight] then
    begin
      ARect.Left := ARect.Left + 4;
      ARect.Top := ARect.Top + 3;
      for i := 1 to (ARect.Right - 8) div 4 do
      begin
        Canvas.Brush.Color := clWhite;
        Canvas.Pen.Color := clWhite;
        Canvas.Rectangle(ARect.Left + 1, ARect.Top + 1, ARect.Left + 3, ARect.Top + 3);

        Canvas.Brush.Color := clBtnShadow;
        Canvas.Pen.Color := clBtnShadow;
        Canvas.Rectangle(ARect.Left, ARect.Top, ARect.Left + 2, ARect.Top + 2);
        ARect.Left := ARect.Left + 4;
      end;
    end;
  end;

  procedure DrawLines(ARect: TRect; DoubleLine: Boolean);
  begin
    if DoubleLine then
    begin
      if Position in [daTop, daBottom] then
      begin
        Draw3DLine(Canvas, Point(ARect.Left + 2, ARect.Bottom - 4), Point(ARect.Left + 2, ARect.Top + 3), true);
        Draw3DLine(Canvas, Point(ARect.Left + 5, ARect.Bottom - 4), Point(ARect.Left + 5, ARect.Top + 3), true);
      end
      else
      begin
        Draw3DLine(Canvas, Point(ARect.Left + 3, ARect.Top + 2), Point(ARect.Right - 5, ARect.Top + 2), true, false);
        Draw3DLine(Canvas, Point(ARect.Left + 3, ARect.Top + 5), Point(ARect.Right - 5, ARect.Top + 5), true, false);
      end;
    end
    else
    begin
      if Position in [daTop, daBottom] then
        Draw3DLine(Canvas, Point(ARect.Left + 4, ARect.Bottom - 4), Point(ARect.Left + 4, ARect.Top + 3), true)
      else
        Draw3DLine(Canvas, Point(ARect.Left + 3, ARect.Top + 4), Point(ARect.Right - 5, ARect.Top + 4), true, false);
    end;
  end;

  procedure DrawFlatDots(ARect: TRect);
  var
    i: integer;
  begin
    if Position in [daTop, daBottom] then
    begin
      ARect.Left := ARect.Left + 1;
      ARect.Top := ARect.Top + 3;
      for i := 1 to (ARect.Bottom - 8) div 2 do
      begin
        Canvas.Pen.Color := RGB(165, 165, 165);
        Canvas.MoveTo(ARect.Left + 1, ARect.Top + 1);
        Canvas.LineTo(ARect.Left + 4, ARect.Top + 1);
        ARect.Top := ARect.Top + 2;
      end;
    end
    else //if Position in [daLeft, daRight] then
    begin
      ARect.Left := ARect.Left + 3;
      ARect.Top := ARect.Top + 1;
      for i := 1 to (ARect.Right - 8) div 2 do
      begin
        Canvas.Pen.Color := RGB(165, 165, 165);
        Canvas.MoveTo(ARect.Left + 1, ARect.Top + 1);
        Canvas.LineTo(ARect.Left + 1, ARect.Top + 4);

        ARect.Left := ARect.Left + 2;
      end;
    end;
  end;

begin
  dgs := FCurrentToolBarStyler.DragGripStyle;

  if (Parent is TAdvPage) or (Parent is TCompactWindow) then
    dgs := dsNone;

  if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
  begin
    if Position in [daTop, daBottom] then
      R := Rect(1, 1, DragGripWidth, Height)
    else
      R := Rect(1, 1, Width, DragGripWidth);

    with FCurrentToolBarStyler, Canvas do
    begin
      if not DragGripImage.Empty then
      begin
        Canvas.StretchDraw(Rect(R.Left, R.Top, R.Right, R.Bottom), DragGripImage);
      end
      else
      begin
        case dgs of
          dsDots: DrawDots(R);
          dsSingleLine: DrawLines(R, false);
          dsDoubleLine: DrawLines(R, true);
          dsFlatDots: DrawFlatDots(R);
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------
// Color : 129, 129, 129
// ColorTo: 161, 161, 161

procedure TAdvCustomToolBar.DrawPopupIndicator;
var
  R: TRect;
  //rgn1, rgn2: HRGN;
  clr, clrto, brClr: TColor;
  ClrMirror, ClrMirrorTo: TColor;
  GradB, GradU: TGDIPGradient;
  DoDraw: Boolean;
  Pic: TGDIPPicture;

  procedure DrawScrollArrows(R: TRect);
  begin
    if CanExpand <= 0 then
      Exit;

    with Canvas do
    begin
      if Position in [daTop, daBottom] then
      begin
        //  |_
        //  |
        Pen.Color := clBlack;
        moveto(R.Right - 6, R.Top + 5);
        LineTo(R.Right - 6, R.Top + 8);
        moveto(R.Right - 6, R.Top + 6);
        LineTo(R.Right - 4, R.Top + 6);
        //  |_
        //  |
        moveto(R.Right - 10, R.Top + 5);
        LineTo(R.Right - 10, R.Top + 8);
        moveto(R.Right - 10, R.Top + 6);
        LineTo(R.Right - 8, R.Top + 6);

        //  |-
        Pen.Color := clWhite;
        moveto(R.Right - 5, R.Top + 7);
        LineTo(R.Right - 5, R.Top + 9);
        moveto(R.Right - 5, R.Top + 7);
        LineTo(R.Right - 3, R.Top + 7);
        //  |-
        moveto(R.Right - 9, R.Top + 7);
        LineTo(R.Right - 9, R.Top + 9);
        moveto(R.Right - 9, R.Top + 7);
        LineTo(R.Right - 7, R.Top + 7);
      end
      else
      begin
        //  -|-
        Pen.Color := clBlack;
        moveto(R.Left + 5, R.Top + 5);
        LineTo(R.Left + 8, R.Top + 5);
        moveto(R.Left + 6, R.Top + 5);
        LineTo(R.Left + 6, R.Top + 7);
        //  -|-
        moveto(R.Left + 5, R.Top + 9);
        LineTo(R.Left + 8, R.Top + 9);
        moveto(R.Left + 6, R.Top + 9);
        LineTo(R.Left + 6, R.Top + 11);
        //  |-
        Pen.Color := clWhite;
        moveto(R.Left + 7, R.Top + 6);
        LineTo(R.Left + 9, R.Top + 6);
        moveto(R.Left + 7, R.Top + 6);
        LineTo(R.Left + 7, R.Top + 8);
        //  |-
        moveto(R.Left + 7, R.Top + 10);
        LineTo(R.Left + 9, R.Top + 10);
        moveto(R.Left + 7, R.Top + 10);
        LineTo(R.Left + 7, R.Top + 12);
      end;
    end;
  end;

  procedure DrawFlatScrollArrows(R: TRect);
  begin
    if CanExpand <= 0 then
      exit;

    with Canvas do
    begin
      Pen.Color:= clBlack;
      if Position in [daTop, daBottom] then
      begin
        MoveTo(R.Left + 8, R.Top + 3);
        LineTo(R.Left + 11, R.Top + 6);
        MoveTo(R.Left + 11, R.Top + 6);
        LineTo(R.Left + 7, R.Top + 10);

        MoveTo(R.Left + 6, R.Top + 3);
        LineTo(R.Left + 9, R.Top + 6);
        MoveTo(R.Left + 9, R.Top + 6);
        LineTo(R.Left + 5, R.Top + 10);
      end
      else // Position in [daLeft, daRight] then
      begin
        MoveTo(R.Left + 3, R.Top + 6);
        LineTo(R.Left + 5, R.Top + 8);
        MoveTo(R.Left + 5, R.Top + 8);
        LineTo(R.Left + 8, R.Top + 5);

        MoveTo(R.Left + 3, R.Top + 8);
        LineTo(R.Left + 5, R.Top + 10);
        MoveTo(R.Left + 5, R.Top + 10);
        LineTo(R.Left + 8, R.Top + 7);
      end;
    end;
  end;

  procedure DrawOptionsIndicator(R: TRect);
  begin
    if not ShowOptionIndicator then
      Exit;

    with Canvas do
    begin
      if Position in [daTop, daBottom] then
      begin
        Pen.Color := clBlack;
        moveto(R.Right - 9, R.Bottom - 11);
        LineTo(R.Right - 4, R.Bottom - 11);

        moveto(R.Right - 9, R.Bottom - 8);
        LineTo(R.Right - 4, R.Bottom - 8);
        moveto(R.Right - 8, R.Bottom - 7);
        LineTo(R.Right - 5, R.Bottom - 7);
        Pixels[R.Right - 7, R.Bottom - 6] := clBlack;

        Pen.Color := clWhite;
        moveto(R.Right - 8, R.Bottom - 10);
        LineTo(R.Right - 3, R.Bottom - 10);

        moveto(R.Right - 5, R.Bottom - 7);
        LineTo(R.Right - 3, R.Bottom - 7);
        moveto(R.Right - 6, R.Bottom - 6);
        LineTo(R.Right - 4, R.Bottom - 6);
        Pixels[R.Right - 6, R.Bottom - 5] := clWhite;
      end
      else
      begin
        Pen.Color := clBlack;
        moveto(R.Right - 9, R.Top + 5);
        LineTo(R.Right - 9, R.Top + 10);

        moveto(R.Right - 6, R.Top + 5);
        LineTo(R.Right - 6, R.Top + 10);
        moveto(R.Right - 5, R.Top + 6);
        LineTo(R.Right - 5, R.Top + 9);
        Pixels[R.Right - 4, R.Top + 7] := clBlack;

        Pen.Color := clWhite;
        moveto(R.Right - 8, R.Top + 6);
        LineTo(R.Right - 8, R.Top + 11);

        moveto(R.Right - 5, R.Top + 9);
        LineTo(R.Right - 5, R.Top + 11);
        moveto(R.Right - 4, R.Top + 8);
        LineTo(R.Right - 2, R.Top + 8);
        Pixels[R.Right - 4, R.Top + 9] := clWhite;
      end;
    end;
  end;

  procedure DrawFlatOptionsIndicator(R: TRect);
  begin
    if not ShowOptionIndicator then
      Exit;

    with Canvas do
    begin
      if Position in [daTop, daBottom] then
      begin
        Pen.Color := clBlack;
        moveto(R.Right - 9, R.Bottom - 9);
        LineTo(R.Right - 4, R.Bottom - 9);

        moveto(R.Right - 9, R.Bottom - 7);
        LineTo(R.Right - 4, R.Bottom - 7);
        moveto(R.Right - 8, R.Bottom - 6);
        LineTo(R.Right - 5, R.Bottom - 6);
        Pixels[R.Right - 7, R.Bottom - 5] := clBlack;
      end
      else
      begin
        Pen.Color := clBlack;
        moveto(R.Right - 9, R.Top + 6);
        LineTo(R.Right - 9, R.Top + 11);

        moveto(R.Right - 6, R.Top + 6);
        LineTo(R.Right - 6, R.Top + 11);
        moveto(R.Right - 5, R.Top + 7);
        LineTo(R.Right - 5, R.Top + 10);
        Pixels[R.Right - 4, R.Top + 8] := clBlack;
      end;
    end;
  end;

begin
  if ShowPopupIndicator and ShowRightHandle and (ToolBarState <> tsFloating) and not FullSize then
  begin
    if Position in [daTop, daBottom] then
      R := Rect(Width - PopupIndicatorWidth, 0, Width + 1, Height + 1)
    else
      R := Rect(0, Height - PopupIndicatorWidth, Width, Height);

    {
    if FCurrentToolBarStyler.Style = bsOffice2000 then
    begin
      if Position in [daTop, daBottom] then
        R := Rect(R.Left, R.Top+1, R.Right - 2, R.Bottom -2)
      else
        R := Rect(R.Left+1, R.Top+1, R.Right-1, R.Bottom);
    end;
    }
    if not FCurrentToolBarStyler.RoundEdges then
    begin
      if Position in [daTop, daBottom] then
        R := Rect(R.Left-1, R.Top+1, R.Right - 2, R.Bottom -2)
      else
        R := Rect(R.Left+1, R.Top, R.Right-1, R.Bottom-1);

    end;

    if FDownPopupIndicator or (Assigned(FOptionWindow) and (FOptionWindow.Visible)) then
    begin
      clr := FCurrentToolBarStyler.RightHandleColorDown;
      clrto := FCurrentToolBarStyler.RightHandleColorDownTo;
      brClr := FCurrentToolBarStyler.ButtonAppearance.BorderDownColor;
    end
    else if FHotPopupIndicator then
    begin
      clr := FCurrentToolBarStyler.RightHandleColorHot;
      clrto := FCurrentToolBarStyler.RightHandleColorHotTo;
      brClr := FCurrentToolBarStyler.ButtonAppearance.BorderHotColor;
    end
    else
    begin
      clr := FCurrentToolBarStyler.RightHandleColor;
      clrto := FCurrentToolBarStyler.RightHandleColorTo;
      brClr := FCurrentToolBarStyler.ButtonAppearance.BorderColor;
    end;

    with FCurrentToolBarStyler, Canvas do
    begin
      if not RightHandleImage.Empty then
      begin
        Canvas.StretchDraw(Rect(R.Left, R.Top, R.Right, R.Bottom), RightHandleImage);
      end
      else
      begin
        //case FCurrentToolBarStyler.Style of
          //bsOffice2003Blue, bsOffice2003Silver, bsOffice2003Olive:
          //begin
            // Draw BackGround
        if (Clr <> clNone) and (ClrTo <> clNone) then
        begin
          Pen.Color := clr;
          Brush.Color := clr;
          if Position in [daTop, daBottom] then
          begin
            DrawGradient(Canvas, clr, clrto, 16, Rect(R.Left + 3, R.Top, R.Right, R.Bottom), false);
            //Rectangle(R.Left + 3, R.Top, R.Right, R.Bottom);
          end
          else
          begin
            DrawGradient(Canvas, clr, clrto, 16, Rect(R.Left, R.Top + 3, R.Right, R.Bottom), true);
            //Rectangle(R.Left, R.Top + 3, R.Right, R.Bottom);
          end;
        end
        else
        begin
          Pen.Color := clr;
          Brush.Color := clr;
          if Position in [daTop, daBottom] then
          begin
            Rectangle(R.Left + 3, R.Top, R.Right, R.Bottom);
          end
          else
          begin
            Rectangle(R.Left, R.Top + 3, R.Right, R.Bottom);
          end;
        end;

        if RoundEdges then
        begin
          {
          rgn1 := CreateRoundRectRgn(R.Left, R.Top, R.Right, R.Bottom, 10, 10);
          rgn2 := CreateRectRgn(R.Left, R.Top, R.Left +5, R.Bottom-1);
          CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
          SelectClipRgn(Canvas.Handle, rgn1);

          Pen.Color:= RightHandleColor;
          Brush.Color:= RightHandleColor;
          RoundRect(R.Left-8, R.Top, R.Right, R.Bottom, 12, 12);

          SelectClipRgn(Canvas.Handle, 0);
          DeleteObject(rgn1);
          DeleteObject(rgn2);


          rgn1 := CreateRoundRectRgn(R.Left, R.Top, R.Left+5, R.Bottom, 10, 10);
          rgn2 := CreateRectRgn(R.Left, R.Top, R.Left+1 , R.Bottom-1);
          CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
          SelectClipRgn(Canvas.Handle, rgn1);
          }

          if ClrTo = clNone then
            ClrTo := Clr;
          
          if Position in [daTop, daBottom] then
          begin
            if Assigned(FCurrentDock) and (self.parent is TAdvDockPanel) then
            begin // UnComment Numbers to remove GetMyImage
              Canvas.Pixels[R.Right - 2, R.Top] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top];
              Canvas.Pixels[R.Right - 3, R.Top] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 2, self.Top];
              Canvas.Pixels[R.Right - 2, R.Top + 1] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top];

              Canvas.Pixels[R.Right - 2, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top + Height];
              Canvas.Pixels[R.Right - 3, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 2, self.Top + Height];
              Canvas.Pixels[R.Right - 2, R.Bottom - 3] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top + Height];
            end;

            Canvas.Pixels[R.Left + 1, R.Bottom - 2] := clrto;
            Canvas.Pixels[R.Left + 2, R.Bottom - 2] := clrto;
            Canvas.Pixels[R.Left + 2, R.Bottom - 3] := clrto;

            Canvas.Pixels[R.Left + 1, R.Top] := clr;
            Canvas.Pixels[R.Left + 2, R.Top] := clr;
            Canvas.Pixels[R.Left + 2, R.Top + 1] := clr;
          end
          else // if Position in [daLeft, daRight] then
          begin
            if Assigned(FCurrentDock) and (self.parent is TAdvDockPanel) then
            begin
              Canvas.Pixels[R.Left, R.Bottom - 1] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left {-1} + 1, self.Top + Height];
              Canvas.Pixels[R.Left + 1, R.Bottom - 1] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left {-1} + 2, self.Top + Height];
              Canvas.Pixels[R.Left, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left {-1} + 1, self.Top + Height];

              Canvas.Pixels[R.Right - 1, R.Bottom - 1] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top + Height];
              Canvas.Pixels[R.Right - 2, R.Bottom - 1] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 2, self.Top + Height];
              Canvas.Pixels[R.Right - 1, R.Bottom - 2] := FCurrentDock.GetMyImage.Canvas.Pixels[self.Left + Width {+1} - 1, self.Top + Height];

            end;

          //clr:= clred;

            Canvas.Pixels[R.Left, R.Top + 2] := clr;
            Canvas.Pixels[R.Left + 1, R.Top + 2] := clr;
            Canvas.Pixels[R.Left, R.Top + 1] := clr;

            Canvas.Pixels[R.Right - 1, R.Top + 2] := clrto;
            Canvas.Pixels[R.Right - 2, R.Top + 2] := clrto;
            Canvas.Pixels[R.Right - 1, R.Top + 1] := clrto;

          end;
          //Canvas.Pixels[R.Right-2, R.Bottom-2]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top + Height];
          // Canvas.Pixels[R.Right-3, R.Bottom-2]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top + Height];
          // Canvas.Pixels[R.Right-2, R.Bottom-3]:= FCurrentDock.Canvas.Pixels[self.Left+Width+1, self.Top + Height];

          {
          if ColorTo <> clNone then
          begin
            if GradientDirection = gdHorizontal then
            begin
              DrawGradient(canvas, Canvas.Pixels[R.Left-8, R.Top+2], ColorTo, GradientStep, Rect(R.Left-8, R.Top, R.Left + 4, R.Bottom), true);
            end
            else
             DrawGradient(canvas, Color, ColorTo, GradientStep, Rect(R.Left-8, R.Top, R.Left + 4, R.Bottom), false);
          end
          else
          begin
            Pen.Color:= Color;
            Brush.Color:= Color;
            RoundRect(R.Left-8, R.Top, R.Left + 4, R.Bottom, 12, 12);
          end;
          SelectClipRgn(Canvas.Handle, 0);
          DeleteObject(rgn1);
          DeleteObject(rgn2);
          }

          //--- Scroll Arrows
          DrawScrollArrows(R);

          //---- Popup Indicator
          DrawOptionsIndicator(R);
        end
        else // if not RoundEdges then
        begin
          if brClr <> clNone then
          begin   // Draw Border
            Pen.Color := brClr;
            Brush.Style := bsClear;
            if Position in [daTop, daBottom] then
            begin
              Rectangle(R.Left + 3, R.Top, R.Right-1, R.Bottom-1);
            end
            else
            begin
              Rectangle(R.Left, R.Top + 3, R.Right, R.Bottom);
            end;
          end;

          //--- Scroll Arrows
          DrawFlatScrollArrows(R);

          //---- Popup Indicator
          DrawFlatOptionsIndicator(R);
        end;
          //end;
        //end;
      end;
    end;

  end
  else
  if ShowOptionIndicator and not ShowRightHandle and (ToolBarState <> tsFloating) and ShowCaption and (Position in [daTop, daBottom]) then
  begin // Draw OptionIndicator on Caption
    R := GetOptionIndicatorRect;
    clr := clNone;
    clrto := clNone;
    brClr := clNone;
    ClrMirror := clNone;
    ClrMirrorTo := clNone;
    GradB := ggVertical;
    GradU := ggVertical;
    DoDraw := True;
    
    with  FCurrentToolBarStyler.GlowButtonAppearance do
    begin

      if FCapOptIndicatorDown then
      begin
        clr := ColorDown;
        clrTo := ColorDownTo;
        ClrMirror := ColorMirrorDown;
        ClrMirrorTo := ColorMirrorDownTo;
        brClr := BorderColorDown;
        GradU := GradientDown;
        GradB := GradientMirrorDown;

        if Assigned(FOptionTimer) then
        begin
          if (FOptionGlowState = gsPush) then
          begin
            Clr := BlendColor(Clr, ColorHot, FOptionStepPush);
            ClrTo := BlendColor(ClrTo, ColorHotTo, FOptionStepPush);
            ClrMirror := BlendColor(ClrMirror, ColorMirrorHot, FOptionStepPush);
            ClrMirrorTo := BlendColor(ClrMirrorTo, ColorMirrorHotTo, FOptionStepPush);
            BrClr := BlendColor(BrClr, BorderColorHot, FOptionStepPush);
          end;
        end;

      end
      else //if State = absUp then
      begin
        if FCapOptIndicatorHot then
        begin
          clr := ColorHot;
          clrTo := ColorHotTo;
          ClrMirror := ColorMirrorHot;
          ClrMirrorTo := ColorMirrorHotTo;
          brClr := BorderColorHot;
          GradU := GradientHot;
          GradB := GradientMirrorHot;

          if Assigned(FOptionTimer) and (FOptionGlowState = gsHover) then
          begin
            Clr := BlendColor(Clr, FCurrentToolBarStyler.CaptionAppearance.CaptionColor, FOptionStepHover);
            if (FCurrentToolBarStyler.CaptionAppearance.CaptionColorTo <> clNone) then
              ClrTo := BlendColor(ClrTo, FCurrentToolBarStyler.CaptionAppearance.CaptionColorTo, FOptionStepHover)
            else
              ClrTo := BlendColor(ClrTo, FCurrentToolBarStyler.CaptionAppearance.CaptionColor, FOptionStepHover);
            ClrMirror := BlendColor(ClrMirror, FCurrentToolBarStyler.CaptionAppearance.CaptionColor, FOptionStepHover);
            ClrMirrorTo := BlendColor(ClrMirrorTo, FCurrentToolBarStyler.CaptionAppearance.CaptionColor, FOptionStepHover);
            BrClr := BlendColor(BrClr, BorderColor, FOptionStepHover);
          end
          else if Assigned(FOptionTimer) and (FOptionGlowState = gsPush) then
          begin
            clr := ColorDown;
            clrTo := ColorDownTo;
            ClrMirror := ColorMirrorDown;
            ClrMirrorTo := ColorMirrorDownTo;
            brClr := BorderColorDown;
            GradU := GradientDown;
            GradB := GradientMirrorDown;

            Clr := BlendColor(Clr, ColorHot, FOptionStepPush);
            ClrTo := BlendColor(ClrTo, ColorHotTo, FOptionStepPush);
            ClrMirror := BlendColor(ClrMirror, ColorMirrorHot, FOptionStepPush);
            ClrMirrorTo := BlendColor(ClrMirrorTo, ColorMirrorHotTo, FOptionStepPush);
            BrClr := BlendColor(BrClr, BorderColorHot, FOptionStepPush);
          end;
        end
        else // Normal draw
        begin
          if False then
          begin
            clr := Color;
            clrTo := ColorTo;
            ClrMirror := ColorMirror;
            ClrMirrorTo := ColorMirrorTo;
            brClr := BorderColor;
            GradU := Gradient;
            GradB := GradientMirror;
          end
          else
          begin
            DoDraw := False;
            if Assigned(FOptionTimer) and (FOptionGlowState = gsHover) then
            begin
              clr := ColorHot;
              clrTo := ColorHotTo;
              ClrMirror := ColorMirrorHot;
              ClrMirrorTo := ColorMirrorHotTo;
              brClr := BorderColorHot;
              GradU := GradientHot;
              GradB := GradientMirrorHot;

              Clr := BlendColor(Clr, FCurrentToolBarStyler.CaptionAppearance.CaptionColor, FOptionStepHover);
              if (FCurrentToolBarStyler.CaptionAppearance.CaptionColorTo <> clNone) then
                ClrTo := BlendColor(ClrTo, FCurrentToolBarStyler.CaptionAppearance.CaptionColorTo, FOptionStepHover)
              else
                ClrTo := BlendColor(ClrTo, FCurrentToolBarStyler.CaptionAppearance.CaptionColor, FOptionStepHover);
              ClrMirror := BlendColor(ClrMirror, FCurrentToolBarStyler.CaptionAppearance.CaptionColor, FOptionStepHover);
              ClrMirrorTo := BlendColor(ClrMirrorTo, FCurrentToolBarStyler.CaptionAppearance.CaptionColor, FOptionStepHover);
              BrClr := BlendColor(BrClr, BorderColor, FOptionStepHover);
              DoDraw := True;
            end;

          end;
        end;
      end;

      if DoDraw then
        DrawVistaGradient(Canvas, R,Clr, ClrTo, ClrMirror, ClrMirrorTo, BrClr,
          GradU, GradB, '', {Canvas.}Font, Enabled, False, FAntiAlias, False);

      if ParentOptionPicture and (Parent is TAdvPage) and (Parent.Parent is TAdvToolBarPager) then
      begin
        if Enabled or TAdvToolBarPager(Parent.Parent).OptionDisabledPicture.Empty then
          Pic := TAdvToolBarPager(Parent.Parent).OptionPicture
        else
          Pic := TAdvToolBarPager(Parent.Parent).OptionDisabledPicture;
      end
      else
      begin
        if Enabled or OptionDisabledPicture.Empty then
          Pic := OptionPicture
        else
          Pic := OptionDisabledPicture;
      end;

      if not Pic.Empty then
      begin
        Pic.GetImageSizes;
        Canvas.Draw(r.Left + Max(0, (R.Right - R.Left - Pic.Width) div 2), r.Top + Max(0, (R.Bottom - r.Top - Pic.Height) div 2), Pic)
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetOptionIndicatorRect: TRect;
begin
  Result := Rect(-1, -1, -1, -1);
  if ShowOptionIndicator and not ShowRightHandle and (ToolBarState <> tsFloating) and ShowCaption and (Position in [daTop, daBottom]) then
  begin
    Result := GetCaptionRect;
    Result.Right := Result.Right - 1;
    Result.Left := Result.Right - CaptionHeight+2;
    Result.Top := Result.Top + 2;
    Result.Bottom := Result.Bottom - 1;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.DrawCloseBtn;
var
  R: TRect;
  Clr: TColor;

  procedure DrawCross(R: TRect; Clr: TColor);
  begin
    with Canvas do
    begin
      Pen.Color := Clr;
                     {/}
      MoveTo(R.Left, R.Top + 7);
      LineTo(R.Left + 8, R.Top);
      MoveTo(R.Left + 1, R.Top + 7);
      LineTo(R.Left + 7, R.Top);
                     {\}
      MoveTo(R.Left, R.Top + 1);
      LineTo(R.Left + 8, R.Top + 8);
      MoveTo(R.Left + 1, R.Top + 1);
      LineTo(R.Left + 7, R.Top + 8);

    (*                {/}
      MoveTo(R.Right{Left} -1, R.top+1);//  R.Bottom - 4 - 1);
      LineTo(R.Left -1, R.Bottom);
      MoveTo(R.Right{Left} -1, R.Top); //R.Bottom - 4 - 1);
      LineTo(R.Left, R.Bottom);
                    {\}
      MoveTo(R.Right{Left}-1 , R.Bottom - 1);
      LineTo(R.Left + 1, R.top); // R.Bottom - 5 - 1);
      MoveTo(R.Right{Left} , R.Bottom - 1);
      LineTo(R.Left, R.top); // R.Bottom - 5 - 1);
    *)

    end;
  end;
begin
  if (ToolBarState = tsFloating) and (ShowClose) then
  begin
    R := FWCloseBtnRect;
    with Canvas do
    begin
      if FDownCloseBtn then
      begin
        Pen.Color := clBlack;
        Brush.Color := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.Color;
        Rectangle(R);
        Clr := clWhite;
      end
      else if FHotCloseBtn then
      begin
        Pen.Color := clBlack;
        Brush.Color := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.HoverColor;
        Rectangle(R);
        Clr := clBlack;
      end
      else
      begin
        Pen.Color := FCurrentToolBarStyler.CaptionAppearance.CaptionColor;
        Brush.Color := FCurrentToolBarStyler.CaptionAppearance.CaptionColor;
        Rectangle(R);
        Clr := clWhite;
      end;

      DrawCross(Rect(R.Left + 4, R.Top + 4, R.Right - 4, R.Bottom - 4), Clr);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.DrawCustomizedBtn;
var
  R: TRect;
  Clr: TColor;
begin
  if ToolBarState = tsFloating then
  begin
    R := FWCustomizedBtnRect;
    with Canvas do
    begin
      if FDownCustomizedBtn then
      begin
        Pen.Color := clBlack;
        Brush.Color := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.Color;
        Rectangle(R);
        Clr := clWhite; // TODO: can be replaced
      end
      else if FHotCustomizedBtn then
      begin
        Pen.Color := clBlack;
        Brush.Color := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.HoverColor;
        Rectangle(R);
        Clr := clBlack;
      end
      else
      begin
        Pen.Color := FCurrentToolBarStyler.CaptionAppearance.CaptionColor;
        Brush.Color := FCurrentToolBarStyler.CaptionAppearance.CaptionColor;
        Rectangle(R);
        Clr := clWhite;
      end;

      Canvas.Pen.Color := Clr;
             {-------}
      Canvas.MoveTo(R.Left + 5, R.Bottom - 10);
      Canvas.LineTo(R.Left + 12, R.Bottom - 10);
              {-----}
      Canvas.MoveTo(R.Left + 6, R.Bottom - 9);
      Canvas.LineTo(R.Left + 11, R.Bottom - 9);
               {---}
      Canvas.MoveTo(R.Left + 7, R.Bottom - 8);
      Canvas.LineTo(R.Left + 10, R.Bottom - 8);
                {-}
      Canvas.MoveTo(R.Left + 8, R.Bottom - 7);
      Canvas.LineTo(R.Left + 9, R.Bottom - 7);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetDragGripWidth(const Value: integer);
begin
  FDragGripWidth := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetParent(AParent: TWinControl);
var
  OldHandle: HWND;
  OldParent: TWinControl;
  Docked, UnDocked: Boolean;
  //OldValue: Boolean;
begin
  //inherited;

  if not (csDesigning in ComponentState) and not (csLoading in ComponentState) then
    HideOptionWindow;

  OldParent := inherited Parent;

  Docked := false;
  UnDocked := false;

  if AParent <> Parent then
  begin
    if FDraging then
    begin
      OldHandle := 0;
      if Assigned(AParent) then
      begin
        OldHandle := WindowHandle;
        WindowHandle := 0
      end;

      inherited SetParent(nil);

      try
        if OldHandle <> 0 then
        begin
          WindowHandle := OldHandle;
          Windows.SetParent(OldHandle, AParent.Handle);
        end;
        inherited;
      except
        raise;
      end;
    end
    else
      inherited;

    FOldState := FToolBarState;

    if AParent is TAdvDockPanel then
    begin
      if AParent <> FCurrentDock then
      begin
        if FCurrentDock <> nil then
        begin
          FCurrentDock.RemoveToolBar(self);
        end;

        if OldParent is TFloatingWindow then
        begin
          if FTimerID <> 0 then
          begin
            KillTimer(Handle, FTimerID);
            FTimerID := 0;
          end;

          if Position in [daTop, daBottom] then
          begin
            //Height := Height - CaptionHeight;

            Constraints.MinHeight := 0;
            Constraints.MaxHeight := 0;
            Height := FSizeAtDock;
          end;
        end;
        //FCurrentDock:= TAdvDockPanel(AParent);
        //FCurrentDock.AddToolBar(self);
        FToolBarState := tsDocked;
        if TAdvDockPanel(AParent).AddToolBar(self) = -1 then // Will Set FCurrentDock
        begin
          FToolBarState := FOldState; 
        end
        else
        begin
          Docked := true;
          //FToolBarState:= tsDocked;

          FLastDock := TAdvDockPanel(AParent);
          ParentStyler := ParentStyler;

          if FFloatingWindow <> nil then
          begin
            FFloatingWindow.Visible := false;
            //FFloatingWindow:= nil;
          end;
        end;
      end;
    end
    else if AParent is TFloatingWindow then
    begin
      FToolBarState := tsFloating;
      if FCurrentDock <> nil then
      begin
        FCurrentDock.RemoveToolBar(self);
        FCurrentDock := nil;
      end;

      UnDocked := true;
      //OldValue:= FInternalControlPositioning;
      //FInternalControlPositioning:= true;
      if Position in [daLeft, daRight] then
        Position := daTop;
      //FInternalControlPositioning:= OldValue;

      if Position in [daTop, daBottom] then
        Height := Height + CaptionHeight;
    end
    else
    begin
      if not (AParent is TAdvPage) or not Assigned(AParent.Parent) or (not (AParent.Parent is TAdvToolBarPager) and not (AParent.Parent is TMinimizedRibbonWindow)) then
        ParentStyler := false;
      FToolBarState := tsFixed;
      if FCurrentDock <> nil then
      begin
        FCurrentDock.RemoveToolBar(self);
        FCurrentDock := nil;
      end;      
    end;

    //SetItemsPosition;
    
    SetControlsPosition;

    if not (csLoading in ComponentState) then
    begin
      if Docked and Assigned(OnDocked) and Assigned(AParent) and (AParent is TAdvDockPanel) then
        FOnDocked(self, TAdvDockPanel(aParent))
      else if UnDocked and Assigned(FOnUnDocked) and Assigned(AParent) and (AParent is TFloatingWindow) then
        FOnUnDocked(self);
    end;
    
  end;

  if (csDesigning in ComponentState) then
  begin
    if (AParent is TAdvDockPanel) then
    begin
      ToolBarStyler := (AParent as TAdvDockPanel).FCurrentToolBarStyler;
    end;
  end; 
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetParentStyler(const Value: Boolean);
begin
  if (FParentStyler <> Value) or Value then
  begin
    FParentStyler := Value;
    ToolBarStyler := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetPopupIndicatorWidth(const Value: integer);
begin
  FPopupIndicatorWidth := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetToolBarStyler(
  const Value: TCustomAdvToolBarStyler);
begin
  if (FToolBarStyler <> Value) or (Value = nil) then
  begin
    if Assigned(FToolBarStyler) and (FToolBarStyler <> FInternalToolBarStyler) then
      FToolBarStyler.RemoveControl(self);

    FToolBarStyler := Value;

    if FParentStyler and Assigned(FLastDock) and Assigned(FLastDock.FCurrentToolBarStyler) and not(csDestroying in FLastDock.FCurrentToolBarStyler.ComponentState) then
      FToolBarStyler := FLastDock.FCurrentToolBarStyler;

    if FParentStyler and Assigned(Parent) and (Parent is TAdvPage) and Assigned(Parent.Parent) then
    begin
      if (Parent.Parent is TAdvToolBarPager) then
      begin
        if not(csDestroying in TAdvToolBarPager(Parent.Parent).FCurrentToolBarStyler.ComponentState) then
          FToolBarStyler := TAdvToolBarPager(Parent.Parent).FCurrentToolBarStyler
        else if not(csDestroying in TAdvToolBarPager(Parent.Parent).FInternalToolBarStyler.ComponentState) then
          FToolBarStyler := TAdvToolBarPager(Parent.Parent).FInternalToolBarStyler;
      end
      else if (Parent.Parent is TMinimizedRibbonWindow) and Assigned(TMinimizedRibbonWindow(Parent.Parent).AdvToolBarPager) then
      begin
        if not(csDestroying in TMinimizedRibbonWindow(Parent.Parent).AdvToolBarPager.FCurrentToolBarStyler.ComponentState) then
          FToolBarStyler := TMinimizedRibbonWindow(Parent.Parent).AdvToolBarPager.FCurrentToolBarStyler
        else if not(csDestroying in TMinimizedRibbonWindow(Parent.Parent).AdvToolBarPager.FInternalToolBarStyler.ComponentState) then
          FToolBarStyler := TMinimizedRibbonWindow(Parent.Parent).AdvToolBarPager.FInternalToolBarStyler;
      end;
    end;

    if FToolBarStyler = nil then
    begin
      //FToolBarStyler := FInternalToolBarStyler
      FCurrentToolBarStyler := FInternalToolBarStyler;
    end
    else
    begin
      FCurrentToolBarStyler := FToolBarStyler;
      FToolBarStyler.AddControl(self);
    end;

    //FCurrentToolBarStyler := FToolBarStyler;

    if Assigned(Parent) then
    begin
      AdjustSizeOfAllButtons();
      UpdateAllGlowButtons;
    end;
    //Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateMe(PropID: integer);
begin
  Color := FCurrentToolBarStyler.Color.Color;
  case PropID of
    5: 
    begin
      SetControlsPosition;
      UpdateRULists;
    end;    
    6:
    begin
      if not (csLoading in ComponentState) then
        AdjustSizeOfAllButtons(True);
    end;
    2,7:
    begin
      UpdateAllGlowButtons;
      UpdateCompactButton;
    end;
  end;

  UpdateAllContainer;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateAllContainer;
var
  I: Integer;
begin
  if Assigned(FCurrentToolBarStyler) then
  begin
    for i := 0 to FATBControls.Count - 1 do
    begin
      if (TControl(FATBControls[i]) is TAdvToolBarContainer) then
      begin
        TAdvToolBarContainer(FATBControls[i]).Invalidate;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateAllGlowButtons;
var
  I: Integer;
  tmsif: ITMSStyle;
begin
  if Assigned(FCurrentToolBarStyler) then
  begin
    for i := 0 to FATBControls.Count - 1 do
    begin
      if (TControl(FATBControls[i]) is TAdvCustomGlowButton) then
      begin
        if Compact then
          TAdvGlowButton(FAtbControls[i]).Appearance.Assign(FCurrentToolBarStyler.CompactGlowButtonAppearance)
        else
          TAdvGlowButton(FAtbControls[i]).Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
      end;

      if (TControl(FATBControls[i]) is TAdvGlowMenuButton) then
          TAdvGlowMenuButton(FAtbControls[i]).Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
{$IFNDEF TMS_STD}
      if (TControl(FATBControls[i]) is TDBAdvGlowButton) then
          TDBAdvGlowButton(FAtbControls[i]).Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
{$ENDIF}

      if (FCurrentToolBarStyler.GetInterface(ITMSStyle, tmsif)) and (FCurrentToolBarStyler.TMSStyle <> tsCustom) then
      begin
        if (TControl(FATBControls[i]).GetInterface(ITMSStyle, tmsif)) then
           tmsif.SetComponentStyle(FCurrentToolBarStyler.TMSStyle);
      end;

    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetPosition(const Value: TDockAlign);
var
  i: integer;
  //OldPos: TDockAlign;
  OldV: Boolean;
begin
  if FPosition <> Value then
  begin
    //OldPos:= FPosition;
    FPosition := Value;
    OldV := AllowBoundChange;
    AllowBoundChange := true;
{
    if (ToolBarState = tsFloating) or (FOldState = tsFloating) then
    begin
      H := FSizeAtDock;
      W := self.width;
    end
    else
    begin
      H:= self.Height;
      W:= self.Width;
    end;
}
    //FMaxLength := GetMaxLength;   // FF: Control hiding issue when changing DockPanel
    if (Value in [daTop, daBottom]) then
    begin
      //if (OldPos in [daLeft, daRight]) then
      begin
      {  if (csLoading in ComponentState) then
        begin
          Constraints.MinWidth:= FMinLength;
          Constraints.MaxWidth:= FMinLength;
        end
        else
        begin
          Constraints.MinWidth:= Constraints.MinHeight;
          Constraints.MaxWidth:= Constraints.MaxHeight;
        end;
       }
        Constraints.MinHeight := 0;
        Constraints.MaxHeight := 0;
        Constraints.MinWidth := FMinLength;
        Constraints.MaxWidth := FMaxLength;
        Width := FMaxLength;
        Height := FSizeAtDock;

       {
        if (csLoading in ComponentState) then
        begin
          Width:= H;
          Height:= FMinLength;//W;
        end
        else
        begin
          Width:= H;
          Height:= W;
        end;
        }
      end;
    end
    else if (Value in [daLeft, daRight]) then
    begin
      //if (OldPos in [daTop, daBottom]) then
      begin
       { if (csLoading in ComponentState) then
        begin
          Constraints.MinHeight:= FMinLength; //Constraints.MinWidth;
          Constraints.MaxHeight:= FMinLength; //Constraints.MaxWidth;
        end
        else
        begin
          Constraints.MinHeight:= Constraints.MinWidth;
          Constraints.MaxHeight:= Constraints.MaxWidth;
        end;
        }
        Constraints.MinWidth := 0;
        Constraints.MaxWidth := 0;
        Constraints.MinHeight := FMinLength;
        Constraints.MaxHeight := FMaxLength;
        Width := FSizeAtDock;
        Height := FMaxLength;

        {
        if (csLoading in ComponentState) then
        begin
          Width:= H;
          Height:= FMinLength;//W;
        end
        else
        begin
          Width:= H;
          Height:= W;
        end;
        }
      end;
    end;

    AllowBoundChange := OldV;

    OldV := FInternalControlPositioning;
    FInternalControlPositioning := true;
    for i := 0 to FATBControls.Count - 1 do
    begin
      if TControl(FATBControls[i]) is TAdvCustomToolBarControl then
        TAdvCustomToolBarControl(FAtbControls[i]).Position := Value;
    end;
    FInternalControlPositioning := OldV;

    FMaxLength := GetMaxLength;   // FF: Control hiding issue when changing DockPanel
    if (Value in [daTop, daBottom]) then
    begin
      Constraints.MinWidth := FMinLength;
      Constraints.MaxWidth := FMaxLength;
      Width := FMaxLength;
    end
    else if (Value in [daLeft, daRight]) then
    begin
      Constraints.MinHeight := FMinLength;
      Constraints.MaxHeight := FMaxLength;
      Height := FMaxLength;
    end;
    SetControlsPosition(false);

    UpdateRULists;  // to make sure control hide/unhide correctly
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.WMEraseBkGnd(var Msg: TMessage);
begin
  Msg.Result := 1;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMMouseLeave(var Message: TMessage);
var
  R: TRect;
begin
  inherited;

  if not FDraging then
    if self.Cursor = crSizeAll then
      self.Cursor := FOldCursor;

  if FHotPopupIndicator or FDownPopupIndicator then
  begin
    FHotPopupIndicator := false;
    FDownPopupIndicator := false;
    DrawPopupIndicator;
  end;

  if ToolBarState = tsFloating then
  begin
    if FDownCustomizedBtn or FHotCustomizedBtn then
    begin
      FDownCustomizedBtn := false;
      FHotCustomizedBtn := false;
      DrawCustomizedBtn;
    end;
    if FDownCloseBtn or FHotCloseBtn then
    begin
      FDownCloseBtn := false;
      FHotCloseBtn := false;
      DrawCloseBtn;
    end;
  end  // not Floating
  else
  begin

    if FMDIDownCloseBtn or FMDIHotCloseBtn then
    begin
      FMDIDownCloseBtn := false;
      FMDIHotCloseBtn := False;
      R := GetMDICloseBtnRect;
      InvalidateRect(Handle, @R, True);
    end;

    if FMDIDownMaxBtn or FMDIHotMaxBtn then
    begin
      FMDIDownMaxBtn := False;
      FMDIHotMaxBtn := false;
      R := GetMDIMaxBtnRect;
      InvalidateRect(Handle, @R, True);
    end;

    if FMDIDownMinBtn or FMDIHotMinBtn then
    begin
      FMDIDownMinBtn := False;
      FMDIHotMinBtn := false;
      R := GetMDIMinBtnRect;
      InvalidateRect(Handle, @R, True);
    end;

    if FCapOptIndicatorHot or FCapOptIndicatorDown then
    begin
      FCapOptIndicatorHot := False;
      FCapOptIndicatorDown := False;
      R := GetOptionIndicatorRect;
      InvalidateRect(Handle, @R, True);
    end;

  end;

  if (csDesigning in ComponentState) then
    Exit;

  if (Parent is TAdvPage) or (Parent is TCompactWindow) then
  begin
    FHot := false;
    Invalidate;

    if not Assigned(FTimer) then
    begin
      FTimer := TTimer.Create(self);
      FTimer.OnTimer := TimerProc;
      FTimer.Interval := GLOWSPEED;
      FTimer.Enabled := true;
    end;
    FTimeInc := -20;

    FGlowState := gsHover;
  end;  
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  R: TRect;  
begin
  inherited;

  if not FDraging then
  begin
    if ToolBarState = tsDocked then
    begin
      if PtOnDragGrip(Point(X, Y)) then
      begin
        if not Locked then
          BeginMove(Shift, X, Y);

       { FOldMouseX := X;
        FOldMouseY := Y;
        //SetCapture(Handle);
        FDraging:= true;  }
      end
      else if not (csDesigning in ComponentState) then
      begin
        if PtOnPopupIndicator(Point(X, Y)) or PtOnCustomizedBtn(Point(X, Y)) then
        begin
          FDownPopupIndicator:= true;
          DrawPopupIndicator;

          OptionIndicatorClick;
        end;

        // MDI Buttons
        if FAutoMDIButtons then
        begin
          if PtOnMDIClose(Point(X, Y)) then
          begin
            FMDIDownCloseBtn := true;
            DrawMDIButtons;
          end;
          if PtOnMDIMax(Point(X, Y)) then
          begin
            FMDIDownMaxBtn := true;
            DrawMDIButtons;
          end;
          if PtOnMDIMin(Point(X, Y)) then
          begin
            FMDIDownMinBtn := true;
            DrawMDIButtons;
          end;
        end;

      end;

    end
    else if ToolBarState = tsFloating then
    begin
      if PtOnGripCaption(Point(X, Y)) then
      begin
        //Screen.Cursor:= OldCursor;
        if Screen.Cursor <> crSizeAll then
          Screen.Cursor := crSizeAll;

        BeginMove(Shift, X, Y);

       // if Screen.Cursor = crSizeAll then
          //self.Cursor:= OldCursor;

      end
      else
      begin
        if PtOnCustomizedBtn(Point(X, Y)) then
        begin
          if not FDownCustomizedBtn then
          begin
            FDownCustomizedBtn := true;
            DrawCustomizedBtn;
            OptionIndicatorClick;
          end;
        end;

        if PtOnCloseBtn(Point(X, Y)) then
        begin
          if not FDownCloseBtn then
          begin
            FDownCloseBtn := true;
            DrawCloseBtn;
          end;
        end;

      end;
    end
    else
    begin

    end;

    if ShowOptionIndicator and not ShowRightHandle and (ToolBarState <> tsFloating) and ShowCaption
      and not (csDesigning in ComponentState) and (ToolBarState in [tsFixed, tsDocked]) then
    begin
      R := GetOptionIndicatorRect;
      if PtInRect(R, Point(X, Y)) then
      begin
        if not (csDesigning in ComponentState) then
        begin
          if not Assigned(FOptionTimer) then
          begin
            FOptionTimer := TTimer.Create(self);
            FOptionTimer.OnTimer := OptionTimerProc;
            FOptionTimer.Interval := GlowSpeed;
            FOptionTimer.Enabled := true;
          end;
          FOptionTimeInc := +20;
          FOptionGlowState := gsPush;
        end;

        FCapOptIndicatorDown := True;
        DrawPopupIndicator;

        CapOptionIndicatorClick;
        InvalidateCapOptionBtn;
      end;
    end;

  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.BeginMove(Shift: TShiftState; X, Y: Integer);
var
  DockInfo: PDockInfo;
  Msg: TMsg;
  CurP: TPoint;

  function GetParentForm: TCustomForm;
  var
    ParentCtrl: TWinControl;
  begin
    Result := nil;
    ParentCtrl := FLastDock.Parent;
    while Assigned(ParentCtrl) do
    begin
      if ParentCtrl is TCustomForm then
      begin
        Result := TCustomForm(ParentCtrl);
        break;
      end;
      ParentCtrl := ParentCtrl.Parent;
    end;
  end;

  procedure BuildDockPanelList;
    procedure SearchChildForDockPanel(ParentCtrl: TWinControl);
    var
      i: integer;
    begin
      if (ParentCtrl = nil) or (ContainsControl(ParentCtrl)) or (not ParentCtrl.Showing) then
        exit;

      if not (ParentCtrl is TAdvDockPanel) and (ParentCtrl is TWinControl) then
      begin
        for i := 0 to ParentCtrl.ControlCount - 1 do
        begin
          if (ParentCtrl.Controls[i] is TWinControl) and ((DockMode = dmAll) or ((DockMode = dmAllParentDockPanels) and (ParentCtrl.Controls[i] is TAdvDockPanel))) then
            SearchChildForDockPanel(TWinControl(ParentCtrl.Controls[i]));
        end;
      end;

      if (ParentCtrl is TAdvDockPanel) then
      begin
        if (FDockList.IndexOf(ParentCtrl) < 0) and AcceptableDockPanel(TAdvDockPanel(ParentCtrl)) then
        begin
          New(DockInfo);
          DockInfo.Dock := TAdvDockPanel(ParentCtrl);
          GetWindowRect(DockInfo.Dock.Handle, DockInfo.DockRect);
          case DockInfo.Dock.Align of
            daLeft: DockInfo.DockRect.Right := DockInfo.DockRect.Right + 15;
            daTop: DockInfo.DockRect.Bottom := DockInfo.DockRect.Bottom + 15;
            daRight: DockInfo.DockRect.Left := DockInfo.DockRect.Left - 15;
            daBottom: DockInfo.DockRect.Top := DockInfo.DockRect.Top - 15;
          end;
          FDockList.Add(DockInfo);
        end;
      end;
    end;

  begin
    if (DockMode = dmParentDockPanelOnly) and Assigned(FLastDock) then
    begin
      SearchChildForDockPanel(FLastDock);
    end
    else if (DockMode = dmAllParentDockPanels) and Assigned(FLastDock) and Assigned(FLastDock.Parent) then
    begin
      SearchChildForDockPanel(FLastDock.Parent);
    end
    else
    begin
      SearchChildForDockPanel(GetParentForm);
    end;
  end;

begin
  FDockList := TDbgList.Create;
  BuildDockPanelList;

  FOldMouseX := X;
  FOldMouseY := Y;
  SetCapture(Handle);
  FDraging := true;

  while GetCapture = Handle do
  begin
    case integer(GetMessage(Msg, 0, 0, 0)) of
      -1: break;
      0:
        begin
          PostQuitMessage(Msg.WParam);
          Break;
        end;
    end;

    case Msg.message of
      WM_MOUSEMOVE:
        begin
          GetCursorPos(CurP); // SmallPointToPoint(TSmallPoint(DWord(GetMessagePos)));
          CurP := ScreenToClient(CurP);
          Move(Shift, curP.X, Curp.Y);
        end;
      WM_LBUTTONUP:
        begin
          EndMove;
          break;
        end;
    else
      TranslateMessage(Msg);
      DispatchMessage(Msg);
    end;
  end;
  EndMove;
  //OutputDebugString(Pchar('DockCount: ' +inttostr(FDockList.count)));
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.Move(Shift: TShiftState; X, Y: Integer);
  procedure UpdateDockRects;
  var
    i: integer;
    DockInfo: PDockInfo;
  begin
    for i := 0 to FDockList.Count - 1 do
    begin
      DockInfo := PDockInfo(FDockList[i]);
      if Assigned(DockInfo) and Assigned(DockInfo.Dock) then
      begin
        GetWindowRect(DockInfo.Dock.Handle, DockInfo.DockRect);
        case DockInfo.Dock.Align of
          daLeft: DockInfo.DockRect.Right := DockInfo.DockRect.Right + 15;
          daTop: DockInfo.DockRect.Bottom := DockInfo.DockRect.Bottom + 15;
          daRight: DockInfo.DockRect.Left := DockInfo.DockRect.Left - 15;
          daBottom: DockInfo.DockRect.Top := DockInfo.DockRect.Top - 15;
        end;
      end;
    end;
  end;
  
var
  ax, ay, i, OldRow, OldL: integer;
  P: TPoint;
  ExceedBounds, FoundNewParent: Boolean;
  Rgn1, Rgn2: HRGN;
begin
  if FDraging then
  begin
    ExceedBounds := false;
    if ToolBarState = tsDocked then
    begin
      OldRow := Row;
      if Position in [daTop, daBottom] then
      begin
        OldL := Left;
        ax := left + (X - FOldMouseX);
        //ay:= top + (Y - FOldMouseY);
        // OutputDebugString(PChar('Lf: '+inttostr(Left) + ' ax: '+ inttostr(ax)));
        Left := ax;
        ay := Y; //ScreenToClient(Point(X, Y)).Y;
        if (ay > Height) then
          Top := Top + (ay - Height)
        else if (ay < 0) then
          Top := Top + (ay);

        if Top <> ay then
        begin
          if ay > Height then
          begin
            if (Row = OldRow) and ((Top + (ay {- Height})) > FCurrentDock.Height + DEFAULT_TOOLBARHEIGHT) then
              ExceedBounds := true;
          end
          else if ay < 0 then
          begin
            if (Row = OldRow) and (Top + ay < -DEFAULT_TOOLBARHEIGHT) then
              ExceedBounds := true;
          end;
        end;

        if (Left <> ax) and not ExceedBounds then
        begin
          if ax > Width then
          begin
            if ax > FCurrentDock.Width + DEFAULT_TOOLBARHEIGHT then
              ExceedBounds := true;
          end
          else if x < 0 then      // FF: Left Top Flickering
          begin
            if (x + OldL) < -DEFAULT_TOOLBARHEIGHT then
              ExceedBounds := true;
          end;
        end;
      end
      else // if Position in [daLeft, daRight] then
      begin
        ay := Top + (Y - FOldMouseY);
        Top := ay;

        ax := X; //ScreenToClient(Point(X, Y)).Y;
        if (ax > Width) then
          Left := Left + (ax - Width)
        else if (ax < 0) then
          Left := Left + (ax);

        if Left <> ax then
        begin
          if ax > Width then
          begin
            if (Row = OldRow) and ((Left + (ax)) > FCurrentDock.Width + DEFAULT_TOOLBARHEIGHT) then
              ExceedBounds := true;
          end
          else if ax < 0 then
          begin
            if (Row = OldRow) and (Left + ax < -DEFAULT_TOOLBARHEIGHT) then
              ExceedBounds := true;
          end;
        end;

        if (Top <> ay) and not ExceedBounds then
        begin
          if ay > Height then
          begin
            if ay > FCurrentDock.Height + DEFAULT_TOOLBARHEIGHT then
              ExceedBounds := true;
          end
          else if ay < 0 then
          begin
            if ay < -DEFAULT_TOOLBARHEIGHT then
              ExceedBounds := true;
          end;
        end;

      end;

      if Position in [daTop, daBottom] then
      begin
        Rgn1 := CreateRectRgn(Width - 2, 0, Width, 2);
        Rgn2 := CreateRectRgn(Width - 2, Height - 2, Width, Height);
      end
      else
      begin
        Rgn1 := CreateRectRgn(0, Height - 3, 3, Height);
        Rgn2 := CreateRectRgn(Width - 3, Height - 3, Width, Height);
      end;

      CombineRgn(Rgn1, Rgn1, Rgn2, RGN_OR);
      InvalidateRgn(Handle, Rgn1, true);

      DeleteObject(Rgn1);
      DeleteObject(Rgn2);

    end
    else if ToolBarState = tsFloating then
    begin
      ax := left + (X - FOldMouseX);
      ay := top + (Y - FOldMouseY);
      P := ClientToScreen(Point(aX, aY));
      FFloatingWindow.Left := P.X;
      FFloatingWindow.Top := P.Y;
    end;

    if not AllowFloating then
      ExceedBounds := False;
      
    if ExceedBounds or (ToolBarState = tsFloating) then
    begin
      FoundNewParent := false;
      for i := 0 to FDockList.Count - 1 do
      begin
        P := ClientToScreen(Point(X, Y));
        if PtInRect(PDockInfo(FDockList[i]).DockRect, P) then
        begin
          if Parent <> PDockInfo(FDockList[i]).Dock then
          begin
            Parent := PDockInfo(FDockList[i]).Dock;
            FOldMouseX := 1;      // FF: Flickering
            FoundNewParent := true;
            if FFloatingWindow <> nil then
            begin
              FFloatingWindow.Free;
              FFloatingWindow := nil;
            end;

            //if GetCapture <> Handle then
              //SetCapture(Handle);
            break;
          end;
        end;
      end;

      if not FoundNewParent and not (ToolBarState = tsFloating) then
      begin
        SetFloating;
        UpdateDockRects;
      end;
    end;

    //OutputDebugString(PChar('Top: ' + inttostr(y) + ' Left: ' + inttostr(x)));
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.EndMove;
var
  i: integer;
  DockInfo: PDockInfo;
begin
  if Screen.Cursor = crSizeAll then // TODO: Temporary
    Screen.Cursor := crDefault;

  FDraging := false;
  if GetCapture = Handle then
    ReleaseCapture;
  // Dispose DockList
  if Assigned(FDockList) then
  begin
    for i := 0 to FDockList.Count - 1 do
    begin
      DockInfo := FDockList[i];
      Dispose(DockInfo);
    end;
    FDockList.free;
    FDockList := nil;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.ButtonAtPos(X, Y: Integer): TAdvCustomToolBarButton;
var
  i: Integer;
begin
  Result := nil;
  for i := 0 to FATBControls.Count - 1 do
  begin
    if (TControl(FATBControls[i]) is TAdvCustomToolBarButton) and TControl(FATBControls[i]).Visible and TControl(FATBControls[i]).Enabled
        and (((FLUHidedControls.IndexOf(FATBControls[i]) < 0) and (ToolBarState = tsDocked)) or (ToolBarState in [tsFloating, tsFixed]))
        and (TControl(FATBControls[i]).Left <= X) and (TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width >= X)
        and (TControl(FATBControls[i]).Top <= Y) and (TControl(FATBControls[i]).Top + TControl(FATBControls[i]).Height >= Y) then
    begin
      Result := TAdvCustomToolBarButton(FATBControls[i]);
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MouseMove(Shift: TShiftState; X, Y: Integer);
var
  Button: TAdvCustomToolBarButton;
  R: TRect;
begin
  inherited;

  if FDraging then
  begin
   { ax:= left + (X - FOldMouseX);
    ay:= top + (Y - FOldMouseY);
    //if ax > 100 then
    Left:= ax;
    //Top:= ay;
    ay:= Y;//ScreenToClient(Point(X, Y)).Y;
    if (ay > Height) then
      Top:= Top + (ay - Height)
    else if (ay < 0) then
      Top:= Top + (ay);

    OutputDebugString(PChar('Top: '+inttostr(y)+' Left: '+inttostr(x)));
    }
    //Move(Shift, X, Y);
  end;

  if not FDraging then
  begin
    if not (ssLeft in Shift) and not Locked then
    begin
      if PtOnDragGrip(Point(X, Y)) then
        self.Cursor := crSizeAll
      else if self.Cursor = crSizeAll then
        self.Cursor := FOldCursor;
    end;

    if not (csDesigning in ComponentState) then
    begin
      if PtOnPopupIndicator(Point(X, Y)) then
      begin
        if not FHotPopupIndicator then
        begin
          FHotPopupIndicator := true;
          DrawPopupIndicator;
        end;
      end
      else if FHotPopupIndicator then
      begin
        FHotPopupIndicator := false;
        DrawPopupIndicator;
      end;

      if FMenuFocused then
      begin
        Button := ButtonAtPos(X, Y);
        if (Button <> nil) and (Button <> FHotButton) then
          SetButtonHot(Button);
      end;

      if FAutoMDIButtons then
      begin

        // MDI Buttons
        if PtOnMDIClose(Point(X, Y)) then
        begin
          if not FMDIHotCloseBtn then
          begin
            FMDIHotCloseBtn := true;
            DrawMDIButtons;
          end;
        end
        else if FMDIHotCloseBtn then
        begin
          FMDIHotCloseBtn := false;
          R := GetMDICloseBtnRect;
          InvalidateRect(Handle, @R, True);
          //DrawMDIButtons;
        end;

        if PtOnMDIMax(Point(X, Y)) then
        begin
          if not FMDIHotMaxBtn then
          begin
            FMDIHotMaxBtn := true;
            DrawMDIButtons;
          end;
        end
        else if FMDIHotMaxBtn then
        begin
          FMDIHotMaxBtn := false;
          R := GetMDIMaxBtnRect;
          InvalidateRect(Handle, @R, True);
          //DrawMDIButtons;
        end;

        if PtOnMDIMin(Point(X, Y)) then
        begin
          if not FMDIHotMinBtn then
          begin
            FMDIHotMinBtn := true;
            DrawMDIButtons;
          end;
        end
        else if FMDIHotMinBtn then
        begin
          FMDIHotMinBtn := false;
          R := GetMDIMinBtnRect;
          InvalidateRect(Handle, @R, True);
          //DrawMDIButtons;
        end;
      end;

      if ShowOptionIndicator and not ShowRightHandle and (ToolBarState <> tsFloating) and ShowCaption then
      begin
        R := GetOptionIndicatorRect;
        if PtInRect(R, Point(X, Y)) then
        begin
          if not FCapOptIndicatorHot then
          begin
            if not Assigned(FOptionTimer) then
            begin
              FOptionTimer := TTimer.Create(self);
              FOptionTimer.OnTimer := OptionTimerProc;
              FOptionTimer.Interval := GlowSpeed;
              FOptionTimer.Enabled := true;
            end;

            FOptionTimeInc := 20;
            //Invalidate;
            FOptionGlowState := gsHover;

            FCapOptIndicatorHot := True;
            DrawPopupIndicator;
          end;
        end
        else if FCapOptIndicatorHot then
        begin
          if not Assigned(FOptionTimer) then
          begin
            FOptionTimer := TTimer.Create(self);
            FOptionTimer.OnTimer := OptionTimerProc;
            FOptionTimer.Interval := GlowSpeed;
            FOptionTimer.Enabled := true;
          end;
          FOptionTimeInc := -20;
          FOptionGlowState := gsHover;

          FCapOptIndicatorHot := False;
          R := GetOptionIndicatorRect;
          InvalidateRect(Handle, @R, True);
        end;
      end;
      
    end;

    if ToolBarState = tsFloating then
    begin
      if PtOnCustomizedBtn(Point(X, Y)) then
      begin
        if not FHotCustomizedBtn then
        begin
          FHotCustomizedBtn := true;
          DrawCustomizedBtn;
        end;
      end
      else if FHotCustomizedBtn then
      begin
        FHotCustomizedBtn := false;
        DrawCustomizedBtn;
      end;

      if PtOnCloseBtn(Point(X, Y)) then
      begin
        if not FHotCloseBtn then
        begin
          FHotCloseBtn := true;
          DrawCloseBtn;
        end;
      end
      else if FHotCloseBtn then
      begin
        FHotCloseBtn := false;
        DrawCloseBtn;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MouseUp(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

  if FDownPopupIndicator then
  begin
    FDownPopupIndicator:= false;
    DrawPopupIndicator;
  end;

  if ShowOptionIndicator and not ShowRightHandle and (ToolBarState <> tsFloating) and ShowCaption then
  begin
    if FCapOptIndicatorDown then
    begin
      if not (csDesigning in ComponentState) then
      begin
        FOptionTimeInc := -20;
        FOptionGlowState := gsPush;
        if not Assigned(FOptionTimer) then
        begin
          FOptionTimer := TTimer.Create(self);
          FOptionTimer.OnTimer := OptionTimerProc;
          FOptionTimer.Interval := GlowSpeed;
          FOptionTimer.Enabled := true;
        end;
      end;

      FCapOptIndicatorDown := False;
      //DrawPopupIndicator;
    end;
  end;

  if not (csDesigning in ComponentState) then
  begin
    if FAutoMDIButtons then
    begin
      if FMDIDownCloseBtn then
      begin
        FMDIDownCloseBtn := False;
        FMDIHotCloseBtn := False;
        DrawMDIButtons;
        if PtOnMDIClose(Point(X, Y)) then
          MDICloseBtnClick;
      end;
      if FMDIDownMaxBtn then
      begin
        FMDIDownMaxBtn := False;
        FMDIHotMaxBtn := False;
        DrawMDIButtons;
        MDIMaxBtnClick;
      end;
      if FMDIDownMinBtn then
      begin
        FMDIDownMinBtn := False;
        FMDIHotMinBtn := False;
        DrawMDIButtons;
        MDIMinBtnClick;
      end;
    end;
  end;

  if ToolBarState = tsFloating then
  begin
    if FDownCustomizedBtn then
    begin
      FDownCustomizedBtn := false;
      DrawCustomizedBtn;
    end;
    if FDownCloseBtn then
    begin
      FDownCloseBtn := false;
      FHotCloseBtn := False;
      DrawCloseBtn;
      CloseBtnClick;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.PtOnDragGrip(P: TPoint): Boolean;
var
  dgs: TDragGripStyle;
begin
  Result := false;

  dgs := FCurrentToolBarStyler.DragGripStyle;

  if (Parent is TAdvPage) or (Parent is TCompactWindow) then
    dgs := dsNone;

  if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
  begin
    if Position in [daTop, daBottom] then
      Result := PtInRect(Rect(0, 0, DragGripWidth, Height), P)
    else
      Result := PtInRect(Rect(0, 0, Width, DragGripWidth), P);
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.PtOnPopupIndicator(P: TPoint): Boolean;
begin
  Result := false;
  if ShowPopupIndicator and ShowRightHandle then
  begin
    if Position in [daTop, daBottom] then
      Result := PtInRect(Rect(Width - PopupIndicatorWidth, 0, Width, Height), P)
    else
      Result := PtInRect(Rect(0, Height - PopupIndicatorWidth, Width, Height), P);
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.PtOnGripCaption(P: TPoint): Boolean;
var
  CapR: TRect;
begin
  Result := false;
  if ToolBarState = tsFloating then
  begin
    CapR := GetCaptionRect;
    if ShowOptionIndicator then
      CapR := Rect(CapR.Left, CapR.Top, FWCustomizedBtnRect.Left, CapR.Bottom)
    else if ShowClose then
      CapR := Rect(CapR.Left, CapR.Top, FWCloseBtnRect.Left, CapR.Bottom)
    else
      CapR := Rect(CapR.Left, CapR.Top, CapR.Right, CapR.Bottom);

    Result := PtInRect(CapR, P);
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.PtOnCloseBtn(P: TPoint): Boolean;
begin
  Result := false;
  if ToolBarState = tsFloating then
    Result := PtInRect(FWCloseBtnRect, P);
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.PtOnCustomizedBtn(P: TPoint): Boolean;
begin
  Result := false;
  if ToolBarState = tsFloating then
    Result := PtInRect(FWCustomizedBtnRect, P);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetRow(const Value: integer);
begin
  FRow := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetBounds(ALeft, ATop, AWidth,
  AHeight: Integer);
var
  OldWidth, OldHeight: integer;
begin
  //OutputDebugString(pchar(Name+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft)+' AH:'+inttostr(AHeight)+' AW:'+inttostr(AWidth)));
  //if name = 'AdvToolBar4' then
    //OutputDebugString(pchar(Name+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft)+' AH:'+inttostr(AHeight)+' AW:'+inttostr(AWidth)+' W:'+inttostr(Width)));

  OldWidth := Width;
  OldHeight := Height;

  if (Self.ToolBarState = tsDocked) and Assigned(FCurrentDock) then
  begin
    if not AllowBoundChange then
      FCurrentDock.SetToolBarBounds(self, ALeft, ATop, AWidth, AHeight);
    inherited SetBounds(ALeft, ATop, AWidth, AHeight);
  end
  else
    inherited;

  if (Position in [daTop, daBottom]) then
  begin
    if not (csLoading in ComponentState) and (OldWidth <> Width) then
      UpdateRULists;
  end
  else // position in [daLeft, daRight]
  begin
    if not (csLoading in ComponentState) and (OldHeight <> Height) then
      UpdateRULists;
  end;

  //OutputDebugString(pchar(Name+' T:'+inttostr(top)+' L:'+inttostr(Left)+' H:'+inttostr(Height)+' W:'+inttostr(Width)+' MaxH:'+inttostr(Constraints.maxHeight)));
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.CanShrink: integer;
begin
  if Position in [daTop, daBottom] then
    Result := Width - Constraints.MinWidth
  else
    Result := Height - Constraints.MinHeight;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.CanExpand: integer;
begin
  if Position in [daTop, daBottom] then
    Result := Constraints.MaxWidth - Width
  else
    Result := Constraints.MaxHeight - Height;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAllowBoundChange(const Value: boolean);
begin
  FAllowBoundChange := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetFullSize(const Value: Boolean);
begin
  if Value <> FFullSize then
  begin
    FFullSize := Value;
    if (Self.ToolBarState = tsDocked) and Assigned(FCurrentDock) and FFullSize then
    begin
      ParentStyler := true;
      FCurrentDock.SetToolBarFullSize(self);

      UpdateRULists;
      SetControlsPosition(False);
    end
    else if (Self.ToolBarState = tsDocked) and Assigned(FCurrentDock) and not FFullSize then
    begin
      UpdateSize;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetDockableTo(const Value: TDockableTo);
begin
  FDockableTo := Value;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.AcceptableDockPanel(ADockPanel: TAdvDockPanel): Boolean;
begin
  Result := (ADockPanel.Align in DockableTo);
  if Result and ADockPanel.LockHeight and not (csDesigning in ADockPanel.ComponentState) and (ADockPanel.FPropertiesLoaded) then
    Result := (ADockPanel.IsAllowedInAnyRow(self) >= 0);
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetAdvDockPanel: TAdvDockPanel;
begin
  Result := FCurrentDock;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAdvDockPanel(const Value: TAdvDockPanel);
begin
  if not Assigned(Value) or (FCurrentDock = Value) then
    Exit;

  Parent := Value;

  if (FFloatingWindow <> nil) then
  begin
    FFloatingWindow.Free;
    FFloatingWindow := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetToolBarFloating(P: TPoint);
begin
  if (FFloatingWindow = nil) and (ToolBarState <> tsFloating) then
  begin
    SetFloating(P.X, P.Y, true);
  end
  else
  begin
    FFloatingWindow.Left := P.X;
    FFloatingWindow.Top := P.Y;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetToolBarIndex: Integer;
begin
  if Parent is TAdvPage then
    Result := TAdvPage(Parent).FAdvToolBars.IndexOf(Self)
  else
    Result := -1;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetToolBarIndex(const Value: Integer);
var
  curIndex, newIndex : integer;
begin
  if Parent is TAdvPage then
  begin
    curIndex := TAdvPage(Parent).FAdvToolBars.IndexOf(Self);
    newIndex := Max(0, Min(Value, TAdvPage(Parent).FAdvToolBars.Count-1));
    if newIndex <> curIndex then
    begin
      TAdvPage(Parent).FAdvToolBars.Move(curIndex, newIndex);
      TAdvPage(Parent).UpdateAdvToolBarsPosition;
    end;

    if (ToolBarIndex >= 0) then
      TabOrder := ToolBarIndex;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetFloating(X: integer = 0; Y: integer = 0; ForcePoint: Boolean = false);
var
  P: TPoint;

  function GetMyParentForm: TCustomForm;
  var
    ParentCtrl: TWinControl;
  begin
    Result := nil;
    ParentCtrl := self.Parent;
    if Assigned(FCurrentDock) then
      ParentCtrl := FCurrentDock
    else if Assigned(FLastDock) then
      ParentCtrl := FLastDock;

    while Assigned(ParentCtrl) do
    begin
      if ParentCtrl is TCustomForm then
      begin
        Result := TCustomForm(ParentCtrl);
        break;
      end;
      ParentCtrl := ParentCtrl.Parent;
    end;
  end;

begin
  if (Self.Parent is TAdvPage) or (Self.Parent is TCompactWindow) then
    Exit;

  if (FFloatingWindow = nil) and (ToolBarState <> tsFloating) then
  begin
    FFloatingWindow := TFloatingWindow.CreateNew(FOwner);
    FFloatingWindow.BorderIcons := [];
    FFloatingWindow.BorderStyle := bsNone;
    FFloatingWindow.Ctl3D := false;
    FFloatingWindow.FormStyle := fsStayOnTop;
    FFloatingWindow.Position := poDesigned;
    //FFloatingWindow.Width := 100;
    //FFloatingWindow.Height := 100;
    //FFloatingWindow.AutoScroll := true;
    FFloatingWindow.BorderWidth := FCurrentToolBarStyler.FloatingWindowBorderWidth;
    FFloatingWindow.BorderColor := FCurrentToolBarStyler.FloatingWindowBorderColor;

    if FCurrentToolBarStyler.Color.ColorTo <> clNone then
      FFloatingWindow.Color := FCurrentToolBarStyler.Color.ColorTo
    else
      FFloatingWindow.Color := FCurrentToolBarStyler.Color.Color;

    //P:= ClientToScreen(Point(Left, Top));
    if ForcePoint then
    begin
      P := Point(X, Y);
    end
    else
    begin
      GetCursorPos(P);
      //P:= ScreenToClient(P);
    end;

    //if Position in [daLeft, daRight] then
      //Position:= daTop;

  {  if Position in [daTop, daBottom] then
      FSizeAtDock := Height
    else // daLeft, daRight
      FSizeAtDock := Width;
   }
    FSizeAtDock := GetSizeAtDock(True);

    //FLUHidedControls.Clear;
    UnHideAllControls;

    Parent := FFloatingWindow;
    FFloatingWindow.AdvCustomToolBar := self;
    FFloatingWindow.SetWindowSize;
    FFloatingWindow.Left := P.X;
    FFloatingWindow.Top := P.Y;
    //FFloatingWindow.Visible := true;

    FParentForm := GetParentForm(FLastDock);
    if FParentForm.Visible and not FFloatingWindow.Visible then
      FFloatingWindow.Visible := True
    else
    begin
      FFloatingWindow.Visible := False;
      FAutoHiding := True;
    end;
    FTimerID:= SetTimer(Handle, 500, 40, nil);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCaption(const Value: string);
begin
  if FCaption <> Value then
  begin
    FCaption := Value;
    //if ToolBarState = tsFloating then
    Invalidate;
    inherited Caption := Value;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetWideCaption(const Value: widestring);
begin
  if FWideCaption <> Value then
  begin
    FWideCaption := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCaptionFont(const Value: TFont);
begin
  FCaptionFont.Assign(Value);
  //if ToolBarState = tsFloating then
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetShowOptionIndicator(const Value: Boolean);
begin
  if FShowOptionIndicator <> Value then
  begin
    FShowOptionIndicator := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetShowPopupIndicator(const Value: Boolean);
begin
  if FShowPopupIndicator <> Value then
  begin
    FShowPopupIndicator := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetShowClose(const Value: Boolean);
begin
  FShowClose := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCaptionHeight(const Value: integer);
begin
  if (FCaptionHeight <> Value) then
  begin
    FCaptionHeight := Value;
    if ShowCaption then
    begin
      SetControlsPosition(False);
      Invalidate;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CloseBtnClick;
begin
  if ToolBarState = tsFloating then
  begin
    if FAutoDockOnClose and Assigned(FLastDock) then
    begin
      Self.Parent := FLastDock;
      if FFloatingWindow <> nil then
      begin
        FFloatingWindow.Free;
        FFloatingWindow := nil;
      end;
    end
    else
    begin
      FFloatingWindow.Visible := false;
      self.Visible := False;
      if Assigned(FOnClose) then
        FOnClose(self);
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetSizeAtDock(ForFloating: Boolean): Integer;
var
  w, h, atbW, atbH: Integer;
begin
  w := 0;
  h := 0;
  atbW := 0;
  atbH := 0;
  GetMaxControlSize(w, h);
  GetMaxToolBarButtonSize(atbW, atbH);
  if (ToolBarState = tsFloating) or ForFloating then
  begin
    if Position in [daTop, daBottom] then
    begin
      Result := h + 4;
    end
    else
    begin
      w := 0;
      h := 0;
      GetMaxExternalControlSize(w, h);
      Result := Max(h, atbW);
      Result := Result + 4;
    end;
  end
  else
  begin
    if Position in [daTop, daBottom] then
    begin
      Result := h + 4;
    end
    else
    begin
      Result := w + 4;
    end;
  end;
  Result := Max(Result, DEFAULT_TOOLBARHEIGHT);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.GetMaxControlSize(var W, H: Integer);
var
  i: Integer;
begin
  for i := 0 to FATBControls.count - 1 do
  begin
    if not (TControl(FATBControls[i]) is TAdvToolBarSeparator) then
    begin
      W := Max( W, TControl(FATBControls[i]).Width);
      H := Max(H, TControl(FATBControls[i]).Height);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.GetMaxExternalControlSize(var W, H: Integer);
var
  i: Integer;
begin
  for i := 0 to FATBControls.count - 1 do
  begin
    if not (TControl(FATBControls[i]) is TAdvCustomToolBarControl) then
    begin
      W := Max( W, TControl(FATBControls[i]).Width);
      H := Max(H, TControl(FATBControls[i]).Height);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.GetMaxToolBarButtonSize(var W, H: Integer);
var
  i: Integer;
begin
  for i := 0 to FATBControls.count - 1 do
  begin
    if not (TControl(FATBControls[i]) is TAdvToolBarSeparator) and (TControl(FATBControls[i]) is TAdvCustomToolBarButton) then
    begin
      W := Max( W, TControl(FATBControls[i]).Width);
      H := Max(H, TControl(FATBControls[i]).Height);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetControlsPosition(UpdateMySize: boolean = true);
var
  i, j, x, mw, nmw, x1, y, y1, w, r: integer;
  dgs: TDragGripStyle;
begin
  if (csLoading in ComponentState) or (FUpdateCount > 0) or not Assigned(FATBControls) then
    Exit;
                                                                 // FF: Page.MoveToolBar
  if not AutoPositionControls and (ToolBarState = tsFixed) and ((Self.Parent = nil) or (Self.Parent is TAdvPage) or (Self.Parent is TCompactWindow) or not (Self.Parent is TAdvDockPanel)) then
    Exit;

  if (Parent is TAdvPage) and not AutoSize then
  begin
    x := 2;
    y := 2;

    //  Then set the controls position
    FInternalControlPositioning := true;
    for i := 0 to FATBControls.Count - 1 do
    begin
      if TControl(FATBControls[i]).Visible then
      begin
        if TControl(FATBControls[i]).Width > (self.Width - x - 2) then
        begin
          // find leftmost position!!
          nmw := 0;
          mw := 2;
          for j := 0 to i - 1 do
          begin
            if (TControl(FATBControls[j]).Height > TControl(FATBControls[i]).Height) then
              nmw := TControl(FATBControls[j]).Left + TControl(FATBControls[j]).Width;
            if nmw > mw then
              mw := nmw;  
          end;

          x := mw;
          y := y + TControl(FATBControls[i]).Height;
        end;

        TControl(FATBControls[i]).Left := x;
        TControl(FATBControls[i]).Top := y;

        x := x + TControl(FATBControls[i]).Width;
      end
      else
      begin
        TControl(FATBControls[i]).Top := Height + 2;
      end;
    end;
    FInternalControlPositioning := false;
    Exit;
  end;


  if (ToolBarState = tsFloating) then
  begin
    x := 2;
    y := 2 + CaptionHeight;

    if FFloatingRows = 1 then
    begin
      FInternalControlPositioning := true;
      for i := 0 to FATBControls.Count - 1 do
      begin
        if TControl(FATBControls[i]).Visible then
        begin
          TControl(FATBControls[i]).Left := x;
          TControl(FATBControls[i]).Top := y;
          x := x + TControl(FATBControls[i]).Width;
        end
        else
        begin
          TControl(FATBControls[i]).Top := Height + 2;
        end;
      end;
      FInternalControlPositioning := false;

      if UpdateMySize then
        UpdateSize;
    end
    else
    begin
      // first set the Size
      if UpdateMySize then
        UpdateSize;

      //  Then set the controls position
      FInternalControlPositioning := true;
      for i := 0 to FATBControls.Count - 1 do
      begin
        if TControl(FATBControls[i]).Visible then
        begin
          if TControl(FATBControls[i]).Width > (self.Width - x - 2) then
          begin
            x := 2;
            y := y + FSizeAtDock { + 2};
          end;
          TControl(FATBControls[i]).Left := x;
          TControl(FATBControls[i]).Top := y;
          x := x + TControl(FATBControls[i]).Width;
        end
        else
        begin
          TControl(FATBControls[i]).Top := Height + 2;
        end;
      end;
      FInternalControlPositioning := false;

    end;

  end
  else if Position in [daTop, daBottom] then
  begin
    dgs := FCurrentToolBarStyler.DragGripStyle;

    if (Parent is TAdvPage) or (Parent is TCompactWindow) then
      dgs := dsNone;

    if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
      x := DragGripWidth + 2
    else
      x := 2;

    if Self.ToolBarState in [tsDocked, tsFixed] then
    begin
      y := 2;
      if ShowCaption and (FCaptionPosition = cpTop) then
        y := y + CaptionHeight;
    end
    else
      y := 2 + CaptionHeight;

    if (Parent is TAdvPage) or (Parent is TCompactWindow) then
    begin
      y1 := y;
      x1 := x;
      w := 0;
      r := 1;
      FInternalControlPositioning := true;
      for i := 0 to FATBControls.Count - 1 do
      begin
        if TControl(FATBControls[i]).Visible or (csDesigning in ComponentState) then
        begin
          if (TControl(FATBControls[i]) is TAdvCustomGlowButton) then
          begin
            if (TProCustomglowButton(FATBControls[i]).ButtonSizeState = bsLarge) then
            begin
              TControl(FATBControls[i]).Left := x;
              TControl(FATBControls[i]).Top := y;
              x := x + TControl(FATBControls[i]).Width;
              r := 1;
              y1 := y;
              x1 := x;
              w := 0;
            end
            else
            begin
              TControl(FATBControls[i]).Left := x1;
              TControl(FATBControls[i]).Top := y1;
              //x := x + TControl(FATBControls[i]).Width;
              if (w < TControl(FATBControls[i]).Width) then
              begin
                x := x + (TControl(FATBControls[i]).Width - w);
                w := TControl(FATBControls[i]).Width;
              end;

              Inc(r);
              if (r > TOOLBAR_ROWS) then
              begin
                r := 1;
                y1 := y;
                x1 := x;
                w := 0;
              end
              else
              begin
                y1 := y1 + TControl(FATBControls[i]).Height;
              end;
            end;
          end
          else
          begin
            TControl(FATBControls[i]).Left := x;
            TControl(FATBControls[i]).Top := y;
            x := x + TControl(FATBControls[i]).Width;
            r := 1;
            y1 := y;
            x1 := x;
            w := 0;
          end;
        end
        else
        begin
          TControl(FATBControls[i]).Top := Height + 2;
        end;
      end;
      FInternalControlPositioning := false;
    end
    else
    begin
      FInternalControlPositioning := true;
      for i := 0 to FATBControls.Count - 1 do
      begin
        if TControl(FATBControls[i]).Visible or (csDesigning in ComponentState) then
        begin
          if (FLUHidedControls.IndexOf(FATBControls[i]) >= 0) then
          begin
            //TControl(FATBControls[i]).Left :=
            if TControl(FATBControls[i]).Parent = self then
              TControl(FATBControls[i]).Top := Height + 2;
          end
          else
          begin
            TControl(FATBControls[i]).Left := x;
            TControl(FATBControls[i]).Top := y;
            x := x + TControl(FATBControls[i]).Width;
          end;
        end
        else
        begin
          TControl(FATBControls[i]).Top := Height + 2;
        end;
      end;
      FInternalControlPositioning := false;
    end;  

    if UpdateMySize then
      UpdateSize;

    { // Check for Controls exceeding the boundries and hide them
    for i:=0 to ControlCount-1 do
    begin
      self.Controls[i].Left := x;
      self.Controls[i].Top := y;
      x:= x + self.Controls[i].Width;
    end;
    }
  end
  else // if Position in [daLeft, daRight] then
  begin

    if Self.ToolBarState in [tsDocked, tsFixed] then
    begin
      dgs := FCurrentToolBarStyler.DragGripStyle;

      if (Parent is TAdvPage) or (Parent is TCompactWindow) then
        dgs := dsNone;

      if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
        y := DragGripWidth + 2
      else
        y := 2;

      x := 2;
      if ShowCaption and (FCaptionPosition = cpTop) then
        x := x + CaptionHeight;

      FInternalControlPositioning := true;
      for i := 0 to FATBControls.Count - 1 do
      begin
        if TControl(FATBControls[i]).Visible or (csDesigning in ComponentState) then
        begin
          if (FLUHidedControls.IndexOf(FATBControls[i]) >= 0) then
          begin
            if TControl(FATBControls[i]).Parent = self then
              TControl(FATBControls[i]).Left := Width + 2;
            //TControl(FATBControls[i]).Top := Height + 2;
          end
          else
          begin
            TControl(FATBControls[i]).Left := x;//2;
            TControl(FATBControls[i]).Top := y;
            y := y + TControl(FATBControls[i]).Height;
          end;
        end
        else
        begin
          TControl(FATBControls[i]).Left := Width + 2;
        end;
      end;
      FInternalControlPositioning := false;

    end
    else // ToolBarState = tsFloating
    begin
      y := 2 + CaptionHeight;
      FInternalControlPositioning := true;
      for i := 0 to FATBControls.Count - 1 do
      begin
        if TControl(FATBControls[i]).Visible then
        begin
          TControl(FATBControls[i]).Left := 2;
          TControl(FATBControls[i]).Top := y;
          y := y + TControl(FATBControls[i]).Height;
        end;
      end;
      FInternalControlPositioning := false;
    end;

    if UpdateMySize then
      UpdateSize;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateSize;
var
  H, W, W1, i, j, MaxS, MaxCtrlS: integer;
  dgs: TDragGripStyle;
  OldV: Boolean;
begin
  if (FToolBarState = tsFloating) then
  begin
    Constraints.MinHeight := 0;
    Constraints.MaxHeight := 0;
    Constraints.MinWidth := 0;
    Constraints.MaxWidth := 0;
    if FFloatingRows = 1 then
    begin
      W := FMinLength;
      if FATBControls.Count > 0 then
      begin
        i := FATBControls.count - 1;
        while i >= 0 do
        begin
          if TControl(FATBControls[i]).visible then
            break;
          dec(i);
        end;

        if i >= 0 then
          W := TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width + 2;
      end;
      w := Max(w, FMinLength);
      self.Width := w;
      self.Height := FSizeAtDock + CaptionHeight;
    end
    else
    begin
      GetFloatingSizes(h, w);
      self.Width := w;
      self.Height := h;
    end;

    if Assigned(FFloatingWindow) and (FFloatingWindow.Visible) then
      FFloatingWindow.SetWindowSize;

  end
  else if Position in [daTop, daBottom] then
  begin
    if FullSize and false then
    begin
      if (FToolBarState = tsDocked) and Assigned(FCurrentDock) then
      begin
        //W:= FCurrentDock.Width;
        //Constraints.MaxWidth:= W;
        //Constraints.MinWidth:= W;
      end;
    end
    else
    begin
      W := FMinLength;
      if FATBControls.Count > 0 then
      begin
        i := FATBControls.count - 1;
        while i >= 0 do
        begin
          if (FLUHidedControls.IndexOf(FATBControls[i]) < 0) and TControl(FATBControls[i]).visible then
            break;
          dec(i);
        end;

        if i >= 0 then
        begin
          if (Parent is TAdvPage) or (Parent is TCompactWindow) then
          begin
            i := FATBControls.count - 1;
            j := 1;
            W1 := 0;
            while i >= 0 do
            begin
              if TControl(FATBControls[i]).visible then
              begin
                W1 := Max(W1, TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width);
                if (TControl(FATBControls[i]) is TAdvCustomGlowButton) and (TProCustomGlowButton(FATBControls[i]).ButtonSizeState in [bsLabel, bsGlyph]) then
                begin
                  Inc(j);
                  if (j > TOOLBAR_ROWS) then
                    break;
                end
                else
                  break;
              end;
              dec(i);
            end;

            if (W1 > 0) then
              W := W1;
          end
          else
            W := TControl(FATBControls[i {FATBControls.Count-1}]).Left + TControl(FATBControls[i {FATBControls.Count-1}]).Width;
        end
        else
          W := MIN_BUTTONSIZE;

        if ShowPopupIndicator {CustomizedOption} then
        begin
          if (FToolBarState = tsFloating) then
            W := W + 2
          else
            W := W + PopupIndicatorWidth;
        end;
      end;

      dgs := FCurrentToolBarStyler.DragGripStyle;

      if (Parent is TAdvPage) or (Parent is TCompactWindow) then
        dgs := dsNone;

      if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
        MaxS := DragGripWidth + 2
      else
        MaxS := 2;

      MaxCtrlS := DEFAULT_TOOLBARHEIGHT;
      for i := 0 to FATBControls.count - 1 do
      begin
        if TControl(FATBControls[i]).visible then
        begin
          MaxS := MaxS + TControl(FATBControls[i]).Width;
          if not (TControl(FATBControls[i]) is TAdvToolBarSeparator) then
            MaxCtrlS := Max(MaxCtrlS, TControl(FATBControls[i]).Height + 4);
        end;
      end;

      if ShowPopupIndicator then
        MaxS := MaxS + PopupIndicatorWidth;

      if (Parent is TAdvPage) or (Parent is TCompactWindow) then
        MaxS := W
      else
        MaxS := Max(MaxS, W);
      //FMaxLength:= W;
      FMaxLength := MaxS;

      if (FToolBarState = tsFloating) then
      begin
       { if FullSize then
        begin
          Constraints.MinHeight:= 0;
          Constraints.MaxHeight:= 0;

          Constraints.MinWidth:= 0;
          Constraints.MaxWidth:= W;
          Constraints.MinWidth:= W;
          Width:= W;
        end
        else
        begin
          Constraints.MinHeight:= 0;
          Constraints.MaxHeight:= 0;

          if Constraints.MinWidth > W then
            Constraints.MinWidth:= W;

          Constraints.MaxWidth:= W;

          Width:= W;
        end; }
      end
      else // tsDocked, tsFixed
      begin
        if FullSize then
        begin

        end
        else if FAutoSize then
        begin
          Constraints.MinHeight := 0;
          Constraints.MaxHeight := 0;

          Constraints.MinWidth := FMinLength;
          if Constraints.MinWidth > W then
            Constraints.MinWidth := W;

          if FDoCheckBoundChange and (Constraints.MaxWidth <> FMaxLength) and (Width > FMaxLength) and (Width <> W) then
            Width := W;
          //d:= W - Constraints.MaxWidth;
          Constraints.MaxWidth := FMaxLength; //W;

          // To Adjust size change, not to happened empty space with Shrunk ToolBar
          //Width:= Width + d;

          //Width:= W;  // TODO: remove this and uncomment above line
          //Height := FSizeAtDock;

          if W > Width then
          begin
            Width := W;
          end
          else if W < Width then
          begin
            if Width > FMaxLength then
            begin
              OldV := AllowBoundChange;
              AllowBoundChange := not FDoCheckBoundChange; // True
              Width := W;
              AllowBoundChange := OldV;
            end;
          end;

          if ShowCaption then
            MaxCtrlS := MaxCtrlS + CaptionHeight;
            
          if MaxCtrlS <> Height then
          begin
            Height := MaxCtrlS;
            //Height := FSizeAtDock;
          end;

        end;
      end;
    end;

  end
  else // if Position in [daLeft, daRight] then
  begin
    if FullSize then
    begin
      if (FToolBarState = tsDocked) and Assigned(FCurrentDock) then
      begin
        //H:= FCurrentDock.Height;
        //Constraints.MaxHeight:= H;
      end;
    end
    else
    begin
      H := FMinLength;
      if FATBControls.Count > 0 then
      begin
        i := FATBControls.count - 1;
        while i >= 0 do
        begin
          if (FLUHidedControls.IndexOf(FATBControls[i]) < 0) and TControl(FATBControls[i]).visible then
            break;
          dec(i);
        end;

        if i >= 0 then
          H := TControl(FATBControls[i {FATBControls.Count-1}]).Top + TControl(FATBControls[i {FATBControls.Count-1}]).Height
        else
          H := MIN_BUTTONSIZE;

        if ShowPopupIndicator {CustomizedOption} then
          H := H + PopupIndicatorWidth;
      end;

      dgs := FCurrentToolBarStyler.DragGripStyle;

      if (Parent is TAdvPage) or (Parent is TCompactWindow) then
        dgs := dsNone;

      if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
        MaxS := DragGripWidth + 2
      else
        MaxS := 2;

      MaxCtrlS := DEFAULT_TOOLBARHEIGHT;
      for i := 0 to FATBControls.count - 1 do
      begin
        if TControl(FATBControls[i]).visible then
        begin
          MaxS := MaxS + TControl(FATBControls[i]).Height;
          if not (TControl(FATBControls[i]) is TAdvToolBarSeparator) then
            MaxCtrlS := Max(MaxCtrlS, TControl(FATBControls[i]).Width + 4);
        end;
      end;

      if ShowPopupIndicator then
        MaxS := MaxS + PopupIndicatorWidth;

      MaxS := Max(MaxS, H);
      FMaxLength := MaxS;

      if FAutoSize then
      begin
        Constraints.MinWidth := 0;
        Constraints.MaxWidth := 0;

        Constraints.MinHeight := FMinLength;
        if Constraints.MinHeight > H then
          Constraints.MinHeight := H;
        Constraints.MaxHeight := FMaxLength;
        //FMaxLength:= H;


        //d:= W - Constraints.MaxWidth;

        // To Adjust size change, not to happened empty space with Shrunk ToolBar
        //Height:= Height + d;

        //Width := FSizeAtDock;
        //Height:= H;  // TODO: remove this and uncomment above line

        if H > Height then
        begin
          Height := H;
        end
        else if H < Height then
        begin
          if Height > FMaxLength then
            Height := H;
        end;

        if ShowCaption then
          MaxCtrlS := MaxCtrlS + CaptionHeight;

        if MaxCtrlS <> Width then
        begin
          Width := MaxCtrlS;
        end;
      end;

    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetImages(const Value: TCustomImageList);
var
  i: integer;
  OldImages: TCustomImageList;
begin
  if Value <> FImages then
  begin
    OldImages := FImages;
    FImages := Value;

    if Assigned(OldImages) then
    begin
      if Assigned(FImages) then
      begin
        if Position in [daTop, daBottom] then
          Height := Height + (FImages.Height - OldImages.Height)
        else
          Width := Width + (FImages.Width - OldImages.Width);
      end
      else
      begin
        if Position in [daTop, daBottom] then
          Height := Height - OldImages.Height
        else
          Width := Width - OldImages.Width;
      end;
    end;

    FInternalControlPositioning := True;
    for i := 0 to FATBControls.Count - 1 do
    begin
      if TControl(FATBControls[i]) is TAdvCustomToolBarControl then
        TAdvCustomToolBarControl(FAtbControls[i]).AdjustSize;
    end;
    FInternalControlPositioning := False;

    SetControlsPosition;

    if Assigned(OldImages) then
    begin
      for i := 0 to FATBControls.Count - 1 do
      begin
        if TControl(FATBControls[i]) is TAdvCustomToolBarControl then
          TAdvCustomToolBarControl(FAtbControls[i]).AdjustSize;
        if TControl(FATBControls[i]) is TAdvCustomToolBarButton then
          TAdvCustomToolBarButton(FAtbControls[i]).GenerateShade;
      end;
    end;

    if (ToolBarState = tsFloating) and not (csLoading in ComponentState) then
    begin
      FSizeAtDock := GetSizeAtDock(True);
      SetControlsPosition;
    end;

    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetMenu(const Value: TMainMenu);
var
  I, j: Integer;
begin
  if FMenu = Value then
    Exit;

  if csAcceptsControls in ControlStyle then
  begin
    ControlStyle := [csCaptureMouse, csClickEvents,
      csDoubleClicks, csMenuEvents, csSetCaption];
    RecreateWnd;
  end;

  //ShowCaptions := True;

  if Assigned(FMenu) then
    for I := FATBControls.Count - 1 downto 0 do
    begin
      if (TControl(FATBControls[I]) is TAdvToolBarMenuButton) and (TAdvToolBarMenuButton(FATBControls[I]).FToolBarCreated) then
        TAdvToolBarMenuButton(FATBControls[I]).Free;
    end;

  if Assigned(FMenu) then
  begin
    FMenu.RemoveFreeNotification(Self);
    //if (csDesigning in ComponentState) then
      //FMenu.OnChange:= nil;
  end;
  FMenu := Value;
  if not Assigned(FMenu) then exit;
  FMenu.FreeNotification(Self);

  if FMenu.Handle = 0 then
  begin
    { Do nothing just required to call GetHandle
      which internally calls InternalReThinkHotKeys. }
  end;

  if (csDesigning in ComponentState) then
    FMenu.OnChange:= OnMainMenuChange;

  if (csLoading in ComponentState) then
  begin
    if Assigned(FMenu.Images) then
      FImages := FMenu.Images;
  end
  else
    FImages := FMenu.Images;

  if (csDesigning in ComponentState) then
    FMenuImages := FMenu.Images;

  for I := 0 to FMenu.Items.Count - 1 do
  begin
    with TAdvToolBarMenuButton.Create(Self) do
    try
      Grouped := True;
      Parent := Self;
      ShowCaption := true;
      {Buttons[I].} MenuItem := FMenu.Items[I];
      FToolBarCreated := true;
      AutoSize := True;
    except
      Free;
      raise;
    end;
  end;

  {Copy attributes from each menu item}
  j := 0;
  for I := 0 to FATBControls.Count - 1 {FMenu.Items.Count - 1} do
  begin
    if (TControl(FATBControls[I]) is TAdvToolBarMenuButton) and (TAdvToolBarMenuButton(FATBControls[I]).FToolBarCreated) then
    begin
      TAdvToolBarMenuButton(FATBControls[I]).MenuItem := FMenu.Items[j];
      // Will Be replaced by AutoSize
      //TAdvToolBarMenuButton(FATBControls[I]).Width := Canvas.TextWidth(FMenu.Items[j].Caption) + 8;

      inc(j);
      if j >= FMenu.Items.Count then
        break;
    end;
  end;

{  FMenu := Value;
  if FMenu <> nil then
  begin
    FreeAllItems;
    AddAllMenuItems(FMenu);

     // TODO: here
    SetItemsPosition;
  end;
}
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMControlChange(var Message: TCMControlChange);
begin
  inherited;

  with Message do
  begin
    // FF: D2005
    if (Control is TOptionSelectorWindow) or (Control is TCompactWindow) then
      Exit;

    if not FInternalControlUpdation then
    begin
      if Inserting then
        InsertControl(Control)
      else
        RemoveControl(Control);
    end;
  end;

  if Message.Inserting and not (csLoading in ComponentState) then
  begin
    //CheckAndCreateControlItem(Message.Control)

  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMControlListChange(
  var Message: TCMControlListChange);
begin
  inherited;
  
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.FindButtonFromAccel(
  Accel: Word): TAdvCustomToolBarButton;
var
  I: Integer;
begin
  for I := 0 to FATBControls.Count - 1 do
    if TControl(FATBControls[I]) is TAdvCustomToolBarButton then
    begin
      Result := TAdvCustomToolBarButton(FATBControls[I]);
      if Result.Visible and Result.Enabled and IsAccel(Accel, Result.Caption) then
        Exit;
    end;
  Result := nil;

end;

procedure TAdvCustomToolBar.CMHintShow(var Msg: TCMHintShow);
begin
  inherited;

  if (ToolBarState = tsFloating) and ShowClose and ShowHint and (HintCloseButton <> '') then
  begin
    if PtInRect(FWCloseBtnRect, Msg.HintInfo.CursorPos) then
      Msg.HintInfo.HintStr := HintCloseButton;
  end;

  if (ToolBarState = tsFloating) and ShowOptionIndicator and ShowHint and (HintOptionButton <> '') then
  begin
    if PtInRect(FWCustomizedBtnRect, Msg.HintInfo.CursorPos) then
      Msg.HintInfo.HintStr := HintOptionButton;
  end;

  if (ToolBarState <> tsFloating) and ShowOptionIndicator and ShowHint and (HintOptionButton <> '') then
  begin
    if (PtOnPopupIndicator(Msg.HintInfo.CursorPos)) then
      Msg.HintInfo.HintStr := HintOptionButton;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMDialogChar(var Message: TCMDialogChar);
var
  Button: TAdvCustomToolBarButton;
begin
  if Enabled and Showing {and ShowCaptions} then
  begin
    Button := FindButtonFromAccel(Message.CharCode);
    if Button <> nil then
    begin
      { Display a drop-down menu after hitting the accelerator key if IE3
        is installed. Otherwise, fire the OnClick event for IE4. We do this
        because the IE4 version of the drop-down metaphor is more complete,
        allowing the user to click a button OR drop-down its menu. }
     { if ((Button.Style <> tbsDropDown) or (GetComCtlVersion < ComCtlVersionIE4)) and
        ((Button.DropdownMenu <> nil) or (Button.MenuItem <> nil)) then
        TrackMenu(Button)
      else
        Button.Click; }
      // FF: ShortCut not working with AdvToolBarButton  
      if Button.IsMenuButton and (Assigned(Button.DropDownMenu) or (Button.MenuItem <> nil)) then
        Button.DoDropDown
      else
        Button.Click;

      Message.Result := 1;
      Exit;
    end;
  end;
  inherited;

end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.AddAdvToolBarControl(
  aControl: TAdvCustomToolBarControl): integer;
begin
  Result := FATBControls.Count;
  InsertAdvToolBarControl(aControl, Result);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.InsertAdvToolBarControl(aControl: TAdvCustomToolBarControl; Index: integer);
begin
  if Index > FATBControls.Count then
    raise exception.Create('Invalid Index');

  if FATBControls.IndexOf(aControl) < 0 then
  begin
    FATBControls.Insert(Index, aControl);
    if aControl is TAdvCustomToolBarControl then
      TAdvCustomToolBarControl(aControl).FAdvToolBar := self;

    //FRUControls.Insert(0, aControl);

    SetControlsPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.RemoveAdvToolBarControl(
  aControl: TAdvCustomToolBarControl);
begin
  if FATBControls.IndexOf(aControl) >= 0 then
  begin
    FATBControls.Remove(aControl);

    //FRUControls.Remove(aControl));

    SetControlsPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.AdjustControl(Control: TControl);
var
  Pos: Integer;
begin
  Pos := FATBControls.IndexOf(Control);
  if Pos = -1 then Exit;
  if (csDesigning in ComponentState) or (csLoading in ComponentState) then
    ReorderControl(Pos, Control.Left, Control.Top);

  if not ((csDesigning in ComponentState) or (csLoading in ComponentState)) and
         (Self.ToolBarState = tsDocked) and Assigned(FCurrentDock) then
    FDoCheckBoundChange := True;

  SetControlsPosition;
  UpdateRULists;

  FDoCheckBoundChange := False;

  if not ((csDesigning in ComponentState) or (csLoading in ComponentState)) and
         (Self.ToolBarState = tsDocked) and Assigned(FCurrentDock) then
  begin
    if not AllowBoundChange then
    begin
      if (self.FRow >= 0) and (self.FRow < FCurrentDock.RowCount) then
        FCurrentDock.Rows[self.FRow].ArrangeToolBars;
    end;
  end;

  if not (csDesigning in ComponentState) and AutoOptionMenu then
  begin
    if Assigned(FOptionWindow) and FOptionWindow.Visible then
    begin
      InitializeOptionWindow;
    end;
  end;

end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.ControlIndex(OldIndex, ALeft,
  ATop: Integer): Integer;
begin
  if (OldIndex >= 0) and (FATBControls.Count <= 1) then
  begin
    Result := OldIndex;
    Exit;
  end;

  Result := FATBControls.Count;
  if (ALeft = 0) or (ATop = 0) then
    exit;

  if FATBControls.Count > 0 then
  begin
    for Result := 0 to FATBControls.Count - 1 do
    begin
      if Position in [daTop, daBottom] then
      begin
        if (Result <> OldIndex) and (ALeft <= TControl(FATBControls[Result]).Left) then
          Break;
      end
      else
      begin
        if (Result <> OldIndex) and (ATop <= TControl(FATBControls[Result]).Top) then
          Break;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.ReorderControl(OldIndex, ALeft,
  ATop: Integer): Integer;
var
  Control: TControl;
begin
  Result := ControlIndex(OldIndex, ALeft, ATop);
  if Result <> OldIndex then
  begin
    { If we are inserting to the right of our deletion then account for shift }
    if OldIndex < Result then Dec(Result);
    Control := FATBControls[OldIndex];
    FATBControls.Delete(OldIndex);
    FATBControls.Insert(Result, Control);
    //SetControlsPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.InsertControl(Control: TControl);
var
  FromIndex, ToIndex: Integer;
begin
  if Control is TAdvCustomToolBarControl then
  begin
    if (TAdvCustomToolBarControl(Control) is TAdvToolBarSeparator) and (Parent is TAdvPage) then
      TAdvToolBarSeparator(Control).AutoSize := False;
  
    TAdvCustomToolBarControl(Control).FAdvToolBar := Self;
    TAdvCustomToolBarControl(Control).Position := self.Position;
    if not (csLoading in ComponentState) and not (csDesigning in ComponentState) then // FF: Run time button size
      TAdvCustomToolBarControl(Control).AdjustSize;
  end;

  {$IFNDEF TMS_STD}
  if Assigned(FCurrentToolBarStyler) then
  begin
    if (Control is TAdvGlowButton) or (Control is TDBAdvGlowButton) or (Control is TAdvGlowMenuButton) then
      TAdvGlowButton(Control).Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
  end;
  {$ENDIF}

  if not (csDesigning in ComponentState) and (Parent <> nil) and (Parent is TAdvPage) and (Control is TAdvCustomGlowButton) then
  begin
    TProCustomGlowButton(Control).OnInternalKeyDown := OnGlowButtonKeyDown;
    TProCustomGlowButton(Control).OnSetButtonSize := OnSetGlowButtonSize;
    TProCustomGlowButton(Control).OnGetShortCutHintPos := OnGetGlowButtonShortCutHintPos;
  end;

  if not (csDesigning in ComponentState) and (Parent <> nil) and (Parent is TAdvDockPanel) and (Control is TAdvCustomGlowButton) then
  begin
    TProCustomGlowButton(Control).OnInternalClick := OnGlowButtonClick;
  end;

  if not (csLoading in Control.ComponentState) or true {ch1} then
  begin
    FromIndex := FATBControls.IndexOf(Control);
    if FromIndex >= 0 then
      {ToIndex := } ReorderControl(Fromindex, Control.Left, Control.Top)
    else
    begin
      ToIndex := ControlIndex(FromIndex, Control.Left, Control.Top);
      FATBControls.Insert(ToIndex, Control);
    end;
  end
  else
  begin
    {ToIndex := } FATBControls.Add(Control);
  end;

  if FAutoRUL then
    FRUControls.Add(Control);

  SetControlsPosition;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.RemoveControl(Control: TControl);
var
  I: Integer;
begin
  if (FATBControls = nil) then
    Exit;
    
  I := FATBControls.IndexOf(Control);
  if I >= 0 then
  begin
    if Control is TAdvCustomToolBarButton then TAdvCustomToolBarButton(Control).FAdvToolBar := nil;
    FATBControls.Remove(Control);

    if FAutoRUL then
    begin
      FRUControls.Remove(Control);
      FLUHidedControls.Remove(Control);
    end;

    SetControlsPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.AddMDIChildMenu(ChildForm: TCustomForm; Caption: string = '');
var
  ParntFrm: TCustomForm;
begin
  ParntFrm := GetMyParentForm;
  if (ParntFrm <> nil) and Assigned(TProForm(ParntFrm).WindowMenu) and Assigned(Menu) and (ChildForm <> nil) then
  begin
    if (Caption <> '') then
      FMDIChildMenuSL.AddObject(Caption, ChildForm)
    else
      FMDIChildMenuSL.AddObject(ChildForm.Caption, ChildForm);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.RemoveMDIChildMenu(ChildForm: TCustomForm; Caption: string = '');
var
  I: Integer;
  S: String;
begin
  if (ChildForm <> nil) then
  begin
    if (Caption <> '') then
      S := Caption
    else
      S := ChildForm.Caption;

    for I := 0 to FMDIChildMenuSL.Count-1 do
    begin
      if (UpperCase(S) = UpperCase(FMDIChildMenuSL[I])) and (FMDIChildMenuSL.Objects[I] = ChildForm) then
      begin
        FMDIChildMenuSL.Delete(I);
        Break;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.RemoveAllMDIChildMenu;
begin
  FMDIChildMenuSL.Clear;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnMDIChildMenuClick(Sender: TObject);
var
  ParntFrm: TCustomForm;
begin
  ParntFrm := GetMyParentForm;
  if (Sender is TMenuItem) and (TMenuItem(Sender).Tag >= 0) and (TMenuItem(Sender).Tag < FMDIChildMenuSL.Count)
    and (ParntFrm <> nil) then
  begin
    TProForm(FMDIChildMenuSL.Objects[TMenuItem(Sender).Tag]).SetFocus;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.CheckMenuDropdown(
  Button: TAdvCustomToolBarButton): Boolean;
var
  Hook: Boolean;
  Menu: TMenu;
  Item: TMenuItem;
  I: Integer;
  ParentMenu: TMenu;
  APoint: TPoint;

  MenuWidth, j, k: Integer;
  MeasureItemStruct: TMeasureItemStruct;
  PrntFrm: TCustomForm;
  HasWindowMenu: Boolean;

  function HasWindowMenuInChildren(AMenuItem: TMenuItem): Boolean;
  var
    I: Integer;
  begin
    Result := False;
    if (PrntFrm <> nil) and Assigned(TProForm(PrntFrm).WindowMenu) then
    begin
      if (TProForm(PrntFrm).WindowMenu = AMenuItem) then
        Result := True
      else
      begin
        for I:= 0 to AMenuItem.Count-1 do
        begin
          Result := HasWindowMenuInChildren(AMenuItem.Items[I]);
          if Result then
            Break;
        end;
      end;
    end;
  end;

  procedure CheckAndAddMDIChildMenu;
  var
    i: Integer;
    AItem: TMenuItem;
  begin
    PrntFrm := GetMyParentForm;
    HasWindowMenu := False;
    if (PrntFrm <> nil) and Assigned(TProForm(PrntFrm).WindowMenu) and (FButtonMenu <> nil) then
    begin
      if (TProForm(PrntFrm).WindowMenu = FButtonMenu) then
        HasWindowMenu := True
      else
        HasWindowMenu := HasWindowMenuInChildren(FButtonMenu);

      if HasWindowMenu then
      begin
        for i:= 0 to FMDIChildMenuSL.Count -1 do
        begin
          AItem := TMenuItem.Create(self);
          AItem.Caption := FMDIChildMenuSL[I];
          AItem.Tag := I;
          AItem.OnClick := OnMDIChildMenuClick;
          AItem.RadioItem := True;
          if (FMDIChildMenuSL.Objects[I] <> nil) and (TProForm(PrntFrm).ActiveMDIChild = FMDIChildMenuSL.Objects[I]) then
            AItem.Checked := True
          else
            AItem.Checked := False;  
          TProForm(PrntFrm).WindowMenu.Add(AItem);
          FMDIChildMenuList.Add(AItem)
        end;
      end;
    end;
  end;

begin
  Result := False;
  if Button = nil then Exit;
  
  FCaptureChangeCancels := False;
  try
    if Button.DropdownMenu <> nil then
      FTempMenu := Button.DropdownMenu
    else if Button.MenuItem <> nil then
    begin
      Button.MenuItem.Click;
      ClearTempMenu;
      FTempMenu := TAdvPopupMenu.Create(Self);
      ParentMenu := Button.MenuItem.GetParentMenu;
      if ParentMenu <> nil then
        FTempMenu.BiDiMode := ParentMenu.BiDiMode;
      FTempMenu.HelpContext := Button.MenuItem.HelpContext;
      FTempMenu.TrackButton := tbLeftButton;
      Menu := Button.MenuItem.GetParentMenu;
      if Menu <> nil then
      begin
        FTempMenu.AutoHotkeys := Menu.AutoHotkeys;
        FTempMenu.Images := Menu.Images;
        if (Menu is TAdvMainMenu) then
          FTempMenu.DisabledImages := (Menu as TAdvMainMenu).DisabledImages;
      end;
      FButtonMenu := Button.MenuItem;

      CheckAndAddMDIChildMenu;

      for I := FButtonMenu.Count - 1 downto 0 do
      begin
        Item := FButtonMenu.Items[I];
        FButtonMenu.Delete(I);
        FTempMenu.Items.Insert(0, Item);
      end;
    end
    else
      Exit;
    SendCancelMode(nil);
    FTempMenu.PopupComponent := Self;
    Hook := Button.Grouped or true {(Button.MenuItem <> nil)};
    Hook := Hook and (FTempMenu.Items.Count > 0) and Assigned(Self.Menu);
    if Hook then
    begin
      MenuButtonIndex := Button.Index;
      MenuToolBar := Self;
      InitToolMenuHooks;
    end;
    //Perform(TB_SETHOTITEM, -1, 0);
    SetButtonHot(-1);
    try
      //---------
      // correct popup point coordinates
      MenuWidth := 0;
      j := 0;
      for k := 0 to FTempMenu.Items.Count - 1 do
      begin
        if MenuWidth < (Canvas.TextWidth(FTempMenu.Items[k].Caption) + Canvas.TextWidth(ShortCutToText(FTempMenu.Items[k].shortcut)) ) then
        begin
          MenuWidth := Canvas.TextWidth(FTempMenu.Items[k].Caption) + Canvas.TextWidth(ShortCutToText(FTempMenu.Items[k].shortcut));
          j := k;
        end;
      end;

      if FTempMenu.Items.Count > 0 then
      begin
        with MeasureItemStruct do
        begin
          CtlType := ODT_MENU;
          itemID := FTempMenu.Items[j].Command;
          itemWidth := 10;
          itemHeight := 10;
        end;
        SendMessage(PopupList.Window, WM_MEASUREITEM, 0, lParam(@MeasureItemStruct));
        MenuWidth := MeasureItemStruct.itemWidth; //+ TriangleSize;
      end;
      //LeftSide := (0{X} - TriangleSize - MenuWidth < 0);
      //RightSide := (0{X} + TriangleSize * 2 + MenuWidth >= Screen.Width);
     {
      if (Alignment = paRight) and not LeftSide then
        Inc(X, TriangleSize)
      else if (Alignment = paLeft) and RightSide then
        Inc(X, TriangleSize)
      else if Alignment = paCenter then
        Inc(X, TriangleSize div 2);
      if X >= Screen.Width then
        X := Screen.Width - 1;
      }

      //---------
      if Position in [daTop, daBottom] then
      begin
        if Position = daTop then
        begin
          APoint := Button.ClientToScreen(Point(0, Button.ClientHeight));
          if FTempMenu.IsRightToLeft then Inc(APoint.X, Button.Width);
          FMenuDropped := True;
          if (GetSystemMetrics(SM_CYMENU) * FTempMenu.Items.Count) + APoint.Y + 10 >
          {$IFDEF DELPHI6_LVL}
            Screen.MonitorFromPoint(APoint).Height then
          {$ELSE}
            Screen.Height then
          {$ENDIF}
            //Dec(APoint.Y, Button.Height);
            Dec(APoint.Y, (GetSystemMetrics(SM_CYMENU) * FTempMenu.Items.Count) + Button.Height + 4);

          //---- FF: Menu border pos iss  
          if MenuWidth + APoint.X + 52 >
          {$IFDEF DELPHI6_LVL}
             Screen.MonitorFromPoint(APoint).BoundsRect.Right then
            Dec(APoint.X, (MenuWidth + APoint.X + 52)  - Screen.MonitorFromPoint(APoint).BoundsRect.Right);
          {$ELSE}
             Screen.Width then
            Dec(APoint.X, (MenuWidth + APoint.X + 52)  - Screen.Width);
          {$ENDIF}
            //APoint.X := APoint.X + Button.Width - MenuWidth;
        end
        else // daBottom
        begin
          APoint := Button.ClientToScreen(Point(0, Button.ClientHeight));
          if FTempMenu.IsRightToLeft then
            Inc(APoint.X, Button.Width);
          FMenuDropped := True;
          if (GetSystemMetrics(SM_CYMENU) * FTempMenu.Items.Count) + APoint.Y + 10 >
          {$IFDEF DELPHI6_LVL}
            Screen.MonitorFromPoint(APoint).Height then
          {$ELSE}
            Screen.Height then
          {$ENDIF}
          begin
            //Dec(APoint.Y, Button.Height);
            Dec(APoint.Y, (GetSystemMetrics(SM_CYMENU) * FTempMenu.Items.Count) + Button.Height + 4);
          end;

          //---- FF: Menu border pos iss
          if MenuWidth + APoint.X + 52 >
          {$IFDEF DELPHI6_LVL}
             Screen.MonitorFromPoint(APoint).BoundsRect.Right then
            Dec(APoint.X, (MenuWidth + APoint.X + 52)  - Screen.MonitorFromPoint(APoint).BoundsRect.Right);
          {$ELSE}
             Screen.Width then
            Dec(APoint.X, (MenuWidth + APoint.X + 52)  - Screen.Width);
          {$ENDIF}
        end;
      end
      else // daLeft, daRight then
      begin
        if Position = daLeft then
        begin
          APoint := Button.ClientToScreen(Point(Button.ClientWidth, 1));
          //if FTempMenu.IsRightToLeft then Inc(APoint.X, Button.Width);
          FMenuDropped := True;
          {if MenuWidth + APoint.X + 30 >
             Screen.MonitorFromPoint(APoint).Width then
            Dec(APoint.X, MenuWidth+Button.Width+4);
          }
          {if (GetSystemMetrics(SM_CYMENU) * FTempMenu.Items.Count) + APoint.Y >
             Screen.MonitorFromPoint(APoint).Height then
            Dec(APoint.Y, Button.Height); }
        end
        else // daRight
        begin
          APoint := Button.ClientToScreen(Point(0, 1));
          APoint.X := APoint.X - MenuWidth;

         { LeftSide := (APoint.X - TriangleSize - MenuWidth < 0);
          RightSide := (APoint.X + TriangleSize * 2 + MenuWidth >= Screen.Width);

          if (FTempMenu.Alignment = paRight) and not LeftSide then
            Inc(APoint.X, TriangleSize)
          else if (FTempMenu.Alignment = paLeft) and RightSide then
            Inc(APoint.X, TriangleSize)
          else if FTempMenu.Alignment = paCenter then
            Inc(APoint.X, TriangleSize div 2);
          if APoint.X >= Screen.Width then
            APoint.X := Screen.Width - 1;
          }
          //if FTempMenu.IsRightToLeft then Inc(APoint.X, Button.Width);
          FMenuDropped := True;
          {if (GetSystemMetrics(SM_CYMENU) * FTempMenu.Items.Count) + APoint.Y >
             Screen.MonitorFromPoint(APoint).Height then
            Dec(APoint.Y, Button.Height); }
        end;
      end;
      //if GetComCtlVersion = ComCtlVersionIE5 then
        //Button.Invalidate;
      if FTempMenu is TAdvPopupMenu then
        TAdvPopupMenu(FTempMenu).MenuStyler := FCurrentToolBarStyler.CurrentAdvMenuStyler;

      if Hook or ((FTempMenu.Items.Count > 0) and not Assigned(Self.Menu))then
      begin
        Button.FMenuDisplayed := True;
        FTempMenu.Popup(APoint.X, APoint.Y);
        FLastMenuButton := Button;
      end;
    finally
      if Hook then ReleaseToolMenuHooks;
    end;
    FMenuButton := Button;
    Button.OnDropDownHide;
    if StillModal and FMenuFocused then
      SetButtonHot(Button);
      //Perform(TB_SETHOTITEM, Button.Index, 0);
    Result := True;
    UpControlInRUL(Button);
  finally
    PostMessage(Handle, CN_DROPDOWNCLOSED, 0, 0);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CancelMenu;
begin
  if FInMenuLoop then
  begin

    ReleaseToolMenuKeyHooks;
    MouseCapture := False;
    FMenuFocused := False;
    Perform(TB_SETANCHORHIGHLIGHT, 0, 0);
  end;
  FInMenuLoop := False;
  FCaptureChangeCancels := False;
  SetButtonHot(-1);
  //Perform(TB_SETHOTITEM, -1, 0);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MenuItemTimerOnTime(Sender: TObject);
begin
  if (FNextMenuHotButton <> nil) then
  begin
    TrackMenu(nil);
    SetButtonHot(FNextMenuHotButton);
    FNextMenuHotButton := nil;
  end;
  FMenuItemTimer.Enabled := False;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.ClickButton(Button: TAdvCustomToolBarButton; RealClick: Boolean = false);
var
  P: TPoint;
begin
  FCaptureChangeCancels := False;
  P := Button.ClientToScreen(Point(0, 0));
  FLastMenuButton := nil;
  Button.FInternalClick := True;
  if not RealClick then
  begin
    //PostMessage(Handle, WM_LBUTTONDOWN, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(P))))
    if Assigned(Button.MenuItem) and (Button.MenuItem.Count > 0) then
      PostMessage(Handle, WM_LBUTTONDOWN, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(P))))
    else
    begin
     { keybd_event( VK_ESCAPE, Mapvirtualkey( VK_ESCAPE, 0 ), 0, 0);
      keybd_event( VK_ESCAPE, Mapvirtualkey( VK_ESCAPE, 0 ), KEYEVENTF_KEYUP, 0);}
      if Position in [daTop, daBottom] then
        P := Point(P.X, P.Y-1)
      else
        P := Point(P.X-1, P.Y);

      PostMessage(Handle, WM_LBUTTONDOWN, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(P))));
      PostMessage(Handle, WM_LBUTTONUP, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(P))));

      FNextMenuHotButton := Button;
      FMenuItemTimer.Enabled := True;
      //Button.DoDropDown;
    end;
  end
  else
  begin
    mouse_event( MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 );
    {$IFNDEF DELPHI2006_LVL}
    mouse_event( MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 );
    {$ENDIF}
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CNDropDownClosed(var Message: TMessage);
var
  aButton: TAdvCustomToolBarButton;
  P: TPoint;
  MouseOverButton: Boolean;
begin
  aButton := FLastMenuButton; //FMenuButton;
  ClearTempMenu;
  if Assigned(aButton) and Assigned(Parent) and Assigned(Menu) and not aButton.FInternalClick then
  begin
    GetCursorPos(P);
    MouseOverButton := (FindDragTarget(P, True) = aButton);
    if MouseOverButton then
    begin
      P := aButton.ClientToScreen(Point(1, 1));
      aButton.FMenuBeingClosed := True;
      PostMessage(Parent.Handle, WM_LBUTTONUP, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(P))));
    end;
    //PostMessage(Parent.Handle, WM_LBUTTONDOWN, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(P))));
    //PostMessage(Parent.Handle, WM_LBUTTONUP, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(P))));
    //aButton.Perform(WM_LBUTTONUP, 0, 0);
  end;
  //if not (GetKeyState(VK_LBUTTON) < 0) then  //GetAsyncKeyState
  FMenuDropped := False;
  if Assigned(aButton) then
    aButton.FMenuDisplayed := False;
  if {(GetComCtlVersion = ComCtlVersionIE5) and }(FMenuButton <> nil)
    then FMenuButton.Invalidate;
  FCaptureChangeCancels := True;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.ClearTempMenu;
var
  I: Integer;
  Item: TMenuItem;
  PrntFrm: TCustomForm;
begin
  if (FButtonMenu <> nil) and (FMenuButton <> nil) and
    (FMenuButton.MenuItem <> nil) and (FTempMenu <> nil) then
  begin
    for I := FTempMenu.Items.Count - 1 downto 0 do
    begin
      Item := FTempMenu.Items[I];
      FTempMenu.Items.Delete(I);
      FButtonMenu.Insert(0, Item);
    end;
    FTempMenu.Free;
    FTempMenu := nil;
    FMenuButton := nil;
    FButtonMenu := nil;

    PrntFrm := GetMyParentForm;
    if (PrntFrm <> nil) and Assigned(TProForm(PrntFrm).WindowMenu) then
    begin
      for i:= TProForm(PrntFrm).WindowMenu.Count-1 downto 0 do
      begin
        if (FMDIChildMenuList.IndexOf(TProForm(PrntFrm).WindowMenu.Items[i]) >= 0) then
          TProForm(PrntFrm).WindowMenu.Items[i].Free;
      end;
      FMDIChildMenuList.Clear;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAutoRUL(const Value: Boolean);
begin
  FAutoRUL := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UnHideAllControls;
var
  i: Integer;
  OldV, OldV2: Boolean;
begin
  OldV := FInternalControlUpdation;
  FInternalControlUpdation := True;
  OldV2 := FUpdatingControls;
  FUpdatingControls := True;
  for i := 0 to FLUHidedControls.Count-1 do
  begin
    if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and (TControl(FLUHidedControls[i]).Parent <> self) then
    begin
      TControl(FLUHidedControls[i]).Parent := self;
    end;
  end;
  FInternalControlUpdation := OldV;
  FUpdatingControls := OldV2;
  FLUHidedControls.Clear;  
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpControlInRUL(aControl: TControl);
var
  i, k, l, UHS, sl, sr: integer;
  OldValue, FoundVC, OldV2: Boolean;
  aSeparator: TControl;
begin
  if FATBControls.IndexOf(aControl) >= 0 then
  begin
    if FAutoArrangeButtons then
    begin
      i := FRUControls.IndexOf(aControl);
      if (i >= 0) then
        FRUControls.Move(i, 0);

      i := FLUHidedControls.IndexOf(aControl);
      if (i >= 0) then
      begin

        // Search for Separator to Unhide
        if not (aControl is TAdvToolBarSeparator) then
        begin
          UHS := -1;
          k := FATBControls.IndexOf(FLUHidedControls[i]);
          if k >= 0 then
          begin
            FoundVC := false;
            sl := -1;
            sr := -1;

            for l := k - 1 downto 0 do
            begin
              if TControl(FATBControls[l]) is TAdvToolBarSeparator then
              begin
                sl := l;
                break;
              end;

              if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
              begin
                FoundVC := true;
                break;
              end;
            end;

            if not FoundVC then
            begin
              for l := k + 1 to FATBControls.Count - 1 do
              begin
                if TControl(FATBControls[l]) is TAdvToolBarSeparator then
                begin
                  sr := l;
                  break;
                end;

                if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                begin
                  FoundVC := true;
                  break;
                end;
              end;
            end;

            if not FoundVC then
            begin // Select Separator
              if (sl >= 0) and (FLUHidedControls.IndexOf(FATBControls[sl]) >= 0) and (TControl(FATBControls[sl]) is TAdvToolBarSeparator) then
              begin
                UHS := sl;
              end
              else if (sr >= 0) and (FLUHidedControls.IndexOf(FATBControls[sr]) >= 0) and (TControl(FATBControls[sr]) is TAdvToolBarSeparator) then
              begin
                UHS := sr;
              end;
            end;

          end;

          // Unhide here
          if UHS >= 0 then
          begin
            aSeparator := TControl(FATBControls[UHS]);
            if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and (aSeparator.Parent <> self) then
            begin
              OldValue := FInternalControlUpdation;
              FInternalControlUpdation := True;
              OldV2 := FUpdatingControls;
              FUpdatingControls := True;
              aSeparator.Parent := self;
              FInternalControlUpdation := OldValue;
              FUpdatingControls := OldV2;
            end;

           l := FLUHidedControls.IndexOf(aSeparator);
           if (l >= 0) then
              FLUHidedControls.Delete(l);
          end;

        end;

        i := FLUHidedControls.IndexOf(aControl);
        if (i >= 0) then
          FLUHidedControls.Delete(i);
      end;

      if aControl.Parent <> self then
      begin
        OldValue := FInternalControlUpdation;
        FInternalControlUpdation := True;
        OldV2 := FUpdatingControls;
        FUpdatingControls := True;
        aControl.Parent := self;
        FInternalControlUpdation := OldValue;
        FUpdatingControls := OldV2;
      end;
    end;

    if Assigned(FOptionWindow) then
    begin
      if FOptionWindow.Visible then
      begin
        HideOptionWindow;
        //UpdateRULists;
      end;
    end;
    UpdateRULists;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateRULists;
var
  i, j, k, l, sl, sr, df, UHS: integer;
  FoundVC, OldV, OldV2: Boolean;
  aControl: TControl;
  dgs: TDragGripStyle;
  
begin
  if (ToolBarState <> tsDocked) or not Assigned(FATBControls) or not Assigned(FRUControls) or not Assigned(FLUHidedControls) then
    Exit;

  if FUpdatingControls then   // FF: Index Out of Bound
    Exit;

  if FullSize then
  begin
    //FLUHidedControls.clear;
    UnHideAllControls;
    Exit;
  end;
  //---------- Hiding newly inserted control if its separator already hided
  i := FATBControls.Count - 1;
  while (i >= 0) do
  begin
    if (FLUHidedControls.IndexOf(FATBControls[i]) < 0) and TControl(FATBControls[i]).Visible and not (TControl(FATBControls[i]) is TAdvToolBarSeparator) then
      Break;
    Dec(i);
  end;
  for j:= i-1 downto 0 do
  begin
    if (TControl(FATBControls[j]) is TAdvToolBarSeparator) then
    begin
      if (FLUHidedControls.IndexOf(FATBControls[j]) >= 0) then
        FLUHidedControls.Add(FATBControls[i]);
      Break;
    end;
  end;
  //----------

  i := FATBControls.Count - 1;
  while (i >= 0) do
  begin
    if (FLUHidedControls.IndexOf(FATBControls[i]) < 0) and TControl(FATBControls[i]).Visible then
      Break;
    Dec(i);
  end;

  // found rightmost visible control

  if (i >= 0) then
  begin
    if Position in [daTop, daBottom] then
    begin
      if (TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width) >= (Width - PopupIndicatorWidth) then
      begin // Hide Controls
        df := (TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width) - (Width - PopupIndicatorWidth);
        while df > 0 do
        begin
          j := FRUControls.Count - 1;
          while j >= 0 do
          begin                                                                                                           // FF: btn Loading pos issue
            if (FLUHidedControls.IndexOf(FRUControls[j]) < 0) and not (TControl(FRUControls[j]) is TAdvToolBarSeparator) and TControl(FRUControls[j]).Visible then
              Break;
            dec(j);
          end;

          if j >= 0 then
          begin
            FLUHidedControls.Add(FRUControls[j]);
            Dec(df, TControl(FRUControls[j]).Width);

            // Search for Separator to hide
            k := FATBControls.IndexOf(FRUControls[j]);
            if k >= 0 then
            begin
              FoundVC := false;
              sl := -1;
              sr := -1;

              for l := k - 1 downto 0 do
              begin
                if (TControl(FATBControls[l]) is TAdvToolBarSeparator) and (FLUHidedControls.IndexOf(FATBControls[l]) < 0) then
                begin
                  sl := l;
                  break;
                end;

                if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                begin
                  FoundVC := true;
                  break;
                end;
              end;

              if not FoundVC then
              begin
                for l := k + 1 to FATBControls.Count - 1 do
                begin
                  if (TControl(FATBControls[l]) is TAdvToolBarSeparator) and (FLUHidedControls.IndexOf(FATBControls[l]) < 0) then
                  begin
                    sr := l;
                    break;
                  end;

                  if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                  begin
                    FoundVC := true;
                    break;
                  end;
                end;
              end;

              if not FoundVC then
              begin // Hide Separator
                if (sl >= 0) and (TControl(FATBControls[sl]) is TAdvToolBarSeparator) then
                begin
                  FLUHidedControls.Add(FATBControls[sl]);
                  dec(df, TControl(FATBControls[sl]).Width);
                end
                else if (sr >= 0) and (TControl(FATBControls[sr]) is TAdvToolBarSeparator) then
                begin
                  FLUHidedControls.Add(FATBControls[sr]);
                  dec(df, TControl(FATBControls[sr]).Width);
                end;
              end;

            end;

          end
          else
            break;
        end;
      end
      else
      if (FLUHidedControls.Count > 0) and ((TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width) < (Width - PopupIndicatorWidth)) then
      begin // UnHide Controls
        df := ((TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width) - (Width - PopupIndicatorWidth));
        while df < 0 do
        begin {(TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width + }

          j := FLUHidedControls.Count - 1;
          while j >= 0 do
          begin
            if not (TControl(FLUHidedControls[j]) is TAdvToolBarSeparator) then
            begin
              if (TControl(FLUHidedControls[j]).width <= abs(df)) then
              begin
                UHS := -1;
                // Search for Separator to Unhide
                k := FATBControls.IndexOf(FLUHidedControls[j]);
                if k >= 0 then
                begin
                  FoundVC := false;
                  sl := -1;
                  sr := -1;

                  for l := k - 1 downto 0 do
                  begin
                    if TControl(FATBControls[l]) is TAdvToolBarSeparator then
                    begin
                      sl := l;
                      break;
                    end;

                    if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                    begin
                      FoundVC := true;
                      break;
                    end;
                  end;

                  if not FoundVC then
                  begin
                    for l := k + 1 to FATBControls.Count - 1 do
                    begin
                      if TControl(FATBControls[l]) is TAdvToolBarSeparator then
                      begin
                        sr := l;
                        break;
                      end;

                      if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                      begin
                        FoundVC := true;
                        break;
                      end;
                    end;
                  end;

                  if not FoundVC then
                  begin // Select Separator
                    if (sl >= 0) and (FLUHidedControls.IndexOf(FATBControls[sl]) >= 0) and (TControl(FATBControls[sl]) is TAdvToolBarSeparator) then
                    begin
                      UHS := sl;
                    end
                    else if (sr >= 0) and (FLUHidedControls.IndexOf(FATBControls[sr]) >= 0) and (TControl(FATBControls[sr]) is TAdvToolBarSeparator) then
                    begin
                      UHS := sr;
                    end;
                  end;

                end;

                // Unhide here
                if UHS >= 0 then
                begin
                  if (TControl(FLUHidedControls[j]).Width + (TControl(FATBControls[UHS]).Width) <= abs(df)) then
                  begin
                    aControl := TControl(FATBControls[UHS]);
                    if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and (TControl(FLUHidedControls[j]).Parent <> self) then
                    begin
                      OldV := FInternalControlUpdation;
                      FInternalControlUpdation := True;
                      OldV2 := FUpdatingControls;
                      FUpdatingControls := True;
                      TControl(FLUHidedControls[j]).Parent := self;
                      FInternalControlUpdation := OldV;
                      FUpdatingControls := OldV2;
                    end;

                    Inc(df, TControl(FLUHidedControls[j]).Width);
                    FLUHidedControls.Delete(j);

                    l := FLUHidedControls.IndexOf(aControl{FATBControls[UHS]});
                    if l >= 0 then
                    begin
                      if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and (aControl.Parent <> self) then
                      begin
                        OldV := FInternalControlUpdation;
                        FInternalControlUpdation := True;
                        OldV2 := FUpdatingControls;
                        FUpdatingControls := True;
                        aControl.Parent := self;
                        FInternalControlUpdation := OldV;
                        FUpdatingControls := OldV2;
                      end;

                      inc(df, TControl(FLUHidedControls[l]).width);
                      FLUHidedControls.Delete(l);
                    end;
                  end
                  else // no more search
                  begin
                    j := FLUHidedControls.Count - 1;
                    Break;
                  end;
                end
                else
                begin

                  if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and
                    (TControl(FLUHidedControls[j]).Parent <> self) then
                  begin
                    OldV := FInternalControlUpdation;
                    FInternalControlUpdation := True;
                    OldV2 := FUpdatingControls;
                    FUpdatingControls := True;
                    TControl(FLUHidedControls[j]).Parent := self;
                    FInternalControlUpdation := OldV;
                    FUpdatingControls := OldV2;
                  end;

                  if (j < FLUHidedControls.Count) then
                  begin
                    inc(df, TControl(FLUHidedControls[j]).Width);
                    FLUHidedControls.Delete(j);
                  end;
                end;

                break;
              end
              else
              begin
                j := FLUHidedControls.Count - 1;
                break;
              end;
            end;

            dec(j);
          end;

          if (j = FLUHidedControls.Count - 1) then
            Break;

          FoundVC := False;
          for k:= 0 to FLUHidedControls.Count - 1 do
            if not (TControl(FLUHidedControls[k]) is TAdvToolBarSeparator) then
              FoundVC := True;
          if not FoundVC then
            Break;
            
          (*
          if TControl(FLUHidedControls[j]).width{)} <= abs(df){(Width - PopupIndicatorWidth)} then
          begin
            inc(df, TControl(FLUHidedControls[j]).width);
            FLUHidedControls.Delete(j);
          end
          else
            break;
          *)
        end;
      end;

    end
    else // daLeft, daRight
    begin
      if (TControl(FATBControls[i]).Top + TControl(FATBControls[i]).Height) >= (Height - PopupIndicatorWidth) then
      begin // Hide Controls
        df := (TControl(FATBControls[i]).Top + TControl(FATBControls[i]).Height) - (Height - PopupIndicatorWidth);
        while df > 0 do
        begin
          j := FRUControls.Count - 1;
          while j >= 0 do
          begin                                                                                                          // FF: btn Loading pos issue
            if (FLUHidedControls.IndexOf(FRUControls[j]) < 0) and not (TControl(FRUControls[j]) is TAdvToolBarSeparator) and TControl(FRUControls[j]).Visible then
              break;
            dec(j);
          end;

          if j >= 0 then
          begin
            FLUHidedControls.Add(FRUControls[j]);
            dec(df, TControl(FRUControls[j]).Height);

            // Search for Separator to hide
            k := FATBControls.IndexOf(FRUControls[j]);
            if k >= 0 then
            begin
              FoundVC := false;
              sl := -1;
              sr := -1;

              for l := k - 1 downto 0 do
              begin
                if (TControl(FATBControls[l]) is TAdvToolBarSeparator) and (FLUHidedControls.IndexOf(FATBControls[l]) < 0) then
                begin
                  sl := l;
                  break;
                end;

                if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                begin
                  FoundVC := true;
                  break;
                end;
              end;

              if not FoundVC then
              begin
                for l := k + 1 to FATBControls.Count - 1 do
                begin
                  if (TControl(FATBControls[l]) is TAdvToolBarSeparator) and (FLUHidedControls.IndexOf(FATBControls[l]) < 0) then
                  begin
                    sr := l;
                    break;
                  end;

                  if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                  begin
                    FoundVC := true;
                    break;
                  end;
                end;
              end;

              if not FoundVC then
              begin // Hide Separator
                if (sl >= 0) and (TControl(FATBControls[sl]) is TAdvToolBarSeparator) then
                begin
                  FLUHidedControls.Add(FATBControls[sl]);
                  dec(df, TControl(FATBControls[sl]).Height);
                end
                else if (sr >= 0) and (TControl(FATBControls[sr]) is TAdvToolBarSeparator) then
                begin
                  FLUHidedControls.Add(FATBControls[sr]);
                  dec(df, TControl(FATBControls[sr]).Height);
                end;
              end;

            end;

          end
          else
            break;
        end;
      end
      else if (FLUHidedControls.Count > 0) and ((TControl(FATBControls[i]).Top + TControl(FATBControls[i]).Height) < (Height - PopupIndicatorWidth)) then
      begin // UnHide Controls
        df := ((TControl(FATBControls[i]).Top + TControl(FATBControls[i]).Height) - (Height - PopupIndicatorWidth));
        while df < 0 do
        begin

          j := FLUHidedControls.Count - 1;
          while j >= 0 do
          begin
            if not (TControl(FLUHidedControls[j]) is TAdvToolBarSeparator) then
            begin
              if (TControl(FLUHidedControls[j]).Height <= abs(df)) then
              begin
                UHS := -1;
                // Search for Separator to Unhide
                k := FATBControls.IndexOf(FLUHidedControls[j]);
                if k >= 0 then
                begin
                  FoundVC := false;
                  sl := -1;
                  sr := -1;

                  for l := k - 1 downto 0 do
                  begin
                    if TControl(FATBControls[l]) is TAdvToolBarSeparator then
                    begin
                      sl := l;
                      break;
                    end;

                    if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                    begin
                      FoundVC := true;
                      break;
                    end;
                  end;

                  if not FoundVC then
                  begin
                    for l := k + 1 to FATBControls.Count - 1 do
                    begin
                      if TControl(FATBControls[l]) is TAdvToolBarSeparator then
                      begin
                        sr := l;
                        break;
                      end;

                      if FLUHidedControls.IndexOf(FATBControls[l]) < 0 then
                      begin
                        FoundVC := true;
                        break;
                      end;
                    end;
                  end;

                  if not FoundVC then
                  begin // Select Separator
                    if (sl >= 0) and (FLUHidedControls.IndexOf(FATBControls[sl]) >= 0) and (TControl(FATBControls[sl]) is TAdvToolBarSeparator) then
                    begin
                      UHS := sl;
                    end
                    else if (sr >= 0) and (FLUHidedControls.IndexOf(FATBControls[sr]) >= 0) and (TControl(FATBControls[sr]) is TAdvToolBarSeparator) then
                    begin
                      UHS := sr;
                    end;
                  end;

                end;

                // Unhide here
                if UHS >= 0 then
                begin
                  if (TControl(FLUHidedControls[j]).Height + (TControl(FATBControls[UHS]).Height) <= abs(df)) then
                  begin
                    if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and (TControl(FLUHidedControls[j]).Parent <> self) then
                    begin
                      OldV := FInternalControlUpdation;
                      FInternalControlUpdation := True;
                      OldV2 := FUpdatingControls;
                      FUpdatingControls := True;
                      TControl(FLUHidedControls[j]).Parent := self;
                      FInternalControlUpdation := OldV;
                      FUpdatingControls := OldV2;
                    end;

                    inc(df, TControl(FLUHidedControls[j]).Height);
                    FLUHidedControls.Delete(j);

                    l := FLUHidedControls.IndexOf(FATBControls[UHS]);
                    if l >= 0 then
                    begin
                      inc(df, TControl(FLUHidedControls[l]).Height);
                      FLUHidedControls.Delete(l);
                    end;
                  end
                  else // no more search
                  begin
                    j := FLUHidedControls.Count - 1;
                    break;
                  end;
                end
                else
                begin
                  if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and (TControl(FLUHidedControls[j]).Parent <> self) then
                  begin
                    OldV := FInternalControlUpdation;
                    FInternalControlUpdation := True;
                    OldV2 := FUpdatingControls;
                    FUpdatingControls := True;
                    TControl(FLUHidedControls[j]).Parent := self;
                    FInternalControlUpdation := OldV;
                    FUpdatingControls := OldV2;
                  end;

                  if (j < FLUHidedControls.Count) then
                  begin
                    inc(df, TControl(FLUHidedControls[j]).Height);
                    FLUHidedControls.Delete(j);
                  end;
                end;

                break;
              end
              else
              begin
                j := FLUHidedControls.Count - 1;
                break;
              end;
            end;

            dec(j);
          end;

          if (j = FLUHidedControls.Count - 1) then
            break;

          FoundVC := False;
          for k:= 0 to FLUHidedControls.Count - 1 do
            if not (TControl(FLUHidedControls[k]) is TAdvToolBarSeparator) then
              FoundVC := True;
          if not FoundVC then
            Break;
          {
          if TControl(FLUHidedControls[FLUHidedControls.Count-1]).Height <= abs(df) then
          begin
            inc(df, TControl(FLUHidedControls[FLUHidedControls.Count-1]).Height);
            FLUHidedControls.Delete(FLUHidedControls.Count-1);
          end
          else
            break;  }

        end;
      end;
    end;

    SetControlsPosition(false);
  end
  else
  begin // If All Controls are hided then unhide controls
    if Position in [daTop, daBottom] then
    begin
      if (FLUHidedControls.Count > 0) then
      begin
        df := (Width - PopupIndicatorWidth);

        dgs := FCurrentToolBarStyler.DragGripStyle;

        if (Parent is TAdvPage) or (Parent is TCompactWindow) then
          dgs := dsNone;

        if (dgs <> dsNone) then
          df := df - DragGripWidth;

        df := -df;
        while df < 0 do
        begin
          if FLUHidedControls.Count > 0 then
          begin
            if TControl(FLUHidedControls[FLUHidedControls.Count - 1]).width <= abs(df) then
            begin
              if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and (TControl(FLUHidedControls[FLUHidedControls.Count - 1]).Parent <> self) then
              begin
                OldV := FInternalControlUpdation;
                FInternalControlUpdation := True;
                OldV2 := FUpdatingControls;
                FUpdatingControls := True;
                TControl(FLUHidedControls[FLUHidedControls.Count - 1]).Parent := self;
                FInternalControlUpdation := OldV;
                FUpdatingControls := OldV2;
              end;

              inc(df, TControl(FLUHidedControls[FLUHidedControls.Count - 1]).width);
              FLUHidedControls.Delete(FLUHidedControls.Count - 1);
            end
            else
              break;
          end;
          if FLUHidedControls.Count = 0 then
            break;
        end;
        SetControlsPosition(false);
      end;
    end
    else // Postion in [daLeft, daRight]
    begin
      if (FLUHidedControls.Count > 0) then
      begin
        df := (Height - PopupIndicatorWidth);

        dgs := FCurrentToolBarStyler.DragGripStyle;

        if (Parent is TAdvPage) or (Parent is TCompactWindow) then
          dgs := dsNone;

        if (dgs <> dsNone) then
          df := df - DragGripWidth;

        df := -df;
        while ((df < 0) and (FLUHidedControls.Count > 0)) do
        begin
          if TControl(FLUHidedControls[FLUHidedControls.Count - 1]).Height <= abs(df) then
          begin
            if not(csDesigning in ComponentState) and not(csLoading in ComponentState) and (TControl(FLUHidedControls[FLUHidedControls.Count - 1]).Parent <> self) then
            begin
              OldV := FInternalControlUpdation;
              FInternalControlUpdation := True;
              OldV2 := FUpdatingControls;
              FUpdatingControls := True;
              TControl(FLUHidedControls[FLUHidedControls.Count - 1]).Parent := self;
              FInternalControlUpdation := OldV;
              FUpdatingControls := OldV2;
            end;

            inc(df, TControl(FLUHidedControls[FLUHidedControls.Count - 1]).Height);
            FLUHidedControls.Delete(FLUHidedControls.Count - 1);
          end
          else
            break;
        end;
        SetControlsPosition(false);
      end;

    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetFloatingRows(const Value: integer);
begin
  if (Value <= 0) or (Value > GetMaxFloatingRowCount) then
    exit;

  if (FFloatingRows <> Value) then
  begin
    FFloatingRows := Value;
    if (csLoading in ComponentState) then
      exit;

    //FFloatingRows := Min(FFloatingRows, GetMaxFloatingRowCount);
    SetControlsPosition;
    if (ToolBarState = tsFloating) and Assigned(FFloatingWindow) {and FFloatingWindow.Visible} then
      FFloatingWindow.SetWindowSize;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetMaxFloatingRowCount: integer;
var
  i, mcs, x, y: integer;
begin
  mcs := 0;
  x := 2;

  for i := 0 to FATBControls.count - 1 do
  begin
    if Position in [daTop, daBottom] then
      mcs := Max(mcs, TControl(FAtbControls[i]).Width)
    else // daLeft, daRight
      mcs := Max(mcs, TControl(FAtbControls[i]).Height);
  end;

  mcs := mcs + x;
  mcs := max(mcs, FMinLength);
  y := 1;
  for i := 0 to FATBControls.count - 1 do
  begin
    if Position in [daTop, daBottom] then
    begin
      if (TControl(FAtbControls[i]).Width > (mcs - x)) then
      begin
        inc(y);
        x := 2;
      end;
      inc(x, TControl(FAtbControls[i]).Width);
    end
    else // daLeft, daRight
    begin
      if (TControl(FAtbControls[i]).Height > (mcs - x)) then
      begin
        inc(y);
        x := 2;
      end;
      inc(x, TControl(FAtbControls[i]).Height);
    end;

    if x >= mcs then
    begin
      inc(y);
      x := 2;
    end;
  end;

  Result := y;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.GetFloatingSizes(var aHeight, aWidth: integer);
var
  i, x, y, empty: integer;
  AllSet: Boolean;
begin
  aWidth := 0;

  for i := 0 to FATBControls.count - 1 do
  begin
    if Position in [daTop, daBottom] then
      aWidth := Max(aWidth, TControl(FAtbControls[i]).Width)
    else // daLeft, daRight
      aWidth := Max(aWidth, TControl(FAtbControls[i]).Height);
  end;

  x := 2;
  aWidth := aWidth + x * 2;
  aWidth := max(aWidth, FMinLength);
  AllSet := false;
  empty := aWidth;

  while not AllSet do
  begin
    x := 2;
    y := 1;
    for i := 0 to FATBControls.count - 1 do
    begin
      if Position in [daTop, daBottom] then
      begin
        if (TControl(FAtbControls[i]).Width > (aWidth - x - 2)) then
        begin
          empty := min(empty, (aWidth - x - 2));
          inc(y);
          x := 2;
        end;
        inc(x, TControl(FAtbControls[i]).Width);
      end
      else // daLeft, daRight
      begin
        if (TControl(FAtbControls[i]).Height > (aWidth - x - 2)) then
        begin
          empty := min(empty, (aWidth - x - 2));
          inc(y);
          x := 2;
        end;
        inc(x, TControl(FAtbControls[i]).Height);
      end;

      if Y > FFloatingRows then
        break;
    end;

    if Y <= FFloatingRows then
    begin
      AllSet := true;
      aHeight := Y * FSizeAtDock + CaptionHeight;
      if Y > 1 then
      begin
        empty := min(empty, (aWidth - x - 2));
        Dec(aWidth, empty);
      end;
    end
    else
    begin
      inc(aWidth, 10);
    end;

  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetFloatingWindowSizes(aRows: integer;
  var aHeight, aWidth: integer): Boolean;
var
  i, x, y, empty: integer;
  AllSet: Boolean;
begin
  Result := false;

  if (aRows <= 0) or (aRows > GetMaxFloatingRowCount) then
    exit;

  aWidth := 0;

  for i := 0 to FATBControls.count - 1 do
  begin
    if Position in [daTop, daBottom] then
      aWidth := Max(aWidth, TControl(FAtbControls[i]).Width)
    else // daLeft, daRight
      aWidth := Max(aWidth, TControl(FAtbControls[i]).Height);
  end;

  x := 2;
  aWidth := aWidth + x * 2;
  aWidth := max(aWidth, FMinLength);
  AllSet := false;
  empty := aWidth;
  Result := true;

  while not AllSet do
  begin
    x := 2;
    y := 1;
    for i := 0 to FATBControls.count - 1 do
    begin
      if Position in [daTop, daBottom] then
      begin
        if (TControl(FAtbControls[i]).Width > (aWidth - x - 2)) then
        begin
          empty := min(empty, (aWidth - x - 2));
          inc(y);
          x := 2;
        end;
        inc(x, TControl(FAtbControls[i]).Width);
      end
      else // daLeft, daRight
      begin
        if (TControl(FAtbControls[i]).Height > (aWidth - x - 2)) then
        begin
          empty := min(empty, (aWidth - x - 2));
          inc(y);
          x := 2;
        end;
        inc(x, TControl(FAtbControls[i]).Height);
      end;

      if Y > aRows then
        break;
    end;

    if Y <= aRows then
    begin
      AllSet := true;
      aHeight := Y * FSizeAtDock + CaptionHeight;
      if Y > 1 then
      begin
        empty := min(empty, (aWidth - x - 2));
        Dec(aWidth, empty);
      end;
    end
    else
    begin
      inc(aWidth, 10);
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetShowRightHandle(const Value: Boolean);
begin
  if FShowRightHandle <> Value then
  begin
    FShowRightHandle := Value;

    if FShowRightHandle then
    begin
      PopupIndicatorWidth := DEFAULT_POPUPINDICATORWIDTH;
    end
    else
    begin
      PopupIndicatorWidth := 4;
    end;
    SetControlsPosition;
    if Assigned(FCurrentDock) and (ToolBarState = tsDocked) then
      FCurrentDock.Rows.SetRowsPosition;

    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OptionIndicatorClick;
var
  pt,spt: TPoint;
begin
  if (Assigned(FOnOptionClick) or Assigned(OptionMenu) or Assigned(FCustomizer)) and Assigned(Parent) then
  begin
    if ToolBarState <> tsFLoating then
    begin
      pt := Point(Left + Width - 12, Top + Height + 1);
      spt := Parent.ClientToScreen(pt);
    end
    else
    begin
      if ShowClose then
        pt := Point(Left + Width - 40, Top + CaptionHeight - 2)
      else
        pt := Point(Left + Width - 20, Top + CaptionHeight - 2);
      spt := ClientToScreen(pt);
    end;

    if Assigned(FOnOptionCLick) then
      FOnOptionClick(self, pt, spt );
   { if Assigned(OptionMenu) then
    begin
      if OptionMenu is TAdvPopupMenu then
      begin
        (OptionMenu as TAdvPopupMenu).MenuStyler := ToolBarStyler.AdvMenuStyler;
      end;

      OptionMenu.Popup(spt.X,spt.Y);
    end;
    }
    ShowOptionWindow(0, 0, False);

    if FDownPopupIndicator or FHotPopupIndicator then
    begin
      FDownPopupIndicator := false;
      FHotPopupIndicator := False;
      DrawPopupIndicator;
    end;

  end
  else if Assigned(Parent) then
  begin
    ShowOptionWindow(0, 0, False);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CapOptionIndicatorClick;
var
  pt,spt: TPoint;
begin
  if (Assigned(FOnOptionClick){ or Assigned(OptionMenu) or Assigned(FCustomizer)}) and Assigned(Parent) then
  begin
    if ToolBarState <> tsFLoating then
    begin
      pt := Point(Left + Width - 12, Top + Height + 1);
      spt := Parent.ClientToScreen(pt);
      if Assigned(FOnOptionCLick) then
        FOnOptionClick(self, pt, spt);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetPersistence(const Value: TPersistence);
begin
  FPersistence.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.LoadPosition;
var
  L, T, FR, St, V, I, SV: integer;
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
  N : String;
  b: Boolean;
begin

  if (FPersistence.Enabled) and (FPersistence.Key <>'') and
     (FPersistence.Section <>'') and
     (not (csDesigning in ComponentState)) then
  begin
    {$IFDEF DELPHI4_LVL}
    if FPersistence.location = plRegistry then
      IniFile := TRegistryIniFile.Create(FPersistence.Key)
    else
    {$ENDIF}
      IniFile := TIniFile(tIniFile.Create(FPersistence.Key));

    with IniFile do
    begin
      //OldV:= AllowBoundChange;
      //AllowBoundChange:= true;

      N := ReadString(FPersistence.section, Name+'.Name', '');
      St := ReadInteger(FPersistence.section, Name+'.State', integer(tsDocked));

      if (N <> '') and (UpperCase(N) = UpperCase(Name)) and (TToolBarState(st) = tsFloating) then
      begin
        {i := ReadInteger(FPersistence.section,'Width', Width);
        if Constraints.MaxWidth < i then
          Constraints.MaxWidth:= i;
        if (i <> Width) then
          Width := i;
        }
        //i := ReadInteger(FPersistence.section,'Height', Height);

        FR := ReadInteger(FPersistence.section, Name+'.FloatingRows', FloatingRows);
        L := ReadInteger(FPersistence.Section, Name+'.Left', Left);
        T := ReadInteger(FPersistence.section, Name+'.Top', Top);
        SetFloating(L, T, True);
        if FR > FloatingRows then
          FloatingRows:= FR;

        SV := ReadInteger(FPersistence.section, Name+'.Visible', Integer(Self.Visible));
        if self.Visible <> Boolean(SV) then
          self.Visible := Boolean(SV);
      end;

      b := false;
      //if (N <> '') and (UpperCase(N) = UpperCase(Name)) then
      begin
        for I:= 0 to FATBControls.Count-1 do
        begin
          if (TControl(FATBControls[i]).Name <> '') then
          begin
            V := ReadInteger(FPersistence.section, Name+'.'+TControl(FATBControls[i]).Name, Integer(TControl(FATBControls[i]).Visible));
            if V <> Integer(TControl(FATBControls[i]).Visible) then
            begin
              TControl(FATBControls[i]).Visible := Boolean(V);
              b := true;
            end;
          end;
        end;
      end;

      if b then
        SetControlsPosition;

      //if Self.Visible <> Boolean(SV) then
        //Self.Visible := Boolean(SV);
      //AllowBoundChange:= OldV;
    end;
    IniFile.Free;
    FPersistSettingLoaded := True;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SavePosition;
var
  N: String;
  St, i: integer;
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
begin
  if (FPersistence.Enabled) and (FPersistence.Key <>'') and
     (FPersistence.Section <>'') and
     (not (csDesigning in ComponentState)) then
  begin
    {$IFDEF DELPHI4_LVL}
    if FPersistence.Location = plRegistry then
      IniFile := TRegistryIniFile.Create(FPersistence.Key)
    else
    {$ENDIF}
      IniFile := TIniFile.Create(FPersistence.Key);

    with IniFile do
    begin
      if (ToolBarState = tsFloating) then
      begin
        WriteString(FPersistence.section, Name+'.Name', Name);
        WriteInteger(FPersistence.section, Name+'.State', integer(ToolBarState));
        WriteInteger(FPersistence.section, Name+'.FloatingRows', FloatingRows);
        WriteInteger(FPersistence.section, Name+'.Left', FFloatingWindow.Left);
        WriteInteger(FPersistence.section, Name+'.Top', FFloatingWindow.Top);
        WriteInteger(FPersistence.section, Name+'.Width', Width);
        WriteInteger(FPersistence.section, Name+'.Height', Height);
        WriteInteger(FPersistence.section, Name+'.Visible', integer(Self.Visible));
      end
      else
      begin
        N := ReadString(FPersistence.section, Name+'.Name', '');
        St := ReadInteger(FPersistence.section, Name+'.State', integer(tsDocked));
        if (N <> '') and (UpperCase(N) = UpperCase(Name)) and (TToolBarState(st) = tsFloating) then
        begin
          WriteInteger(FPersistence.section, Name+'.State', integer(ToolBarState));
        end;
      end;

      for I:= 0 to FATBControls.Count-1 do
      begin
        if (TControl(FATBControls[i]).Name <> '') then
          WriteInteger(FPersistence.section, Name+'.'+TControl(FATBControls[i]).Name, Integer(TControl(FATBControls[i]).Visible));
      end;
    end;
    IniFile.Free;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetShowHint: Boolean;
begin
  Result := inherited ShowHint;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetShowHint(const Value: Boolean);
begin
  inherited ShowHint := Value;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetMenuItemCount: integer;
  procedure CountChildItems(Item: TMenuItem);
  var
    i: integer;
  begin
    for i:=0 to Item.Count-1 do
      CountChildItems(Item.Items[i]);

    inc(Result);
  end;

var
  i: integer;
begin
  Result := 0;
  for i:=0 to FMenu.Items.Count - 1 do
    CountChildItems(FMenu.Items[i]);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnMainMenuChange(Sender: TObject;
  Source: TMenuItem; Rebuild: Boolean);
var
  I: integer;
  ReqReBuild: Boolean;
  OldMenu: TMainMenu;
begin
  if not (csDesigning in ComponentState) then
    exit;

  if FTempMenuItemCount <= 0 then
  begin
    ReqReBuild := False;

    if (Source <> nil) then
    begin
      for I := 0 to FMenu.Items.Count - 1 do
      begin
        if Source = FMenu.Items[I] then
        begin
          ReqReBuild := True;    // May Required ReBuild since it is root item
          Break;
        end;
      end;

      if ReqReBuild then
      begin
        for I := 0 to FATBControls.Count - 1 do
        begin
          if (TControl(FATBControls[I]) is TAdvToolBarMenuButton) and (TAdvToolBarMenuButton(FATBControls[I]).FToolBarCreated)
             and (TAdvToolBarMenuButton(FATBControls[I]).MenuItem = Source) then
          begin
            TAdvToolBarMenuButton(FATBControls[I]).MenuItem := TAdvToolBarMenuButton(FATBControls[I]).MenuItem;
            ReqReBuild:= false;
            Break;
          end;
        end;
      end;
    end;

  {  if Assigned(FMenuImages) and Assigned(FMenu.Images) then
      showmessage(FMenuImages.Name + ' ' + FMenu.Images.name)
    else if Assigned(FMenuImages) then
      showmessage(FMenuImages.Name)
    else if Assigned(FMenu.Images) then
      showmessage(FMenu.Images.name);

    if csLoading in ComponentState then
      showmessage('Self is loading');
    if csLoading in FMenu.ComponentState then
      showmessage('Menu is loading');
   }
    if FMenu.Images <> FMenuImages then
    begin
      FTempMenuItemCount := GetMenuItemCount - 1;
      //FMenuImages := FMenu.Images; // set in SetMenu
    end;

    if ReqReBuild or (Source = nil) then
    begin
      OldMenu := FMenu;
      SetMenu(nil);
      SetMenu(OldMenu);
    end;

  end
  else
  begin
    Dec(FTempMenuItemCount);
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetVersion: string;
var
  vn: Integer;
begin
  vn := GetVersionNr;
  Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn)));
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetVersionNr: Integer;
begin
  Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetVersion(const Value: string);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.WMGetDlgCode(var Message: TMessage);
begin
  if FInMenuLoop or (Parent is TAdvPage) or (Parent is TCompactWindow) then
    Message.Result := DLGC_WANTARROWS;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.WMSysCommand(var Message: TWMSysCommand);
var
  Button: TAdvCustomToolBarButton;
begin
  { Enter menu loop if only the Alt key is pressed -- ignore Alt-Space and let
    the default processing show the system menu. }
  if not FInMenuLoop and Enabled and Showing {and ShowCaptions} and Assigned(FMenu) then
    with Message do
      if (CmdType and $FFF0 = SC_KEYMENU) and (Key <> VK_SPACE) and
        (Key <> Word('-')) and (GetCapture = 0) then
      begin
        if Key = 0 then
          Button := nil else
          Button := FindButtonFromAccel(Key);
        if (Key = 0) or (Button <> nil) then
        begin
          TrackMenu(Button);
          Result := 1;
          Exit;
        end;
      end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.TrackMenu(
  Button: TAdvCustomToolBarButton): Boolean;
begin
  { Already in menu loop - click button to drop-down menu }
  if FInMenuLoop then
  begin
    if Button <> nil then
    begin
      ClickButton(Button);
      Result := True;
    end
    else
      Result := False;
    Exit;
  end;

  InitMenu(Button);
  try                      // FF: Menu with one root Item causing disable mouse click after showing menu
    if Assigned(Menu){ and (Menu.Items.Count > 1) }then  // FF: DropDown Menu with MenuButton only causing disable mouse click after showing menu
    begin
      FInMenuLoop := True;
      repeat
        Application.HandleMessage;
        if Application.Terminated then
          FInMenuLoop := False;
      until not FInMenuLoop;
    end;
  finally
    CancelMenu;
  end;
  Result := FMenuResult;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.InitMenu(Button: TAdvCustomToolBarButton);
{var
  Button2: TAdvCustomToolBarButton;
  MP: TPoint;  }
begin
  Perform(TB_SETANCHORHIGHLIGHT, 1, 0);
  MenuToolBar2 := Self;
  MouseCapture := True;
  FMenuFocused := True;
  InitToolMenuKeyHooks;
  if Button <> nil then
  begin
    //Perform(TB_SETHOTITEM, Button.Index, 0);
    SetButtonHot(Button.Index);
    //ClickButton(Button);
    Button.DoDropDown;
  end
  else
  begin
    SetButtonHot(0);
   { GetCursorPos(MP);
    Mp := ScreenToClient(Mp);
    Button2 := ButtonAtPos(Mp.X, MP.Y);
    if (Button2 <> nil) then
    begin
      Button2.FUnHotTimer.Enabled := False;
      Button2.FMouseInControl := false;
      Button2.FHot := false;
      if Button2.Enabled then
        Button2.InvalidateMe;
    end;}
  end;
    //Perform(TB_SETHOTITEM, 0, 0);
  if Button = nil then
    FCaptureChangeCancels := True;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CNSysKeyDown(var Message: TWMSysKeyDown);
begin
  inherited;
  if (Message.CharCode = VK_MENU) then
    CancelMenu;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CNChar(var Message: TWMChar);
begin
  { We got here through the installed ToolMenuKeyHook }
  if FInMenuLoop and not (csDesigning in ComponentState) then
    with Message do
      if Perform(CM_DIALOGCHAR, CharCode, KeyData) <> 0 then
        Result := 1;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.WMCaptureChanged(var Message: TMessage);
begin
  inherited;
  if FInMenuLoop and FCaptureChangeCancels then CancelMenu;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.WMKeyDown(var Message: TWMKeyDown);
var
  //Item: Integer;
  I: Integer;
  Button: TAdvCustomToolBarButton;
  P: TPoint;
  Ctrl: TWinControl;
begin
  if FInMenuLoop then
  begin
    //Item := Perform(TB_GETHOTITEM, 0, 0);
    Button := FHotButton;
    case Message.CharCode of
      VK_RETURN, VK_DOWN:
        begin
          //if (Item > -1) and (Item < FATBControls.Count) then
          if Button <> nil then
          begin
            //Button := TAdvCustomToolBarButton(FATBControls[Item]);
            P := Button.ClientToScreen(Point(1, 1));
            Button.DoDropDown;
            //ClickButton(Button);
          end;
          { Prevent default processing }
          if Message.CharCode = VK_DOWN then Exit;
        end;
      VK_ESCAPE: CancelMenu;
      VK_LEFT:
      begin
        if FHotButton <> nil then
        begin
          I := FHotButton.Index;
          I := I -1;
          if (I < 0) or (I >= FATBControls.Count) then
            I := FATBControls.Count-1;

          if I >= 0 then
            SetButtonHot(I);
        end;
      end;
      VK_RIGHT:
      begin
        if FHotButton <> nil then
        begin
          I := FHotButton.Index;
          I := I +1;
          if (I < 0) or (I >= FATBControls.Count) then
            I := 0;
          if I >= 0 then
            SetButtonHot(I);
        end;
      end;
    end;
  end
  else if Assigned(Parent) and (Parent is TAdvPage) then
  begin
    if (TAdvPage(Parent).FShortCutHint <> nil) then
      TAdvPage(Parent).HideShortCutHintOfAllToolBars;
  end
  else if (Parent is TCompactWindow) then
  begin
    //--- Handling shortcuthint for compact state
    if Assigned(FSelfClone) and (FSelfClone.Parent is TAdvPage) then
    begin
      if FCompactShortCutHintShowing then
      begin
        if not (Message.CharCode in [48..57, 65..90, 97..122]) then
        begin
          HideShortCutHintOfButtons;

          // Redisplay KeyTips for all Tabs
          if (Message.CharCode = VK_ESCAPE) and (TAdvPage(FSelfClone.Parent).AdvToolBarPager is TAdvToolBarPager) then
          begin
            if Assigned(FSelfClone.FCompactBtn) and FSelfClone.FCompactBtn.Visible then
              FSelfClone.FCompactBtn.SetFocus;

            TAdvPage(FSelfClone.Parent).ShowShortCutHintOfAllToolBars;
            inherited;
            Exit;
          end;
        end;

        if (Message.CharCode in [48..57, 65..90, 97..122]) then
        begin
          TAdvPage(FSelfClone.Parent).FShortCutChars := TAdvPage(FSelfClone.Parent).FShortCutChars + char(Message.CharCode);
          if {TAdvPage(FSelfClone.Parent).}HasShortCut(TAdvPage(FSelfClone.Parent).FShortCutChars, i) then
          begin
            //TAdvPage(FSelfClone.Parent).HideShortCutHintOfAllToolBars;
            HideShortCutHintOfButtons;
          end;
        end;
        
      end;
    end;
    //----

    case Message.CharCode of
      VK_DOWN, VK_LEFT, VK_RIGHT:
      begin
        Ctrl := GetFirstTabControl(True);
        if (Ctrl <> nil) and (Ctrl.CanFocus) then
        begin
          Ctrl.SetFocus;
        end;
      end;
      VK_ESCAPE, VK_UP:
      begin
        if Assigned(FSelfClone) and Assigned(FSelfClone.Parent) and (FSelfClone.Parent is TAdvPage) and (FSelfClone.Parent.Parent is TAdvToolBarPager) then
        begin
          TAdvToolBarPager(FSelfClone.Parent.Parent).SetFocus;
        end;
      end;
    end;
  end;
  inherited;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.SetButtonHot(Button: TAdvCustomToolBarButton): Boolean;
begin
  Result := false;
  if Assigned(Button) then
  begin
    Button.Hot := True;
    Result := True;
  end
  else if FHotButton <> nil then
  begin
    FHotButton.Hot := false;
    Result := True;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.SetButtonHot(ButtonNumber: Integer): Boolean;
var
  I, J: Integer;
  Button: TAdvCustomToolBarButton;
begin
  Result := False;
  if ButtonNumber >= 0 then
  begin
    Button := nil;
    J := 0;
    for i := 0 to FATBControls.Count - 1 do
    begin
      if (TControl(FATBControls[i]) is TAdvToolBarMenuButton) and TControl(FATBControls[i]).Visible and TControl(FATBControls[i]).Enabled
          and (((FLUHidedControls.IndexOf(FATBControls[i]) < 0) and (ToolBarState = tsDocked)) or (ToolBarState in [tsFloating, tsFixed])) then
      begin
        if (J = ButtonNumber) then
        begin
          Button := TAdvCustomToolBarButton(FATBControls[i]);
          break;
        end;
        inc(J);
      end;
    end;
    if Button <> nil then
      Result := SetButtonHot(Button);
  end
  else
  begin
    Result := True;
    SetButtonHot(nil);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateButtonHot(Button: TAdvCustomToolBarButton);
begin
  if Assigned(Button) then
  begin
    if Button.Hot then
    begin
      if (FHotButton <> nil) and (FHotButton <> Button) then
        FHotButton.Hot := false;
      FHotButton := Button;
    end
    else
    begin
      if FHotButton = Button then
        FHotButton := nil;
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAllowFloating(const Value: Boolean);
begin
  if FAllowFloating <> Value then
  begin
    FAllowFloating := Value;
    if (ToolBarState = tsFloating) and not FAllowFloating then
      FAllowFloating := True;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetLocked(const Value: Boolean);
begin
  if FLocked <> Value then
  begin
    FLocked := Value;
    if (ToolBarState = tsFloating) and Value then
      FLocked := False;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.InitializeOptionWindow;
var
  i, j, k: Integer;
  ASep: TAdvToolBarSeparator;
begin
  if not (csDesigning in ComponentState){ and AutoOptionMenu} then
  begin
    if not Assigned(FOptionWindow) then
    begin
      FOptionWindow := TOptionSelectorWindow.CreateNew(self);
      FOptionWindow.Parent := self;   // FF: D2005
      FOptionWindow.BorderIcons := [];
      FOptionWindow.BorderStyle := bsNone;
      FOptionWindow.Ctl3D := false;
      FOptionWindow.FormStyle := fsStayOnTop;
      FOptionWindow.Visible := False;
      FOptionWindow.Width := 10;
      FOptionWindow.Height := 10;
      FOptionWindow.AutoScroll := False;
      FOptionWindow.BorderWidth := 0;
      FOptionWindow.OnHide := OnOptionWindowHide;
      FOptionWindow.AdvToolBar := Self;
    end;

    if not Assigned(FOptionWindowPanel) then
    begin
      FOptionWindowPanel := TControlSelectorPanel.Create(FOptionWindow);
      FOptionWindowPanel.Parent := FOptionWindow;
    end;
    
    FOptionWindowPanel.ShowAddAndRemoveBtn := AutoOptionMenu;
    if Assigned(self.OptionMenu) then
      if (self.OptionMenu is TAdvPopupMenu) then
        TAdvPopupMenu(OptionMenu).MenuStyler := FCurrentToolBarStyler.CurrentAdvMenuStyler;
        
    FOptionWindowPanel.OptionsMenu := self.OptionMenu;
    FOptionWindowPanel.TextAutoOptionMenu := self.TextAutoOptionMenu;
    FOptionWindowPanel.TextOptionMenu := self.TextOptionMenu;

    FOptionWindowPanel.Customizer := Self.Customizer;
    FOptionWindowPanel.AdvToolBar := Self;

    if Assigned(FMenu) then
    begin
      FOptionWindowPanel.ItemColorHot := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.HoverColor;
      FOptionWindowPanel.ItemColorHotTo := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.HoverColorTo;
      FOptionWindowPanel.ItemColorDown := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.SelectedColor;
      FOptionWindowPanel.ItemColorDownTo := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.SelectedColorTo;
      FOptionWindowPanel.ItemTextColor := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.Font.Color;
      FOptionWindowPanel.ItemTextColorHot := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.HoverTextColor;
      FOptionWindowPanel.ItemTextColorDown := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.SelectedTextColor;
    end
    else
    begin
      FOptionWindowPanel.ItemColorHot := FCurrentToolBarStyler.ButtonAppearance.ColorHot;
      FOptionWindowPanel.ItemColorHotTo := FCurrentToolBarStyler.ButtonAppearance.ColorHotTo;
      FOptionWindowPanel.ItemColorDown := FCurrentToolBarStyler.ButtonAppearance.ColorDown;
      FOptionWindowPanel.ItemColorDownTo := FCurrentToolBarStyler.ButtonAppearance.ColorDownTo;
      FOptionWindowPanel.ItemTextColor := FCurrentToolBarStyler.ButtonAppearance.CaptionTextColor;
      FOptionWindowPanel.ItemTextColorHot := FCurrentToolBarStyler.ButtonAppearance.CaptionTextColorHot;
      FOptionWindowPanel.ItemTextColorDown := FCurrentToolBarStyler.ButtonAppearance.CaptionTextColorDown;
    end;

    FOptionWindow.OptionsPanel := FOptionWindowPanel;
    FOptionWindowPanel.ControlList.Clear;

    // Assigning Hidden Controls
    FInternalControlUpdation := True;
   { for i:= 0 to FLUHidedControls.Count-1 do
    begin
      if not (TControl(FLUHidedControls[i]) is TAdvToolBarSeparator) then
        FOptionWindowPanel.AddControl(TControl(FLUHidedControls[i]));
    end; }
    k := 1;
    ASep := nil;
    for i:= 0 to FATBControls.Count - 1 do
    begin
      if (TControl(FATBControls[i]) is TAdvToolBarSeparator) then
        ASep := TAdvToolBarSeparator(FATBControls[i]);
        
      j := FLUHidedControls.IndexOf(FATBControls[i]);
      if (j >= 0) then
      begin
        if not (((k = 1) or (k = FLUHidedControls.Count)) and (TControl(FLUHidedControls[j]) is TAdvToolBarSeparator)) then
        begin
          if ((ASep <> nil) and not(TControl(FLUHidedControls[j]) is TAdvToolBarSeparator)) then
          begin
            if (k > 1 ) then
              FOptionWindowPanel.AddCopySeparator(ASep);
            ASep := nil;
          end;
          FOptionWindowPanel.AddControl(TControl(FLUHidedControls[j]));
          if (TControl(FLUHidedControls[j]) is TAdvToolBarSeparator) then
            ASep := nil;
          inc(k);
        end;
      end;
    end;

    FInternalControlUpdation := False;

    FOptionWindowPanel.ArrangeControls;

    FOptionWindow.SetWindowSize;

  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnOptionWindowHide(Sender: TObject);
begin
 { State := absUp; }
  UpdateRULists;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.ShowOptionWindow(X, Y: Integer; ForcePoint: Boolean=True);
var
  pt, spt: TPoint;
  R: TRect;
  {$IFDEF DELPHI9_LVL}
  w,h: Integer;
  {$ENDIF}
begin
  //if not AutoOptionMenu then
    //exit;

  InitializeOptionWindow;
  
  if not ForcePoint then
  begin
    if ToolBarState <> tsFLoating then
    begin
      pt := Point(Left + Width - 12, Top + Height + 1);
      spt := Parent.ClientToScreen(pt);

    {$IFNDEF TMSDOTNET}
      SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
    {$ENDIF}
    {$IFDEF TMSDOTNET}
      SystemParametersInfo(SPI_GETWORKAREA, 0, R, 0);
    {$ENDIF}

      if R.Bottom < (spt.Y + FOptionWindow.Height + 2) then
        spt.Y := spt.Y - ((spt.Y + FOptionWindow.Height + 2) - R.Bottom);

      {$IFDEF DELPHI6_LVL}
      R.Right := Screen.MonitorFromPoint(spt).Width;
      {$ELSE}
      R.Right := Screen.Width;
      {$ENDIF}

      //R.Right := Screen.Width;

      if (R.Right < spt.X + FOptionWindow.Width) then
      begin
        if Position = daRight then
          spt.X := ClientToScreen(Point(Left - FOptionWindow.Width, Top + Height + 1)).X
        else
          spt.X := spt.X - ((spt.X + FOptionWindow.Width) - R.Right);
      end;

    end
    else
    begin
      if ShowClose then
        pt := Point(Left + Width - 40, Top + CaptionHeight - 2)
      else
        pt := Point(Left + Width - 20, Top + CaptionHeight - 2);
      spt := ClientToScreen(pt);
    end;
    X := spt.X;
    Y := spt.Y;
  end;

  if not FOptionWindowPanel.IsEmpty then
  begin
    {$IFDEF DELPHI9_LVL}
    w := FOptionWindow.Width;
    h := FOptionWindow.Height;
    FOptionWindow.Width := 0;
    FOptionWindow.Height := 0;
    FOptionWindow.Visible := True;
    {$ENDIF}

    FOptionWindow.Left := X;
    FOptionWindow.Top := Y;
    FOptionWindow.Visible := True;

    {$IFDEF DELPHI9_LVL}
    FOptionWindow.Width := w;
    FOptionWindow.Height := h;
    {$ENDIF}
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.HideOptionWindow;
begin
  if Assigned(FOptionWindow) and FOptionWindow.visible then
  begin
    FOptionWindow.visible := False;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAutoOptionMenu(const Value: Boolean);
begin
  if FAutoOptionMenu <> Value then
  begin
    FAutoOptionMenu := Value;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateMenu;
var
  ReAssignMenu, ItemFound: Boolean;
  I, J: Integer;
  OldMenu: TMainMenu;
begin
  if Assigned(FMenu) then
  begin
    if FMenu.Handle = 0 then
    begin
      { Do nothing just required to call GetHandle
        which internally calls InternalReThinkHotKeys. }
    end;


    ReAssignMenu := False;

    for I := 0 to FMenu.Items.Count - 1 do
    begin
      ItemFound := False;
      for J := 0 to FATBControls.Count - 1 do
      begin
        if (TControl(FATBControls[J]) is TAdvToolBarMenuButton) and (TAdvToolBarMenuButton(FATBControls[J]).FToolBarCreated)
           and (TAdvToolBarMenuButton(FATBControls[J]).MenuItem = FMenu.Items[I]) then
        begin
          TAdvToolBarMenuButton(FATBControls[J]).MenuItem := FMenu.Items[I]; // Refresh Item
          ItemFound := True;
          Break;
        end;
      end;

      if not ItemFound then
      begin
        ReAssignMenu := True;
        Break;
      end;
    end;

    if ReAssignMenu then
    begin
      OldMenu := FMenu;
      SetMenu(nil);
      SetMenu(OldMenu);
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.AdjustSizeOfAllButtons(
  MenuButtonsOnly: Boolean);
var
  I: Integer;  
begin
  for i := 0 to FATBControls.Count - 1 do
  begin
    if MenuButtonsOnly then
    begin
      if TControl(FATBControls[i]) is TAdvToolBarMenuButton then
        TAdvToolBarMenuButton(FAtbControls[i]).AdjustSize;
    end
    else
    begin
      if TControl(FATBControls[i]) is TAdvCustomToolBarButton then
        TAdvCustomToolBarButton(FAtbControls[i]).AdjustSize;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMVisibleChanged(var Message: TMessage);
begin
  inherited;
  if (Self.ToolBarState = tsDocked) and Assigned(FCurrentDock) then
  begin
    if not (csDesigning in ComponentState) then
      FCurrentDock.UpdateToolBarVisibility(self);
  end
  else if (Self.ToolBarState = tsFloating) then
  begin
    if (FFloatingWindow <> nil) {and (FFloatingWindow.Visible)} then
    begin
      FAutoHiding := Self.Visible;
      FFloatingWindow.Visible := Self.Visible;
    end;
  end;

  if (Self.ToolBarState in [tsFixed, tsDocked]) and Assigned(Self.Parent) and (Self.Parent is TAdvPage) then
  begin
    TAdvPage(Self.Parent).UpdateAdvToolBarsPosition;
    if Self.Visible then
      TAdvPage(Self.Parent).DecreaseToolBarSize
    else
      TAdvPage(Self.Parent).IncreaseToolBarSize;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.IsShortCut(var Message: TWMKey): Boolean;
begin
  Result := False;
  if Assigned(FMenu) then
  begin
    Result := FMenu.IsShortCut(Message);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAutoArrangeButtons(const Value: Boolean);
begin
  if FAutoArrangeButtons <> Value then
  begin
    FAutoArrangeButtons := Value;

    if not FAutoArrangeButtons and not(csLoading in ComponentState) and FAutoRUL then
    begin
      FRUControls.Clear;
      {$IFDEF DELPHI6_LVL}
      FRUControls.Assign(FATBControls, laCopy);
      {$ELSE}
      FRUControls.AssignList(FATBControls);
      {$ENDIF}
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetMaxLength: Integer;
var
  x, y, i, w: Integer;
  dgs: TDragGripStyle;

begin
  W := FMinLength;

  dgs := FCurrentToolBarStyler.DragGripStyle;
  if (Parent is TAdvPage) or (Parent is TCompactWindow) then
    dgs := dsNone;

  if (Position in [daTop, daBottom]) or (FToolBarState = tsFloating) then
  begin
    if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
      x := DragGripWidth + 2
    else
      x := 2;
    {
    if Self.ToolBarState in [tsDocked, tsFixed] then
      y := 2
    else
      y := 2 + CaptionHeight;
    }

    for i := 0 to FATBControls.Count - 1 do
    begin
      if TControl(FATBControls[i]).Visible then
        x := x + TControl(FATBControls[i]).Width;
    end;

    if ShowPopupIndicator then
      x := x + PopupIndicatorWidth;

    x := Max(x, W);
    Result := x;
  end
  else // if Position in [daLeft, daRight] then
  begin
    if (dgs <> dsNone) and (ToolBarState <> tsFloating) then
      y := DragGripWidth + 2
    else
      y := 2;

    for i := 0 to FATBControls.Count - 1 do
    begin
      if TControl(FATBControls[i]).Visible then
        y := y + TControl(FATBControls[i]).Height;
    end;

    if ShowPopupIndicator then
      y := y + PopupIndicatorWidth;

    y := Max(y, W);
    Result := y;
  end;
end;
(*
var
  i, W, H, MaxS, MaxCtrlS: Integer;
begin
  if (Position in [daTop, daBottom]) or (FToolBarState = tsFloating) then
  begin
    W := FMinLength;
    if FATBControls.Count > 0 then
    begin
      i := FATBControls.count - 1;
      while i >= 0 do
      begin
        if {(FLUHidedControls.IndexOf(FATBControls[i]) < 0) and }TControl(FATBControls[i]).visible then
          break;
        dec(i);
      end;

      if i >= 0 then
        W := TControl(FATBControls[i]).Left + TControl(FATBControls[i]).Width
      else
        W := MIN_BUTTONSIZE;

      if ShowPopupIndicator then
      begin
        if (FToolBarState = tsFloating) then
          W := W + 2
        else
          W := W + PopupIndicatorWidth;
      end;
    end;

    if (FCurrentToolBarStyler.DragGripStyle <> dsNone) and (ToolBarState <> tsFloating) then
      MaxS := DragGripWidth + 2
    else
      MaxS := 2;

    MaxCtrlS := DEFAULT_TOOLBARHEIGHT;
    for i := 0 to FATBControls.count - 1 do
    begin
      if TControl(FATBControls[i]).visible then
      begin
        MaxS := MaxS + TControl(FATBControls[i]).Width;
        if not (TControl(FATBControls[i]) is TAdvToolBarSeparator) then
          MaxCtrlS := Max(MaxCtrlS, TControl(FATBControls[i]).Height + 4);
      end;
    end;

    if ShowPopupIndicator then
      MaxS := MaxS + PopupIndicatorWidth;

    MaxS := Max(MaxS, W);
    Result := MaxS;
  end
  else // if Position in [daLeft, daRight] then
  begin
    H := FMinLength;
    if FATBControls.Count > 0 then
    begin
      i := FATBControls.count - 1;
      while i >= 0 do
      begin
        if {(FLUHidedControls.IndexOf(FATBControls[i]) < 0) and }TControl(FATBControls[i]).visible then
          break;
        dec(i);
      end;

      if i >= 0 then
        H := TControl(FATBControls[i]).Top + TControl(FATBControls[i]).Height
      else
        H := MIN_BUTTONSIZE;

      if ShowPopupIndicator then
        H := H + PopupIndicatorWidth;
    end;

    if (FCurrentToolBarStyler.DragGripStyle <> dsNone) and (ToolBarState <> tsFloating) then
      MaxS := DragGripWidth + 2
    else
      MaxS := 2;

    MaxCtrlS := DEFAULT_TOOLBARHEIGHT;
    for i := 0 to FATBControls.count - 1 do
    begin
      if TControl(FATBControls[i]).visible then
      begin
        MaxS := MaxS + TControl(FATBControls[i]).Height;
        if not (TControl(FATBControls[i]) is TAdvToolBarSeparator) then
          MaxCtrlS := Max(MaxCtrlS, TControl(FATBControls[i]).Width + 4);
      end;
    end;

    if ShowPopupIndicator then
      MaxS := MaxS + PopupIndicatorWidth;

    MaxS := Max(MaxS, H);
    Result := MaxS;
  end;
end;
*)
//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.WMTimer(var Message: TWMTimer);
begin
  inherited;
  if not Assigned(FParentForm) then
    Exit;
  if not Assigned(FFloatingWindow) then
    Exit;

  if not FParentForm.Visible and FFloatingWindow.Visible then
  begin
    FFloatingWindow.Visible := False;
    FAutoHiding := True;
  end;

  if FParentForm.Visible and not FFloatingWindow.Visible and FAutoHiding then
  begin
    FAutoHiding := False;
    FFloatingWindow.Visible := True;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.WndProc(var Message: TMessage);
var
  PrtForm: TCustomForm;
begin
  if (Message.Msg = WM_DESTROY) then
  begin
    if FTimerID <> 0 then
    begin
      KillTimer(Handle, FTimerID);
      FTimerID := 0;
    end;
  end;

  if (Message.Msg = WM_TBCOMPACTWINHIDE) then
  begin
    PrtForm := GetParentForm(Self);
    if Assigned(PrtForm) and Assigned(PrtForm.Menu) then  // FF: Form.Menu repainting
    begin // Force repaint
      PrtForm.Height := PrtForm.Height + 1;
      PrtForm.Height := PrtForm.Height - 1;
    end;
  end;

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetDisabledImages(const Value: TCustomImageList);
var
  i: Integer;
begin
  if Value <> FDisabledImages then
  begin
    FDisabledImages := Value;

    for i := 0 to FATBControls.Count - 1 do
    begin
      if TControl(FATBControls[i]) is TAdvCustomToolBarControl then
        TAdvCustomToolBarControl(FAtbControls[i]).AdjustSize;
    end;

    Invalidate;
  end;

end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetToolBarControlCount: Integer;
begin
  Result := FATBControls.Count;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetToolBarControls(index: Integer): TControl;
begin
  Result := nil;
  if (Index >= 0) and (Index < FATBControls.Count) then
    Result := FATBControls[Index];
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.IndexOfToolBarControl(
  AControl: TControl): Integer;
begin
  Result := FATBControls.IndexOf(AControl);
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.AddToolBarControl(AControl: TControl): Integer;
var
  i: Integer;
begin
  Result := -1;
  if (AControl <> nil) and (FATBControls.IndexOf(AControl) < 0) and (AControl.Parent <> self) then
  begin
    AControl.Parent := Self;
    i := FATBControls.IndexOf(AControl);
    if i >= 0 then
    begin
      MoveToolBarControl(I, ToolBarControlCount-1);
      Result := ToolBarControlCount-1;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.InsertToolBarControl(Index: integer;
  AControl: TControl);
var
  i: Integer;  
begin
  if {(Index >= 0) and (Index < FATBControls.Count) and} (AControl <> nil) and (FATBControls.IndexOf(AControl) < 0) and (AControl.Parent <> self) then
  begin
    i := AddToolBarControl(AControl);
    MoveToolBarControl(i, Index);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MoveToolBarControl(FromIndex,
  ToIndex: integer);
var
  i: Integer;
  aControl: TControl;
begin
  if (FromIndex >= 0) and (FromIndex < FATBControls.Count) and (ToIndex >= 0) and (ToIndex < FATBControls.Count) and (FromIndex <> ToIndex) then
  begin
    aControl := FATBControls[FromIndex];
    FATBControls.Move(FromIndex, ToIndex);
    
    if not FAutoArrangeButtons and false then
    begin
      i := FRUControls.IndexOf(aControl);
      if (i >= 0) and (ToIndex < FRUControls.Count) then
        FRUControls.Move(i, ToIndex);
    end;

    SetControlsPosition;
    UpdateRULists;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.AddMergedMenuItems;
var
  I, J: Integer;
  MergedItemFound: Boolean;
  ItemsList: TList;
begin
  if FMergedMenu <> nil then
  begin
    ItemsList := TList.Create;
    for I := 0 to FMergedMenu.Items.Count - 1 do
    begin
      MergedItemFound := False;
      for J := 0 to FATBControls.Count - 1 do
      begin
        if (TControl(FATBControls[J]) is TAdvToolBarMenuButton) and (TAdvToolBarMenuButton(FATBControls[J]).FToolBarCreated) and (FMergedMenu.Items[I].GroupIndex > 0)
           and Assigned(TAdvToolBarMenuButton(FATBControls[J]).MenuItem) and (TAdvToolBarMenuButton(FATBControls[J]).MenuItem.GroupIndex = FMergedMenu.Items[I].GroupIndex)
           and (ItemsList.IndexOf(FATBControls[J]) < 0) then
        begin
          TAdvToolBarMenuButton(FATBControls[J]).MenuItem := FMergedMenu.Items[I];
          TAdvToolBarMenuButton(FATBControls[J]).FInternalTag := 1;
          MergedItemFound := True;
          ItemsList.Add(FATBControls[J]);
          Break;
        end;
      end;

      if not MergedItemFound then
      begin
        with TAdvToolBarMenuButton.Create(Self) do
        try
          Grouped := True;
          Parent := Self;
          ShowCaption := true;
          MenuItem := FMergedMenu.Items[I];
          FInternalTag := 1;
          //FToolBarCreated := true;
          AutoSize := True;
        except
          Free;
          raise;
        end;
      end;
    end;
    
  ItemsList.Free;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.DeleteMergedMenuItems;
var
  I: Integer;
begin
  for I := FATBControls.Count - 1 downto 0 do
  begin
    if (TControl(FATBControls[I]) is TAdvToolBarMenuButton) and (TAdvToolBarMenuButton(FATBControls[I]).FInternalTag = 1) then
      TAdvToolBarMenuButton(FATBControls[I]).Free;
  end;
  UpdateMenu;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MergeMenu(AMenu: TMainMenu);
begin
  if (AMenu <> nil) and (Menu <> nil) then
  begin
    if (FMergedMenu <> AMenu) and (FMergedMenu <> Menu) then
    begin
      if FMergedMenu <> nil then
      begin
        //FMerged.FMergedWith := nil;
        DeleteMergedMenuItems;
        FMergedMenu := nil;
      end;
      FMergedMenu := AMenu;
      AddMergedMenuItems;
      FMergedMenu.FreeNotification(Self);
    end;
  end
  else
  begin
    DeleteMergedMenuItems;
    FMergedMenu := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UnmergeMenu(AMenu: TMainMenu);
begin
  if (AMenu <> nil) and (FMergedMenu = AMenu) then
    MergeMenu(nil);
end;

//------------------------------------------------------------------------------
function TAdvCustomToolBar.GetMyParentForm: TCustomForm;
var
  ParentCtrl: TWinControl;
begin
  Result := nil;
  ParentCtrl := self.Parent;
  if Assigned(FCurrentDock) then
    ParentCtrl := FCurrentDock
  else if Assigned(FLastDock) then
    ParentCtrl := FLastDock;

  while Assigned(ParentCtrl) do
  begin
    if ParentCtrl is TCustomForm then
    begin
      Result := TCustomForm(ParentCtrl);
      break;
    end;
    ParentCtrl := ParentCtrl.Parent;
  end;
end;

//------------------------------------------------------------------------------
{ Auto MDI Buttons Support }

var
  MDIToolBar: TAdvCustomToolBar;
  WndProcHooked: Boolean;

function ATBWindowProc(hWnd: HWND; uMsg: Integer; WParam: WPARAM; lParam: LPARAM): LRESULT; {$IFNDEF TMSDOTNET} stdcall; {$ENDIF}
begin
  if Assigned(MDIToolBar) then
  begin
    if (uMsg = WM_WINDOWPOSCHANGED{WM_WINDOWPOSCHANGING}) then
    begin
      //MDIChildForm := TProForm(MDIToolBar.GetMyParentForm).ActiveMDIChild;
      //if Assigned(MDIChildForm) and (MDIChildForm.WindowState = wsMaximized) and MDIToolBar.MDIButtonsVisible and (MDIToolBar.ToolBarState <> tsFloating) then
      //if MDIToolBar.MDIButtonsVisible then
      MDIToolBar.Invalidate;
    end;
  end;
  Result := CallWindowProc(IntPtr(GetWindowLong(hWnd, GWL_USERDATA)), hwnd, uMsg, wParam, lParam);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAutoMDIButtons(const Value: Boolean);
var
  WindowHandle: THandle;
  OldWndProc: Integer;
  MyParentForm: TCustomForm;
begin
  if (Parent is TAdvToolBarPager) and Value and (FAutoMDIButtons <> Value) then
    Exit;

  if (FAutoMDIButtons <> Value) then
  begin
    FAutoMDIButtons := Value;
    if (csDesigning in ComponentState) or (csLoading in ComponentState) then
      Exit;

    if FAutoMDIButtons and FullSize and Assigned(Menu) then
    begin
      MyParentForm := GetMyParentForm;
      if not Assigned(MyParentForm) then
      begin
        FAutoMDIButtons := False;
        Exit;
      end;

      WindowHandle := MyParentForm.Handle;
      if (GetWindowLong(WindowHandle, GWL_WNDPROC) <> Integer(@ATBWindowProc)) then
      begin
        MDIToolBar := Self;
        FMDIChildForm := nil;
        SetWindowLong(WindowHandle, GWL_USERDATA, GetWindowLong(WindowHandle, GWL_WNDPROC));
        SetWindowLong(WindowHandle, GWL_WNDPROC, Integer(@ATBWindowProc));
        WndProcHooked := True;
      end;
    end
    else
    begin
      if WndProcHooked then
      begin // UnHook here
        WndProcHooked := False;
        MDIToolBar := nil;
        FMDIChildForm := nil;

        WindowHandle := GetMyParentForm.Handle;
        OldWndProc := GetWindowLong(WindowHandle, GWL_USERDATA);
        SetWindowRgn(WindowHandle, 0, True);
        if OldWndProc <> 0 then
        begin
          SetWindowLong(WindowHandle, GWL_WNDPROC, OldWndProc);
          SetWindowLong(WindowHandle, GWL_USERDATA, 0);
        end;

        Invalidate;
      end;
      FAutoMDIButtons := False;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetMDIButtonsVisible(const Value: Boolean);
begin
  if (FMDIButtonsVisible <> Value) then
  begin
    FMDIButtonsVisible := Value;
    Invalidate;
  end;

  {  MDIChildForm := TProForm(GetMyParentForm).ActiveMDIChild;
    if Assigned(MDIChildForm) then
    begin
   }
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.DrawMDIButtons;
  procedure DrawCross(R: TRect; Clr: TColor);
  begin
    with Canvas do
    begin
      Pen.Color := Clr;
                     {/}
      MoveTo(R.Left, R.Top + 7);
      LineTo(R.Left + 8, R.Top);
      MoveTo(R.Left + 1, R.Top + 7);
      LineTo(R.Left + 7, R.Top);
                     {\}
      MoveTo(R.Left, R.Top + 1);
      LineTo(R.Left + 8, R.Top + 8);
      MoveTo(R.Left + 1, R.Top + 1);
      LineTo(R.Left + 7, R.Top + 8);
    end;
  end;

  procedure DrawMaximize(R: TRect; Clr: TColor; HorzDir: Boolean);
  begin
    with Canvas do
    begin
      Pen.Color := Clr;

      if HorzDir then
      begin
        MoveTo(R.Left + 2, R.Top);
        LineTo(R.Left + 8, R.Top);
        MoveTo(R.Left + 2, R.Top + 1);
        LineTo(R.Left + 8, R.Top + 1);
        MoveTo(R.Left + 8, R.Top);
        LineTo(R.Left + 8, R.Top + 6);

        MoveTo(R.Left, R.Top + 3);
        LineTo(R.Left + 7, R.Top + 3);
        MoveTo(R.Left, R.Top + 4);
        LineTo(R.Left + 7, R.Top + 4);
        MoveTo(R.Left, R.Top + 4);
        LineTo(R.Left, R.Top + 8);
        LineTo(R.Left + 6, R.Top + 8);
        LineTo(R.Left + 6, R.Top + 4);
      end
      else
      begin
        MoveTo(R.Right - 5, R.Top + 2);
        LineTo(R.Right - 5, R.Top + 8);
        MoveTo(R.Right - 6, R.Top + 2);
        LineTo(R.Right - 6, R.Top + 8);
        MoveTo(R.Right - 5, R.Top + 8);
        LineTo(R.Right - 11, R.Top + 8);

        MoveTo(R.Right - 8, R.Top);
        LineTo(R.Right - 8, R.Top + 7);
        MoveTo(R.Right - 9, R.Top);
        LineTo(R.Right - 9, R.Top + 7);
        MoveTo(R.Right - 9, R.Top);
        LineTo(R.Right - 13, R.Top);
        LineTo(R.Right - 13, R.Top + 6);
        LineTo(R.Right - 9, R.Top + 6);
      end;
    end;

  end;

  procedure DrawMinimize(R: TRect; Clr: TColor; HorzDir: Boolean);
  begin
    with Canvas do
    begin
      Pen.Color := Clr;

      if HorzDir then
      begin
        MoveTo(R.Left, R.Top);
        LineTo(R.Left + 6, R.Top);
        MoveTo(R.Left , R.Top + 1);
        LineTo(R.Left + 6, R.Top + 1);
      end
      else
      begin
        MoveTo(R.Left, R.Top);
        LineTo(R.Left, R.Top + 6);
        MoveTo(R.Left + 1, R.Top);
        LineTo(R.Left + 1, R.Top + 6);
      end;
    end;
  end;

var
  R, R2: TRect;
  Clr, ClrTo, BrClr, GlpClr: TColor;
  GDHoriztl: Boolean;

begin
  FMDIChildForm := GetMyParentForm;
  if Assigned(FMDIChildForm) then
    FMDIChildForm := TProForm(GetMyParentForm).ActiveMDIChild;
    
  if FAutoMDIButtons and Assigned(FMDIChildForm) and (FMDIChildForm.WindowState = wsMaximized){ and FMDIButtonsVisible} and (ToolBarState <> tsFloating) then
  begin
    FMDIButtonsVisible := True;
    // Close Button
    R := self.GetMDICloseBtnRect;
    //Canvas.Draw(R.left, R.Top, FMDICloseGlyph);

    with Canvas, FCurrentToolBarStyler.ButtonAppearance do
    begin
      // Close Button
      if FMDIDownCloseBtn then
      begin
        Clr := ColorDown;
        ClrTo := ColorDownTo;
        BrClr := BorderDownColor;
        GlpClr := clBlack;
        GDHoriztl := GradientDirectionDown = gdHorizontal;
      end
      else if FMDIHotCloseBtn then
      begin
        Clr := ColorHot;
        ClrTo := ColorHotTo;
        BrClr := BorderHotColor;
        GlpClr := clBlack;
        GDHoriztl := GradientDirectionHot = gdHorizontal;
      end
      else
      begin
        Clr := clNone;
        ClrTo := clNone;
        BrClr := clNone;
        GlpClr := clBlack;
        GDHoriztl := GradientDirection = gdHorizontal;
      end;

      // BackGround
      if (Clr <> clNone) and (ClrTo <> clNone) then
        DrawGradient(Canvas, Clr, ClrTo, 40, R, GDHoriztl)
      else if (Clr <> clNone) then
      begin
        Brush.Color := Clr;
        Pen.Color := Clr;
        Rectangle(R);
      end;

      // Border
      if BrClr <> clNone then
      begin
        Brush.Style := bsClear;
        Pen.Color := BrClr;
        Rectangle(R);
      end;

      R2 := R;
      R2.Left := R.Left + ((R.Right - R.Left) - 8) div 2;
      R2.Top := R.Top + ((R.Bottom - R.Top) - 8) div 2;
      DrawCross(R2, GlpClr);

      // Max Button
      R := GetMDIMaxBtnRect;
      if FMDIDownMaxBtn then
      begin
        Clr := ColorDown;
        ClrTo := ColorDownTo;
        BrClr := BorderDownColor;
        GlpClr := clBlack;
        GDHoriztl := GradientDirectionDown = gdHorizontal;
      end
      else if FMDIHotMaxBtn then
      begin
        Clr := ColorHot;
        ClrTo := ColorHotTo;
        BrClr := BorderHotColor;
        GlpClr := clBlack;
        GDHoriztl := GradientDirectionHot = gdHorizontal;
      end
      else
      begin
        Clr := clNone;
        ClrTo := clNone;
        BrClr := clNone;
        GlpClr := clBlack;
        GDHoriztl := GradientDirection = gdHorizontal;
      end;

      // BackGround
      if (Clr <> clNone) and (ClrTo <> clNone) then
        DrawGradient(Canvas, Clr, ClrTo, 40, R, GDHoriztl)
      else if (Clr <> clNone) then
      begin
        Brush.Color := Clr;
        Pen.Color := Clr;
        Rectangle(R);
      end;

      // Border
      if BrClr <> clNone then
      begin
        Brush.Style := bsClear;
        Pen.Color := BrClr;
        Rectangle(R);
      end;

      if not (biMaximize in TProForm(FMDIChildForm).BorderIcons) then
        GlpClr := clGray;

      R2 := R;
      R2.Left := R.Left + ((R.Right - R.Left) - 8) div 2;
      R2.Top := R.Top + ((R.Bottom - R.Top) - 8) div 2;
      DrawMaximize(R2, GlpClr, Position in [daTop, daBottom]);

      // Min Button
      R := GetMDIMinBtnRect;
      if FMDIDownMinBtn then
      begin
        Clr := ColorDown;
        ClrTo := ColorDownTo;
        BrClr := BorderDownColor;
        GlpClr := clBlack;
        GDHoriztl := GradientDirectionDown = gdHorizontal;
      end
      else if FMDIHotMinBtn then
      begin
        Clr := ColorHot;
        ClrTo := ColorHotTo;
        BrClr := BorderHotColor;
        GlpClr := clBlack;
        GDHoriztl := GradientDirectionHot = gdHorizontal;
      end
      else
      begin
        Clr := clNone;
        ClrTo := clNone;
        BrClr := clNone;
        GlpClr := clBlack;
        GDHoriztl := GradientDirection = gdHorizontal;
      end;

      // BackGround
      if (Clr <> clNone) and (ClrTo <> clNone) then
        DrawGradient(Canvas, Clr, ClrTo, 40, R, GDHoriztl)
      else if (Clr <> clNone) then
      begin
        Brush.Color := Clr;
        Pen.Color := Clr;
        Rectangle(R);
      end;

      // Border
      if BrClr <> clNone then
      begin
        Brush.Style := bsClear;
        Pen.Color := BrClr;
        Rectangle(R);
      end;

      R2 := R;
      if Position in [daTop, daBottom] then
      begin
        R2.Left := R.Left + ((R.Right - R.Left) - 6) div 2;
        R2.Top := R.Bottom - 6;
      end
      else
      begin
        R2.Top := R.Top + ((R.Bottom - R.Top) - 6) div 2;
        R2.Left := R.Left + 5;
      end;

      if not (biMinimize in TProForm(FMDIChildForm).BorderIcons) then
        GlpClr := clGray;

      DrawMinimize(R2, GlpClr, Position in [daTop, daBottom]);
    end; // with ends



  end
  else if FMDIButtonsVisible then
    FMDIButtonsVisible := False;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.PtOnMDIClose(P: TPoint): Boolean;
begin
  Result := False;
  if PtInRect(GetMDICloseBtnRect, P) then
    Result := True;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.PtOnMDIMax(P: TPoint): Boolean;
begin
  Result := False;
  if PtInRect(GetMDIMaxBtnRect, P) and Assigned(FMDIChildForm) and (biMaximize in TProForm(FMDIChildForm).BorderIcons) then
    Result := True;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.PtOnMDIMin(P: TPoint): Boolean;
begin
  Result := False;
  if PtInRect(GetMDIMinBtnRect, P) and Assigned(FMDIChildForm) and (biMinimize in TProForm(FMDIChildForm).BorderIcons) then
    Result := True;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetMDICloseBtnRect: TRect;
var
  x, y: Integer;
begin
  Result := Rect(0, 0, 0, 0);
  FMDIChildForm := TProForm(GetMyParentForm).ActiveMDIChild;
  if Assigned(FMDIChildForm) then
  begin
    if (biSystemMenu in TProForm(FMDIChildForm).BorderIcons) then
    begin
      case Position of
        daTop, daBottom:
        begin
          x := Width - 3 - MDIBTNSIZE;
          if ShowOptionIndicator and not FullSize then
            x := x - PopupIndicatorWidth;
          y := max(2, (Height - MDIBTNSIZE) div 2);
          Result := Rect(x, y, x + MDIBTNSIZE, y + MDIBTNSIZE);
        end;
        daLeft, daRight:
        begin
          x := Height - 3 - MDIBTNSIZE;
          if ShowOptionIndicator and not FullSize then
            x := x - PopupIndicatorWidth;
          y := max(2, (Width - MDIBTNSIZE) div 2);
          Result := Rect(y, x, y + MDIBTNSIZE, x + MDIBTNSIZE);
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetMDIMaxBtnRect: TRect;
begin
  Result := Rect(0, 0, 0, 0);
  FMDIChildForm := TProForm(GetMyParentForm).ActiveMDIChild;
  if Assigned(FMDIChildForm) and (ToolBarState <> tsFloating) then
  begin
    if (biSystemMenu in TProForm(FMDIChildForm).BorderIcons) {and (biMaximize in TProForm(FMDIChildForm).BorderIcons)} then
    begin
      case Position of
        daTop, daBottom:
        begin
          Result := GetMDICloseBtnRect;
          Result.Right := Result.Left - 1;
          Result.Left := Result.Right - MDIBTNSIZE;
        end;
        daLeft, daRight:
        begin
          Result := GetMDICloseBtnRect;
          Result.Bottom := Result.Top - 1;
          Result.Top := Result.Bottom - MDIBTNSIZE;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetMDIMinBtnRect: TRect;
begin
  Result := Rect(0, 0, 0, 0);
  FMDIChildForm := TProForm(GetMyParentForm).ActiveMDIChild;
  if Assigned(FMDIChildForm) and (ToolBarState <> tsFloating) then
  begin
    if (biSystemMenu in TProForm(FMDIChildForm).BorderIcons){ and (biMinimize in TProForm(FMDIChildForm).BorderIcons)} then
    begin
      case Position of
        daTop, daBottom:
        begin
          Result := GetMDIMaxBtnRect;
          Result.Right := Result.Left - 1;
          Result.Left := Result.Right - MDIBTNSIZE;
        end;
        daLeft, daRight:
        begin
          Result := GetMDIMaxBtnRect;
          Result.Bottom := Result.Top - 1;
          Result.Top := Result.Bottom - MDIBTNSIZE;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MDICloseBtnClick;
begin
  FMDIChildForm := TProForm(GetMyParentForm).ActiveMDIChild;
  if FAutoMDIButtons and Assigned(FMDIChildForm) and (FMDIChildForm.WindowState = wsMaximized) and FMDIButtonsVisible and (ToolBarState <> tsFloating) then
    FMDIChildForm.Close;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MDIMaxBtnClick;
begin
  FMDIChildForm := TProForm(GetMyParentForm).ActiveMDIChild;
  if FAutoMDIButtons and Assigned(FMDIChildForm) and (FMDIChildForm.WindowState = wsMaximized) and FMDIButtonsVisible and (ToolBarState <> tsFloating)
    and (biMaximize in TProForm(FMDIChildForm).BorderIcons) then
    FMDIChildForm.WindowState := wsNormal;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MDIMinBtnClick;
begin
  FMDIChildForm := TProForm(GetMyParentForm).ActiveMDIChild;
  if FAutoMDIButtons and Assigned(FMDIChildForm) and (FMDIChildForm.WindowState = wsMaximized) and FMDIButtonsVisible and (ToolBarState <> tsFloating)
    and (biMinimize in TProForm(FMDIChildForm).BorderIcons) then
    FMDIChildForm.WindowState := wsMinimized;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCustomizer(
  const Value: TAdvToolBarCustomizer);
begin
  FCustomizer := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.ShowCustomizer;
begin
  if Assigned(FCustomizer) then
  begin
    FCustomizer.ShowCustomizer;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.ResetToolBar;
begin
  if Assigned(FCustomizer) then
    FCustomizer.ResetToolBar;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAutoDockOnClose(const Value: Boolean);
begin
  FAutoDockOnClose := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCaptionPosition(
  const Value: TCaptionPosition);
begin
  if FCaptionPosition <> Value then
  begin
    FCaptionPosition := Value;
    if ShowCaption then
    begin
      SetControlsPosition(False);
      Invalidate;
    end;  
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetShowCaption(const Value: Boolean);
begin
  if (FShowCaption <> Value) then
  begin
    FShowCaption := Value;
    SetControlsPosition(True);
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCaptionAlignment(const Value: TAlignment);
begin
  if (FCaptionAlignment <> Value) then
  begin
    FCaptionAlignment := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMMouseEnter(var Msg: TMessage);
begin
  inherited;
  if (csDesigning in ComponentState) then
    Exit;

  if (Parent is TAdvPage) or (Parent is TCompactWindow) then
  begin
    FHot := true;

    if not Assigned(FTimer) then
    begin
      FTimer := TTimer.Create(self);
      FTimer.OnTimer := TimerProc;
      FTimer.Interval := GlowSpeed;
      FTimer.Enabled := true;
    end;

    FTimeInc := 20;
    Invalidate;
    FGlowState := gsHover;
  end;  
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.TimerProc(Sender: TObject);
var
  i,j: Integer;
  PropInfo: PPropInfo;
begin
  FStepHover := FStepHover + FTimeInc;
  if ((FStepHover > 100) and (FTimeInc > 0))
     or ((FStepHover < 0) and (FTimeInc < 0)) or (FCurrentToolBarStyler.ColorHot.Color = clNone) then
  begin
    FreeAndNil(FTimer);
    if (FStepHover < 0) then
      FGlowState := gsNone;
  end
  else
  begin
    Invalidate;
    // updating Container to maintain transparency
    for i := 0 to FATBControls.Count - 1 do
    begin
      PropInfo := GetPropInfo(TControl(FATBControls[i]).ClassInfo, 'Transparent');

      if (TControl(FATBControls[i]) is TAdvToolBarContainer) or
         (TControl(FATBControls[i]) is TAdvGlowButton) or
         (Pos('AdvOffice', (TControl(FATBControls[i]).ClassName)) > 0) or
         Assigned(PropInfo) then
          TControl(FAtbControls[i]).Invalidate;

      if (TControl(FATBControls[i]) is TAdvToolBarContainer) then
      begin
        for j := 0 to TAdvToolBarContainer(FATBControls[i]).ControlCount - 1 do
        begin
          if TAdvToolBarContainer(FATBControls[i]).Controls[j] is TAdvGlowButton then
            TAdvToolBarContainer(FATBControls[i]).Controls[j].Invalidate;
        end;
      end;
    end;

  end;

  if (FStepHover > 0) then
  for i := 0 to ControlCount  - 1 do
  begin
    if Controls[i] is TAdvToolBarContainer then
    begin
      for j := 0 to (Controls[i] as TAdvToolBarcontainer).ControlCount - 1 do
      begin
        (Controls[i] as TAdvToolBarContainer).Controls[j].Repaint;
      end;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OptionTimerProc(Sender: TObject);
{var
  I: Integer;
  P: TPoint; }
begin
  case FOptionGlowState of
    gsHover:
    begin
      FOptionStepHover := FOptionStepHover + FOptionTimeInc;
      if ((FOptionStepHover > 100) and (FOptionTimeInc > 0))
         or ((FOptionStepHover < 0) and (FOptionTimeInc < 0)) then
      begin
       { if (FOptionStepHover > 100) and (FOptionTimeInc > 0) then
        begin
          FOptionStepHover := 120;
          GetCursorPos(P);
          P := ScreenToClient(P);
          if not PtInRect(GetOptionIndicatorRect, P) then
          begin
            FOptionTimeInc := -20;
            FOptionGlowState := gsHover;
            FCapOptIndicatorHot := False;
            Exit;
          end;
        end
        else if ((FOptionStepHover < 0) and (FOptionTimeInc < 0)) then }
        begin
          FreeAndNil(FOptionTimer);
          FOptionGlowState := gsNone;
          //if Assigned(FAdvToolBarPager) then
            //FAdvToolBarPager.InvalidateTab(-1);
          if (FOptionStepHover < 0) then
          begin
            FCapOptIndicatorHot := False;
            InvalidateCapOptionBtn;
          end;
          InvalidateCaption;
        end;

        FOptionStepPush := 0;
        if (FOptionStepHover > 100) then
          FOptionStepHover := 120;
        if (FOptionStepHover < 0) then
          FOptionStepHover := -20;
      end
      else
        InvalidateCapOptionBtn;
    end;
    gsPush:
    begin
      FOptionStepPush := FOptionStepPush + FOptionTimeInc;
      if ((FOptionStepPush > 100) and (FOptionTimeInc > 0))
         or ((FOptionStepPush < 0) and (FOptionTimeInc < 0)) then
      begin
        FreeAndNil(FOptionTimer);
        FOptionGlowState := gsNone;
        //FOptionStepPush := 0;
        //FOptionStepHover := 0;
        if (FOptionStepPush < 0) then
        begin
          FCapOptIndicatorDown := False;
          InvalidateCaption;
        end;
      end
      else 
        InvalidateCapOptionBtn;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAutoSizeEx(const Value: Boolean);
begin
  if (FAutoSize <> Value) then
  begin
    if not Value then
      if (ToolBarState <> tsFixed) or {not (Self.Parent is TAdvPage)}(Self.Parent is TAdvDockPanel) then
        Exit;
        
    FAutoSize := Value;
    SetControlsPosition();
    if not FAutoSize then
    begin
      Constraints.MinWidth := 0;
      Constraints.MaxWidth := 0;
      Constraints.MinHeight := 0;
      Constraints.MaxHeight := 0;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetOptionDisabledPicture(
  const Value: TGDIPPicture);
begin
  FIOptionDisabledPicture.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetOptionPicture(const Value: TGDIPPicture);
begin
  FIOptionPicture.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnOptionPictureChanged(Sender: TObject);
begin
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAutoPositionControls(const Value: Boolean);
begin
  if (FAutoPositionControls <> Value) then
  begin
    if not Value then
      if (ToolBarState <> tsFixed) or {not(Self.Parent is TAdvPage)}(Self.Parent is TAdvDockPanel) then
        Exit;
  
    FAutoPositionControls := Value;
    if Value then
      SetControlsPosition
    else
      AutoSize := Value;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.InvalidateCapOptionBtn;
var
  R: TRect;
begin
  R := GetOptionIndicatorRect;
  InvalidateRect(Handle, @R, True);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.InvalidateCaption;
var
  R: TRect;
begin
  R := GetCaptionRect;
  InvalidateRect(Handle, @R, True);
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.SetSmallerVariant(CanCompact: Boolean; var NewState: TButtonSizeState; RealSet: Boolean = True): Integer;

  function CheckGlowButtonSizeState(Ctrl: TControl; aState: TButtonSizeState): Boolean;
  begin
    Result := (Ctrl is TAdvCustomGlowButton) and TProCustomGlowButton(Ctrl).AutoSize and
              (TProCustomGlowButton(Ctrl).ButtonSizeState = aState) and
              (TProCustomGlowButton(Ctrl).ButtonSizeState > TProCustomGlowButton(Ctrl).MinButtonSizeState);
  end;

var
  i, j, w1, w2, c: Integer;
  done, V1, V2: Boolean;
begin
  Result := 0;
  if AutoPositionControls and AutoSize and ((Parent is TAdvPage) or (Parent is TCompactWindow)) and not Compact then
  begin
    done := False;
    V1 := FInternalControlPositioning;
    FInternalControlPositioning := True;
    V2 := FInternalControlUpdation;
    FInternalControlUpdation := True;
    GetSequenceControlList(FSeqControlList);
    // search for bsLarge
    for i := FSeqControlList.Count-1 downto 0 do
    begin
      if CheckGlowButtonSizeState(TControl(FSeqControlList[i]), bsLarge) and (i > 0) and CheckGlowButtonSizeState(TControl(FSeqControlList[i-1]), bsLarge) then
      begin
        w1 := 0;
        w2 := 0;
        for j := 0 to TOOLBAR_ROWS-1 do
        begin
          if ((i - j) < 0) then
            break;
          if CheckGlowButtonSizeState(TControl(FSeqControlList[i - j]), bsLarge) then
          begin
            if RealSet then
            begin
              w1 := w1 + TProCustomGlowButton(FSeqControlList[i - j]).Width;
              TProCustomGlowButton(FSeqControlList[i - j]).ButtonSizeState := bsLabel;
              w2 := Max(w2, TProCustomGlowButton(FSeqControlList[i - j]).Width);
            end
            else
            begin
              w1 := w1 + TProCustomGlowButton(FSeqControlList[i - j]).Width;
              w2 := Max(w2, TProCustomGlowButton(FSeqControlList[i - j]).GetButtonSize(bsLabel).cx);
            end;
          end
          else
          begin
            break;
          end;
        end;

        NewState := bsLabel;
        Result := w1 - w2;
        done := True;
        break;
      end;  
    end;

    // search for bsLabel
    if not done then
    begin
      for i := FSeqControlList.Count-1 downto 0 do
      begin
        if CheckGlowButtonSizeState(TControl(FSeqControlList[i]), bsLabel) and (i > 0) and CheckGlowButtonSizeState(TControl(FSeqControlList[i-1]), bsLabel) then
        begin
          w1 := 0;
          w2 := 0;
          c := -1;
          for j := 0 to TOOLBAR_ROWS-1 do
          begin
            if ((i - j) < 0) then
              break;

            if (j = 0) then
              c := TControl(FSeqControlList[i - j]).Left
            else if (c <> TControl(FSeqControlList[i - j]).Left) then
              break;
            if CheckGlowButtonSizeState(TControl(FSeqControlList[i - j]), bsLabel) then
            begin
              if RealSet then
              begin
                w1 := Max(w1, TProCustomGlowButton(FSeqControlList[i - j]).Width);
                TProCustomGlowButton(FSeqControlList[i - j]).ButtonSizeState := bsGlyph;
                w2 := Max(w2, TProCustomGlowButton(FSeqControlList[i - j]).Width);
              end
              else
              begin
                w1 := Max(w1, TProCustomGlowButton(FSeqControlList[i - j]).Width);
                w2 := Max(w2, TProCustomGlowButton(FSeqControlList[i - j]).GetButtonSize(bsGlyph).cx);
              end;
            end
            else
            begin
              break;
            end;
          end;

          NewState := bsGlyph;
          Result := w1 - w2;
          done := True;
          break;
        end;
      end;
    end;

    FInternalControlPositioning := V1;
    FInternalControlUpdation := V2;

    Result := abs(Result);
    if RealSet and done then
    begin
      SetControlsPosition;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.SmallerVariantDifference(CanCompact: Boolean; var NewState: TButtonSizeState): Integer;
begin
  Result := SetSmallerVariant(CanCompact, NewState, False);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetSmallestVaraint;
var
  i: Integer;
  NewState: TButtonSizeState;
begin
  i := SetSmallerVariant(False, NewState);
  while (i > 0) do
  begin
    i := SetSmallerVariant(False, NewState);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetLargestVaraint;
var
  i: Integer;
  NewState: TButtonSizeState;
begin
  i := SetLargerVariant(False, NewState);
  while (i > 0) do
  begin
    i := SetLargerVariant(False, NewState);
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.SetLargerVariant(CanCompact: Boolean; var NewState: TButtonSizeState; RealSet: Boolean = True): Integer;

  function CheckGlowButtonSizeState(Ctrl: TControl; aState: TButtonSizeState): Boolean;
  begin
    Result := (Ctrl is TAdvCustomGlowButton) and TProCustomGlowButton(Ctrl).AutoSize and
              (TProCustomGlowButton(Ctrl).ButtonSizeState = aState) and
              (TProCustomGlowButton(Ctrl).ButtonSizeState < TProCustomGlowButton(Ctrl).MaxButtonSizeState);
  end;

var
  i, j, w1, w2, c: Integer;
  done, V1, V2: Boolean;
begin
  Result := 0;
  if AutoPositionControls and AutoSize and ((Parent is TAdvPage) or (Parent is TCompactWindow)) and not Compact then
  begin
    done := False;
    V1 := FInternalControlPositioning;
    FInternalControlPositioning := True;
    V2 := FInternalControlUpdation;
    FInternalControlUpdation := True;
    GetSequenceControlList(FSeqControlList);
    // search for bsGlyph
    for i := FSeqControlList.Count-1 downto 0 do
    begin
      if CheckGlowButtonSizeState(TControl(FSeqControlList[i]), bsGlyph) and (i > 0) and CheckGlowButtonSizeState(TControl(FSeqControlList[i-1]), bsGlyph) then
      begin
        w1 := 0;
        w2 := 0;
        c := -1;
        for j := 0 to TOOLBAR_ROWS-1 do
        begin
          if ((i - j) < 0) then
            break;

          if (j = 0) then
            c := TControl(FSeqControlList[i - j]).Left
          else if (c <> TControl(FSeqControlList[i - j]).Left) then
            break;

          if CheckGlowButtonSizeState(TControl(FSeqControlList[i - j]), bsGlyph) then
          begin
            if RealSet then
            begin
              w1 := Max(w1, TProCustomGlowButton(FSeqControlList[i - j]).Width);
              TProCustomGlowButton(FSeqControlList[i - j]).ButtonSizeState := bsLabel;
              w2 := Max(w2, TProCustomGlowButton(FSeqControlList[i - j]).Width);
            end
            else
            begin
              w1 := Max(w1, TProCustomGlowButton(FSeqControlList[i - j]).Width);
              w2 := Max(w2, TProCustomGlowButton(FSeqControlList[i - j]).GetButtonSize(bsLabel).cx);
            end;
          end
          else
          begin
            break;
          end;
        end;

        NewState := bsLabel;
        Result := w2 - w1;
        done := True;
        break;
      end;  
    end;

    // search for bsLabel
    if not done then
    begin
      for i := FSeqControlList.Count-1 downto 0 do
      begin
        if CheckGlowButtonSizeState(TControl(FSeqControlList[i]), bsLabel) and (i > 0) and CheckGlowButtonSizeState(TControl(FSeqControlList[i-1]), bsLabel) then
        begin
          w1 := 0;
          w2 := 0;
          for j := 0 to TOOLBAR_ROWS-1 do
          begin
            if ((i - j) < 0) then
              break;
              
            if CheckGlowButtonSizeState(TControl(FSeqControlList[i - j]), bsLabel) then
            begin
              if RealSet then
              begin
                w1 := Max(w1, TProCustomGlowButton(FSeqControlList[i - j]).Width);
                TProCustomGlowButton(FSeqControlList[i - j]).ButtonSizeState := bsLarge;
                w2 := w2 + TProCustomGlowButton(FSeqControlList[i - j]).Width;
              end
              else
              begin
                w1 := Max(w1, TProCustomGlowButton(FSeqControlList[i - j]).Width);
                w2 := w2 + TProCustomGlowButton(FSeqControlList[i - j]).GetButtonSize(bsLarge).cx;
              end;
            end
            else
            begin
              break;
            end;
          end;

          NewState := bsLarge;
          Result := w2 - w1;
          done := True;
          break;
        end;
      end;
    end;

    FInternalControlPositioning := V1;
    FInternalControlUpdation := V2;

    Result := abs(Result);
    if RealSet and done then
    begin
      SetControlsPosition;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.LargerVariantDifference(CanCompact: Boolean; var NewState: TButtonSizeState): Integer;
begin
  Result := SetLargerVariant(CanCompact, NewState, False);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCompactCaption(const Value: string);
begin
  if (FCompactCaption <> Value) then
  begin
    FCompactCaption := Value;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCompactPicture(const Value: TGDIPPicture);
begin
  FICompactPicture.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnCompactPictureChanged(Sender: TObject);
begin
  if FCompact and (FCompactBtn <> nil) then
    FCompactBtn.Picture.Assign(FICompactPicture);
  Invalidate;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetInCompactWidth: Integer;
begin
  Result := Width;
  if FCompact and (Parent is TAdvPage) and (FSelfClone <> nil) then
  begin
    if Assigned(FSelfClone) and FOldAutoPosition and FOldAutoSize and (Parent is TAdvPage) then
    begin
      // First check for ScrollSelector if it has then show smallest variant other wise largest
      if not FCompactSmallest then
      begin
        FSelfClone.SetSmallestVaraint;
        FCompactSmallest := True;
      end;
    end;

    Result := FSelfClone.Width;
  end;  
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetCompactWidth: Integer;
begin
  Result := Width;
  if (Parent is TAdvPage) then
  begin
    Result :=  FCompactMinWidth;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.IsSmallestVariant: Boolean;
begin
  Result := FCompact;  // To be replaced with variant implementation
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateCompactWindow(UpdateSize: Boolean = false);
var
  l, t: Integer;
  aControl: TControl;
  aList: TdbgList;
begin
  if (FSelfClone = nil) then
    Exit;
    
  FSelfClone.ToolBarStyler := Self.ToolBarStyler;
  FSelfClone.FAutoPositionControls := False;
  FSelfClone.FAutoSize := False;
  FSelfClone.AutoArrangeButtons := False;

  FSelfClone.AllowFloating := AllowFloating;
  FSelfClone.AutoOptionMenu := AutoOptionMenu;
  FSelfClone.Caption := Caption;
  FSelfClone.CaptionFont.Assign(CaptionFont);
  FSelfClone.CaptionHeight := CaptionHeight;
  FSelfClone.CaptionPosition := CaptionPosition;
  FSelfClone.CaptionAlignment := CaptionAlignment;
  FSelfClone.ShowRightHandle := ShowRightHandle;
  FSelfClone.ShowClose := ShowClose;
  FSelfClone.ShowOptionIndicator := ShowOptionIndicator;
  FSelfClone.Enabled := Enabled;
  FSelfClone.Images := Images;
  FSelfClone.DisabledImages := DisabledImages;
  FSelfClone.Menu := Menu;
  FSelfClone.ShowHint := ShowHint;
  FSelfClone.Font.Assign(Font);

  if ParentOptionPicture and (Parent is TAdvPage) and (Parent.Parent is TAdvToolBarPager) then
  begin
    FSelfClone.OptionPicture.Assign(TAdvToolBarPager(Parent.Parent).OptionPicture);
    FSelfClone.OptionDisabledPicture.Assign(TAdvToolBarPager(Parent.Parent).OptionDisabledPicture);
  end
  else
  begin
    FSelfClone.OptionPicture.Assign(OptionPicture);
    FSelfClone.OptionDisabledPicture.Assign(OptionDisabledPicture);
  end;
  FSelfClone.ParentOptionPicture := False;
  FSelfClone.OnOptionClick := OnOptionClick;

  if UpdateSize then
  begin
    aList := TdbgList.Create;
    {$IFDEF DELPHI6_LVL}
    aList.Assign(FATBControls);
    {$ELSE}
    aList.AssignList(FATBControls);
    {$ENDIF}

    FSelfClone.Height := Height;
    FSelfClone.Width := Width;

    FSelfClone.ShowCaption := ShowCaption;
    ShowCaption := False;
    // move controls to clone toolbar

    while (self.ControlCount > 1) do
    begin
      aControl := Self.Controls[0];
      if aControl.ClassName <> 'TCompactWindow' then
      begin
        l := aControl.Left;
        t := aControl.Top;
        aControl.Parent := FSelfClone;
        aControl.Top := t;
        aControl.Left := l;
      end;
    end;

    if (FSelfClone.FATBControls.Count = aList.Count) then
    begin
      {$IFDEF DELPHI6_LVL}
      FSelfClone.FATBControls.Assign(aList);
      {$ELSE}
      FSelfClone.FATBControls.AssignList(aList);
      {$ENDIF}
    end;
    aList.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnCompactWindowHide(Sender: TObject);
begin
  PostMessage(Handle, WM_TBCOMPACTWINHIDE, 0, 0);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.HideCompactWindow;
begin
  if (FCompactWindow <> nil) and FCompact and FCompactWindow.Visible then
    FCompactWindow.Hide;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnCompactBtnDropDown(Sender: TObject);
var
  spt: TPoint;
  R: TRect;
  OldV: Boolean;
  {$IFDEF DELPHI6_LVL}
  mon: TMonitor;
  pt: TPoint;
  {$ENDIF}
  {$IFDEF DELPHI9_LVL}
  w, h: Integer;
  {$ENDIF}
begin
  if FCompact then
  begin
    if Assigned(FSelfClone) and FOldAutoPosition and FOldAutoSize and (Parent is TAdvPage) then
    begin
      // First check for ScrollSelector if it has then show smallest variant other wise largest
      if FCompactSmallest then
      begin
        FSelfClone.GetSequenceControlList(FSelfClone.FSeqControlList);
        FSelfClone.AutoPositionControls := FOldAutoPosition;
        FSelfClone.AutoSize := FOldAutoSize;
        FSelfClone.SetLargestVaraint;
        FCompactSmallest := False;
      end;
    end;

    {$IFDEF DELPHI6_LVL}
    pt := Point(Left, Top + Height + 1);
    spt := Parent.ClientToScreen(pt);
    mon := Screen.MonitorFromPoint(spt);
    if Assigned(mon) then
      R := mon.WorkAreaRect
    else
    {$ENDIF}
    begin
  {$IFNDEF TMSDOTNET}
    SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
  {$ENDIF}

  {$IFDEF TMSDOTNET}
    SystemParametersInfo(SPI_GETWORKAREA, 0, R, 0);
  {$ENDIF}
    end;

    //if R.Bottom < (spt.Y + FCompactWindow.Height + 2) then
      //spt.Y := spt.Y - ((spt.Y + FCompactWindow.Height + 2) - R.Bottom);

    FCompactWindow.DropDownButton := Sender as TAdvGlowButton;
    //FCompactWindow.Parent := self;
    FCompactWindow.SetWindowSize;

    if (R.Right < spt.X + FCompactWindow.Width) and (R.Right > spt.X) then
    begin
      spt.X := spt.X - ((spt.X + FCompactWindow.Width) - R.Right);
    end;
    FCompactWindow.Left := spt.X;
    FCompactWindow.Top := spt.Y;

    OldV := True;
    if (Parent is TAdvPage) and (Parent.Parent is TMinimizedRibbonWindow) then
    begin
      OldV := TMinimizedRibbonWindow(Parent.Parent).HideOnDeActivate;
      TMinimizedRibbonWindow(Parent.Parent).HideOnDeActivate := False;
    end;  

    {$IFDEF DELPHI9_LVL}
    w := FCompactWindow.Width;
    h := FCompactWindow.Height;
    FCompactWindow.Width := 0;
    FCompactWindow.Height := 0;
    {$ENDIF}

    FCompactWindow.Visible := True;
    {$IFDEF DELPHI9_LVL}
    FCompactWindow.Left := spt.X;
    FCompactWindow.Top := spt.Y;
    FCompactWindow.Width := w;
    FCompactWindow.Height := h;
    {$ENDIF}
    FCompactWindow.SetCornersRounded;

    if (Parent is TAdvPage) and (Parent.Parent is TMinimizedRibbonWindow) then
      TMinimizedRibbonWindow(Parent.Parent).HideOnDeActivate := OldV;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.CanUnCompact: Boolean;
begin
  Result := not FCompactMode;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCompactMode(const Value: Boolean);
begin
  if (Value <> FCompact) and (Parent is TAdvPage) then
  begin
    if Value then
    begin
      SetCompact(Value);
      FCompactMode := Value;
    end
    else
    begin
      FCompactMode := Value;
      SetCompact(Value);
    end;
    TAdvPage(Parent).UpdateAllToolBars;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCompact(const Value: Boolean);
var
  l, t: Integer;
  aControl: TControl;
  bmp: TBitMap;
  ms: TMemoryStream;
  aList: TdbgList;
begin
  if (FCompact <> Value) and (Parent is TAdvPage) and (FPropertiesLoaded) and (not FCompactMode) then
  begin
    {FOldAutoPosition := Self.AutoPositionControls;
    AutoPositionControls := False;
    FOldAutoSize := Self.AutoSize;
    Self.AutoSize := False;
    FOldAutoArrangeButtons := Self.AutoArrangeButtons;
    AutoArrangeButtons := False;}

    if Value then
    begin
      FCompactChanging := True;
      
      FOldAutoPosition := Self.AutoPositionControls;
      FOldAutoSize := Self.AutoSize;
      FOldAutoArrangeButtons := Self.AutoArrangeButtons;
      AutoPositionControls := False;
      Self.AutoSize := False;
      AutoArrangeButtons := False;

      if (FCompactWindow = nil) then
      begin
        FCompactWindow := TCompactWindow.CreateNew(self);
        if Name <> '' then //give it a name for debugging
          FCompactWindow.Name := Name + '_CompactWindow';
        FCompactWindow.Parent := Self;   
        //FCompactWindow.Parent := self.GetMyParentForm;
        FCompactWindow.BorderIcons := [];
        FCompactWindow.BorderStyle := bsNone;
        FCompactWindow.Ctl3D := false;
        FCompactWindow.FormStyle := fsStayOnTop;
        FCompactWindow.Visible := False;
        FCompactWindow.Width := 30;
        FCompactWindow.Height := 30;
        FCompactWindow.AutoScroll := False;
        FCompactWindow.BorderWidth := 0;
        FCompactWindow.OnCloseQuery := FOnCompactCloseQuery;
        //FCompactWindow.OnHide := OnOptionWindowHide;
      end;

      if (FSelfClone = nil) then
      begin
        FSelfClone := TAdvCustomToolBar.Create(FCompactWindow);
        if Name <> '' then //give it a name for debugging
          FSelfClone.Name := Name + '_SelfClone';
        FSelfClone.Parent := FCompactWindow;     // set it nil to avoid issue
        FSelfClone.FSelfClone := Self;

        if Assigned(Self.OnDblClick) then
          FSelfClone.OnDblClick := Self.OnDblClick;
        if Assigned(Self.OnKeyPress) then
          FSelfClone.OnKeyPress := Self.OnKeyPress;
        if Assigned(Self.OnKeyDown) then
          FSelfClone.OnKeyDown := Self.OnKeyDown;
        if Assigned(Self.OnKeyUp) then
          FSelfClone.OnKeyUp := Self.OnKeyUp;
      end;
      FCompactWindow.AdvToolBar := FSelfClone;
      FCompactWindow.SetWindowSize;

      // FCompactWindow.Visible := true;

      UpdateCompactWindow(True);
      //FSelfClone.FATBControls.Assign(FATBControls);

      Self.Width := GetCompactWidth;

      FCompactBtn := TAdvGlowButton.Create(Self);
      FCompactBtn.Parent := Self;
      FCompactBtn.FocusType := ftNone;
      FCompactBtn.Picture.Assign(FICompactPicture);
      if (FICompactPicture.Empty) and Assigned(Self.Images) and (CompactImageIndex >= 0) then
      begin
        if (Self.Images is TImageList) then
        begin
          FCompactBtn.Images := TImageList(Self.Images);
          FCompactBtn.ImageIndex := CompactImageIndex;
          FCompactBtn.Picture.Assign(nil);
        end
        else
        begin
          bmp := TBitmap.Create;
          if (Self.Enabled) or not Assigned(DisabledImages) then
          begin
            bmp.Height := Images.Height;
            bmp.Width := Images.Width;
            bmp.TransparentColor := clWhite;
            bmp.TransparentMode := tmAuto;
            bmp.PixelFormat := pf24bit;
            Images.Draw(bmp.Canvas, 0, 0, CompactImageIndex, self.Enabled);
          end
          else
          begin
            bmp.Height := DisabledImages.Height;
            bmp.Width := DisabledImages.Width;
            bmp.TransparentColor := clWhite;
            bmp.TransparentMode := tmAuto;
            bmp.PixelFormat := pf24bit;
            DisabledImages.Draw(bmp.Canvas, 0, 0, CompactImageIndex, True);
          end;
          ms := TMemoryStream.Create;
          bmp.SaveToStream(ms);
          FCompactBtn.Picture.LoadFromStream(ms);
          FCompactBtn.ImageIndex := -1;
          ms.Free;
          bmp.Free;
        end;
      end;
      FCompactBtn.Caption := FCompactCaption;
      FCompactBtn.WideCaption := WideCompactCaption;
      FCompactBtn.Width := FCompactMinWidth;
      FCompactBtn.Height := Self.Height;
      FCompactBtn.Left := 0;
      FCompactBtn.Top := 0;
      FCompactBtn.Visible := True;
      FCompactBtn.Layout := blGlyphTop;
      FCompactBtn.Appearance.Assign(FCurrentToolBarStyler.CompactGlowButtonAppearance);
      FCompactBtn.DropDownButton := True;
      FCompactBtn.DropDownPosition := dpBottom;
      FCompactBtn.DropDownSplit := false;
      FCompactBtn.OfficeHint.Assign(OfficeHint);
      FCompactBtn.OnClick := OnCompactBtnDropDown;
      FCompactBtn.Style := bsCheck;
      FCompactBtn.ShortCutHint := CompactShortCutHint;
      FCompactBtn.ShortCutHintPos := shpBelowBottomCenter;
      FCompactChanging := False;
      FCompact := Value;

      if not (csDesigning in ComponentState) and (Parent <> nil) and (Parent is TAdvPage) then
      begin
        //TProCustomGlowButton(FCompactBtn).OnInternalKeyDown := OnCompactButtonKeyDown;
        //TProCustomGlowButton(FCompactBtn).OnSetButtonSize := OnSetGlowButtonSize;
      end;

    end
    else
    begin
      FCompactChanging := True;

      aList := TdbgList.Create;
      {$IFDEF DELPHI6_LVL}
      aList.Assign(FSelfClone.FATBControls);
      {$ELSE}
      aList.AssignList(FSelfClone.FATBControls);
      {$ENDIF}
      Self.Width := GetInCompactWidth;
      ShowCaption := FSelfClone.ShowCaption;
      AutoPositionControls := False;
      Self.AutoSize := False;
      AutoArrangeButtons := False;

      FCompactBtn.Free;
      FCompactBtn := nil;

      while (FSelfClone.ControlCount > 0) do
      begin
        aControl := FSelfClone.Controls[0];
        l := aControl.Left;
        t := aControl.Top;
        aControl.Parent := Self;
        aControl.Left := l;
        aControl.Top := t;
      end;

      if (FATBControls.Count = aList.Count) then
      begin
        {$IFDEF DELPHI6_LVL}
        FATBControls.Assign(aList);
        {$ELSE}
        FATBControls.AssignList(aList);
        {$ENDIF}
      end;

      if (FCompactWindow <> nil) then
      begin
        FSelfClone.ToolBarStyler := nil;
        FSelfClone.Free;
        FCompactWindow.Free;
        FCompactWindow := nil;
        FSelfClone := nil;
      end;
      FCompact := Value;
      Self.AutoPositionControls := FOldAutoPosition;
      Self.AutoSize := FOldAutoSize;
      Self.AutoArrangeButtons := FOldAutoArrangeButtons;
      aList.Free;
      FCompactChanging := False;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateCompactButton;
begin
  if Compact and Assigned(FCompactBtn) and Assigned(FCurrentToolBarStyler) then
  begin
    FCompactBtn.Appearance.Assign(FCurrentToolBarStyler.CompactGlowButtonAppearance);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetOfficeHint(const Value: TAdvHintInfo);
begin
  FOfficeHint.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetAntiAlias(const Value: TAntiAlias);
begin
  FAntiAlias := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMDialogKey(var Message: TCMDialogKey);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMEnabledChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.AnyDroppedDownButton: Boolean;
  function CheckDroppedDownChildren(Ctrl: TWinControl): Boolean;
  var
    i: Integer;
  begin
    if (Ctrl is TAdvCustomGlowButton) then
    begin
      if TProCustomGlowButton(Ctrl).DroppedDown then
      begin
        Result := True;
        Exit;
      end;
    end;

    Result := False;
    for i:= 0 to Ctrl.ControlCount-1 do
    begin
      if (TControl(Ctrl.Controls[i]) is TWinControl) then
      begin
        Result := CheckDroppedDownChildren(TWinControl(Ctrl.Controls[i]));
        if Result then
          Break;
      end;
    end;
  end;
var
  i: Integer;
begin
  Result := False;
  for i:= 0 to FATBControls.Count-1 do
  begin
    if (TControl(FATBControls[i]) is TWinControl) then
    begin
      Result := CheckDroppedDownChildren(TWinControl(FATBControls[i]));
      if Result then
        Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.CMFocusChanged(var Message: TCMFocusChanged);
var
  //i: Integer;
  OldActive: Boolean;
  //TabOrderList: TDbgList;
  Ctrl: TWinControl;
  //h: HWND;
begin
  inherited;
  if (Message.Sender = Self) and (FATBControls.Count > 0){and (TControl(FATBControls[0]) is TWinControl)} then
  begin  // get first Tab control
    {TabOrderList := TDbgList.Create;
    GetTabOrderList(TabOrderList);
    if (TabOrderList.Count > 0) and (TControl(TabOrderList.Items[0]) is TWinControl) and TWinControl(TabOrderList.Items[0]).CanFocus then
      TWinControl(TabOrderList.Items[0]).SetFocus;
    TabOrderList.Free; }
    Ctrl := GetFirstTabControl(True);
    if (Ctrl <> nil) and (Ctrl.CanFocus) then
    begin
      if not (Parent is TCompactWindow) then
        Ctrl.SetFocus;
    end;
  end;

  OldActive := FActive;
  FActive := False;
  {   //--- commented this, as toolbar should only be ht when mouse over it. 
  for i:= 0 to FATBControls.Count-1 do
  begin
    if (TControl(FATBControls[i]) is TWinControl) then
    begin
      if TWinControl(FATBControls[i]).Focused then
      begin
        FActive := True;
        Break;
      end;
    end;
  end;

  if not FActive and (Message.Sender <> Self) and (self.HandleAllocated) then
  begin
    h := GetFocus;
    i := 1;
    while (h <> 0) do
    begin
      if (h = self.Handle) then
      begin
        FActive := True;
        Break;
      end;
      h := GetParent(h);
      inc(i);
      if (i > 50) then
        Break;
    end;
  end;
  }
  if (FActive <> OldActive) then
    InvalidateTransparentControls;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetControlFromHandle(H: HWnd): TWinControl;
var
  i: Integer;
begin
  Result := nil;
  for i:= 0 to FATBControls.Count-1 do
  begin
    if (TControl(FATBControls[i]) is TWinControl) then
    begin
      if TWinControl(FATBControls[i]).HandleAllocated and (TWinControl(FATBControls[i]).Handle = H) then
      begin
        Result := TWinControl(FATBControls[i]);
        Break;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetFirstTabControl(CheckCanFocus: Boolean): TWinControl;
var
  i: Integer;
  TabOrderList: TDbgList;
begin
  Result := nil;
  if FCompact and (FCompactBtn <> nil) then
  begin
    if FCompactBtn.CanFocus then
      Result := FCompactBtn;
  end
  else
  begin
    TabOrderList := TDbgList.Create;
    GetTabOrderList(TabOrderList);
    for i:= 0 to TabOrderList.Count-1 do
    begin
      if (TControl(TabOrderList.Items[i]) is TWinControl) and not (TControl(TabOrderList.Items[i]) is THintWindow)
         and not (TControl(TabOrderList.Items[i]) is TCompactWindow) and not (TControl(TabOrderList.Items[i]) is TAdvCustomToolBar)
         and (not CheckCanFocus or TWinControl(TabOrderList.Items[i]).CanFocus) then
      begin
        Result := TWinControl(TabOrderList.Items[i]);
        Break;
      end;
    end;
    TabOrderList.Free;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetLastTabControl(CheckCanFocus: Boolean): TWinControl;
var
  i: Integer;
  TabOrderList: TDbgList;
begin
  Result := nil;
  if FCompact and (FCompactBtn <> nil) then
  begin
    if FCompactBtn.CanFocus then
      Result := FCompactBtn;
  end
  else
  begin
    TabOrderList := TDbgList.Create;
    GetTabOrderList(TabOrderList);
    for i:= TabOrderList.Count-1 downto 0 do
    begin
      if (TControl(TabOrderList.Items[i]) is TWinControl) and not (TControl(TabOrderList.Items[i]) is THintWindow)
         and not (TControl(TabOrderList.Items[i]) is TCompactWindow) and not (TControl(TabOrderList.Items[i]) is TAdvCustomToolBar)
         and (not CheckCanFocus or TWinControl(TabOrderList.Items[i]).CanFocus) then
      begin
        Result := TWinControl(TabOrderList.Items[i]);
        Break;
      end;
    end;
    TabOrderList.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnGlowButtonKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
  Ctrl: TWinControl;
  TabOrderList: TDbgList;
  i: Integer;
begin
  if (Sender is TWinControl) then
  begin

    if Assigned(Parent) and (Parent is TAdvPage) then
    begin
      if TAdvPage(Parent).FToolBarShortCutShowing then
      begin
        if not (Key in [48..57, 65..90, 97..122]) then
        begin
          TAdvPage(Parent).HideShortCutHintOfAllToolBars;

          // Redisplay KeyTips for all Tabs
          if (key = VK_ESCAPE) and Assigned(TAdvPage(Parent).AdvToolBarPager) then
          begin
            TAdvPage(Parent).AdvToolBarPager.ShowShortCutHintOfAllPages;
          end;
        end;

        // Key in [VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN, VK_ESCAPE]
        if (Key in [48..57, 65..90, 97..122]) then
        begin
          TAdvPage(Parent).FShortCutChars := TAdvPage(Parent).FShortCutChars + char(key);
          if TAdvPage(Parent).HasShortCut(TAdvPage(Parent).FShortCutChars) then
            TAdvPage(Parent).HideShortCutHintOfAllToolBars;
        end;
      end;
      //if (TAdvPage(Parent).FShortCutHint <> nil) then
        //TAdvPage(Parent).HideShortCutHintOfAllToolBars;
      if (Key = VK_ESCAPE) then
      begin
        if Assigned(TAdvPage(Parent).AdvToolBarPager) and TAdvPage(Parent).AdvToolBarPager.IsFloatingRibbonShowing then
          TAdvPage(Parent).AdvToolBarPager.HideFloatingRibbon;
      end;
    end;

    case (Key) of
      VK_LEFT:
      begin
        TabOrderList := TDbgList.Create;
        GetTabOrderList(TabOrderList);
        RemoveNonFocusCtrlFromList(TabOrderList);
        i := TabOrderList.IndexOf(TWinControl(Sender));
        if (i = 0) and Assigned(Parent) and (Parent is TAdvPage) then  // First Control
        begin
          TabOrderList.Clear;
          TAdvPage(Parent).GetSequencialToolBarList(TabOrderList);
          i := TabOrderList.IndexOf(Self);
          if (i > 0) then
          begin
            //TAdvToolBar(TabOrderList.Items[i-1]).SetFocus;
            Ctrl := TAdvToolBar(TabOrderList.Items[i-1]).getLastTabControl(True);
            if (Ctrl <> nil) and Ctrl.CanFocus then
              Ctrl.SetFocus;
          end
          else if (i = 0) then
          begin
            Ctrl := TAdvToolBar(TabOrderList.Items[TabOrderList.Count-1]).getLastTabControl(True);
            if (Ctrl <> nil) and Ctrl.CanFocus then
              Ctrl.SetFocus;
          end;
        end
        else if (i > 0) then
        begin
          //Ctrl := FindNextControl(TWinControl(Sender), False, False, True);
          Ctrl := TabOrderList.Items[i-1];
          if Assigned(Ctrl) and Ctrl.CanFocus then
          begin
            Ctrl.SetFocus;
          end;
        end;
        TabOrderList.Free;
      end;
      VK_RIGHT:
      begin
        TabOrderList := TDbgList.Create;
        GetTabOrderList(TabOrderList);
        RemoveNonFocusCtrlFromList(TabOrderList);
        i := TabOrderList.IndexOf(TWinControl(Sender));
        if (i = TabOrderList.Count-1) and Assigned(Parent) and (Parent is TAdvPage) then  // Last Control
        begin
          TabOrderList.Clear;
          TAdvPage(Parent).GetSequencialToolBarList(TabOrderList);
          i := TabOrderList.IndexOf(Self);
          if (i >= 0) and (i < TabOrderList.Count-1) then
          begin
            //TAdvToolBar(TabOrderList.Items[i+1]).SetFocus;
            Ctrl := TAdvToolBar(TabOrderList.Items[i+1]).getFirstTabControl(True);
            if (Ctrl <> nil) and Ctrl.CanFocus then
              Ctrl.SetFocus;
          end
          else if (i = TabOrderList.Count-1) and (i >= 0) then
          begin
            Ctrl := TAdvToolBar(TabOrderList.Items[0]).getFirstTabControl(True);
            if (Ctrl <> nil) and Ctrl.CanFocus then
              Ctrl.SetFocus;
          end;
        end
        else if (i >= 0) then
        begin
          //Ctrl := FindNextControl(TWinControl(Sender), True, False, True);
          Ctrl := TabOrderList.Items[i+1];
          if Assigned(Ctrl) and Ctrl.CanFocus then
          begin
            Ctrl.SetFocus;
          end;
        end;
      end;
      VK_UP, VK_ESCAPE:
      begin
        if Assigned(Parent) and (Parent is TAdvPage) and Assigned(Parent.Parent) and (Parent.Parent is TAdvToolBarPager) then
        begin
          TAdvToolBarPager(Parent.Parent).SetFocus;
        end;
      end;
      VK_DOWN:
      begin
      
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.HasShortCut(aShortCut: String; var VisibleHintCount: Integer): Boolean;

  function HasShortCutInChildControls(ParentCtrl: TWinControl): Boolean;
  var
    i: integer;
    sub: String;
  begin
    Result := False;
    if (ParentCtrl = nil) or not ParentCtrl.Enabled or not ParentCtrl.Visible or (not ParentCtrl.Showing) then
      Exit;

    if (ParentCtrl is TAdvCustomGlowButton) then
    begin
      if (UpperCase(TAdvCustomGlowButton(ParentCtrl).ShortCutHint) = UpperCase(aShortCut)) then
      begin
        TAdvCustomGlowButton(ParentCtrl).SetFocus;
        TAdvCustomGlowButton(ParentCtrl).Repaint;
        TProCustomGlowButton(ParentCtrl).InternalClick;
        Result := True;
      end
      else if (Length(TAdvCustomGlowButton(ParentCtrl).ShortCutHint) > 0) then
      begin
        sub := Copy(TAdvCustomGlowButton(ParentCtrl).ShortCutHint, 1, Length(aShortCut));
        if (UpperCase(sub) <> UpperCase(aShortCut)) then
        begin
          TAdvCustomGlowButton(ParentCtrl).HideShortCutHint;
        end
        else
        begin
          Inc(VisibleHintCount);
        end;
      end;
    end
    else
    begin
      for i := 0 to ParentCtrl.ControlCount - 1 do
      begin
        if (ParentCtrl.Controls[i] is TWinControl) and TWinControl(ParentCtrl.Controls[i]).Enabled and TWinControl(ParentCtrl.Controls[i]).Visible then
        begin
          Result := HasShortCutInChildControls(TWinControl(ParentCtrl.Controls[i]));
          if Result then
            Break;
        end;
      end;
    end;
  end;
var
  i: Integer;
  sub: String;
  OldV: Boolean;
begin
  Result := False;
  for i:= 0 to FATBControls.Count-1 do
  begin
    if (TControl(FATBControls[i]) is TAdvCustomGlowButton) then
    begin
      if (UpperCase(TAdvCustomGlowButton(FATBControls[i]).ShortCutHint) = UpperCase(aShortCut)) then
      begin
        if TAdvCustomGlowButton(FATBControls[i]).Visible then
        begin
          if (TAdvCustomGlowButton(FATBControls[i]).Enabled) then
          begin
            OldV := True;
            if (TAdvCustomGlowButton(FATBControls[i]) = FCompactBtn) and (Parent is TAdvPage) and (Parent.Parent is TMinimizedRibbonWindow) then
            begin
              OldV := TMinimizedRibbonWindow(Parent.Parent).HideOnDeActivate;
              TMinimizedRibbonWindow(Parent.Parent).HideOnDeActivate := False;
            end;

            TAdvCustomGlowButton(FATBControls[i]).SetFocus;
            TAdvCustomGlowButton(FATBControls[i]).Repaint;
            //TAdvCustomGlowButton(FATBControls[i]).Click;
            TProCustomGlowButton(FATBControls[i]).InternalClick;
            Result := True;

            if (TAdvCustomGlowButton(FATBControls[i]) <> FCompactBtn) and (Self.Parent is TAdvPage) and Assigned(TAdvPage(Parent).AdvToolBarPager) and (TAdvPage(Parent).AdvToolBarPager.IsFloatingRibbonShowing) then
            begin
              TAdvPage(Parent).AdvToolBarPager.HideFloatingRibbon;
            end;

            if Assigned(FSelfClone) and Compact and (Self.Parent is TAdvPage) then
            begin
              FSelfClone.ShowShortCutHintOfButtons;
              FSelfClone.FCompactShortCutHintShowing := True;
              FSelfClone.SetFocus;
            end;

            if (TAdvCustomGlowButton(FATBControls[i]) = FCompactBtn) and (Parent is TAdvPage) and (Parent.Parent is TMinimizedRibbonWindow) then
              TMinimizedRibbonWindow(Parent.Parent).HideOnDeActivate := OldV;

            Break;
          end;  
        end;  
      end
      else if (Length(TAdvCustomGlowButton(FATBControls[i]).ShortCutHint) > 0) then
      begin
        sub := Copy(TAdvCustomGlowButton(FATBControls[i]).ShortCutHint, 1, Length(aShortCut));
        if (UpperCase(sub) <> UpperCase(aShortCut)) then
        begin
          TAdvCustomGlowButton(FATBControls[i]).HideShortCutHint;
        end
        else
        begin
          Inc(VisibleHintCount);
        end;
      end;
    end
    else if (TControl(FATBControls[i]) is TWinControl) then
    begin
      Result := HasShortCutInChildControls(TWinControl(FATBControls[i]));
      if Result then
        Break;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.InvalidateTransparentControls;
var
  i: Integer;
  PropInfo: PPropInfo;
begin
  Invalidate;
  // updating Container to maintain transparency
  for i := 0 to FATBControls.Count - 1 do
  begin
    PropInfo := GetPropInfo(TControl(FATBControls[i]).ClassInfo, 'Transparent');

    if (TControl(FATBControls[i]) is TAdvToolBarContainer) or
       (TControl(FATBControls[i]) is TAdvGlowButton) or
       (Pos('AdvOffice', (TControl(FATBControls[i]).ClassName)) > 0) or
       Assigned(PropInfo) then
        TControl(FAtbControls[i]).Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.HideShortCutHintOfButtons;
  procedure HideHintOfChildControls(ParentCtrl: TWinControl);
  var
    i: integer;
  begin
    if (ParentCtrl = nil) {or (ContainsControl(ParentCtrl))} or (not ParentCtrl.Showing) then
      Exit;

    if (ParentCtrl is TAdvCustomGlowButton) then
    begin
      TAdvCustomGlowButton(ParentCtrl).HideShortCutHint;
    end
    else
    begin
      for i := 0 to ParentCtrl.ControlCount - 1 do
      begin
        if (ParentCtrl.Controls[i] is TWinControl) then
          HideHintOfChildControls(TWinControl(ParentCtrl.Controls[i]));
      end;
    end;
  end;
  
var
  i: Integer;
begin
  for i := 0 to FATBControls.Count - 1 do
  begin
    if (TControl(FATBControls[i]) is TAdvCustomGlowButton) then
      TAdvCustomGlowButton(FATBControls[i]).HideShortCutHint
    else if (TControl(FATBControls[i]) is TWinControl) then
    begin
      HideHintOfChildControls(TWinControl(FATBControls[i]));
    end;
  end;
  
  FCompactShortCutHintShowing := False;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.ShowShortCutHintOfButtons;


  procedure ShowHintOfChildControls(ParentCtrl: TWinControl);
  var
    i: integer;
  begin
    if (ParentCtrl = nil) or not ParentCtrl.Enabled or not ParentCtrl.Visible or (not ParentCtrl.Showing) then
      Exit;

    if (ParentCtrl is TAdvCustomGlowButton) then
    begin
      TAdvCustomGlowButton(ParentCtrl).ShowShortCutHint;
    end
    else
    begin
      for i := 0 to ParentCtrl.ControlCount - 1 do
      begin
        if (ParentCtrl.Controls[i] is TWinControl) and TWinControl(ParentCtrl.Controls[i]).Enabled and TWinControl(ParentCtrl.Controls[i]).Visible then
          ShowHintOfChildControls(TWinControl(ParentCtrl.Controls[i]));
      end;
    end;
  end;

var
  i: Integer;
begin
  for i := 0 to FATBControls.Count - 1 do
  begin
    if (TObject(FATBControls[i]) is TControl) and (TControl(FATBControls[i]).Enabled) and (TControl(FATBControls[i]).Visible) then
    begin
      if (TControl(FATBControls[i]) is TAdvCustomGlowButton) then
        TAdvCustomGlowButton(FAtbControls[i]).ShowShortCutHint
      else if (TControl(FATBControls[i]) is TWinControl) then
      begin
        ShowHintOfChildControls(TWinControl(FATBControls[i]));
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBar.GetToolBarState: TToolBarState;
begin
  Result := FToolBarState;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetParentOptionPicture(const Value: Boolean);
begin
  if (FParentOptionPicture <> Value) then
  begin
    FParentOptionPicture := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.SetCompactImageIndex(const Value: Integer);
begin
  if (FCompactImageIndex <> Value) then
  begin
    FCompactImageIndex := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.Update;
begin
  inherited;
  SetControlsPosition;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.BeginUpdate;
begin
  if not Visible then
    Exit;
    
  Inc(FUpdateCount);
  SendMessage(Handle,WM_SETREDRAW,integer(False),0);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.EndUpdate;
begin
  if not Visible then
    Exit;

  if FUpdateCount > 0 then Dec(FUpdateCount);
  if FUpdateCount = 0 then
  begin
    SendMessage(Handle,WM_SETREDRAW,integer(True),0);
    InvalidateRect(Handle, Nil, False);
    //NCPaintProc;
    SetControlsPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnGlowButtonClick(Sender: TObject);
begin
  HideOptionWindow;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnSetGlowButtonSize(Sender: TObject; var W, H: Integer);
begin
  if (Sender is TAdvCustomGlowButton)then
  begin
    if (AutoPositionControls or (FOldAutoPosition and IsCompact)) and (TProCustomGlowButton(Sender).ButtonSizeState = bsLarge) then
    begin
      H := Self.Height - (Self.CaptionHeight + 5);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateButtonRowCount;
var
  i: Integer;
begin
  if Assigned(Parent) and (Parent is TAdvPage) and Assigned(Parent.Parent) and ((Parent.Parent is TAdvToolBarPager) or (Parent.Parent is TMinimizedRibbonWindow)) then
  begin
    FButtonRows[1] := -100;
    FButtonRows[2] := -100;
    FButtonRows[3] := -100;
    for i:= 0 to FATBControls.Count - 1 do
    begin
      if (TControl(FATBControls[i]).Top >= 0) and TControl(FATBControls[i]).Visible then
      begin
        if (FButtonRows[1] < 0) then
          FButtonRows[1] := TControl(FATBControls[i]).Top
        else if not ((TControl(FATBControls[i]).Top >= FButtonRows[1] - 4) and (TControl(FATBControls[i]).Top <= FButtonRows[1] + 4)) then
        begin
          if (FButtonRows[2] < 0) then
            FButtonRows[2] := TControl(FATBControls[i]).Top
          else if not ((TControl(FATBControls[i]).Top >= FButtonRows[2] - 4) and (TControl(FATBControls[i]).Top <= FButtonRows[2] + 4)) then
          begin
            if (FButtonRows[3] < 0) then
              FButtonRows[3] := TControl(FATBControls[i]).Top;
          end;
        end;
      end;
    end;

    if (FButtonRows[1] > FButtonRows[2]) and (FButtonRows[2] > 0) then
    begin
      i := FButtonRows[2];
      FButtonRows[2] := FButtonRows[1];
      FButtonRows[1] := i;
    end;

    if (FButtonRows[2] > FButtonRows[3]) and (FButtonRows[2] > 0) and (FButtonRows[3] > 0) then
    begin
      i := FButtonRows[3];
      FButtonRows[3] := FButtonRows[2];
      FButtonRows[2] := i;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.OnGetGlowButtonShortCutHintPos(Sender: TObject;
  ButtonSizeState: TButtonSizeState;
  var ShortCutHintPosition: TShortCutHintPos);
var
  rc: Integer;
begin
  if (ShortCutHintPosition <> shpAuto) or not (Sender is TControl) then
    Exit;

  if (TControl(Sender).Height >= Height - CaptionHeight - 15) then
    ShortCutHintPosition := shpBottom
  else //if (ButtonSizeState in [bsGlyph, bsLabel]) then
  begin
    if (FButtonRows[3] > 0) then
      rc := 3
    else
      rc := 2;

    if (FButtonRows[1] > 0) and ((TControl(Sender).Top >= FButtonRows[1] - 4) and (TControl(Sender).Top <= FButtonRows[1] + 4)) then
    begin
      if (rc <= 2) then
        ShortCutHintPosition := shpAboveTopLeft
      else
        ShortCutHintPosition := shpTopLeft
    end
    else if (FButtonRows[2] > 0) and ((TControl(Sender).Top >= FButtonRows[2] - 4) and (TControl(Sender).Top <= FButtonRows[2] + 4)) then
    begin
      if (rc <= 2) then
        ShortCutHintPosition := shpBelowBottomLeft
      else
        ShortCutHintPosition := shpLeft
    end
    else
    begin
      ShortCutHintPosition := shpBottomLeft;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.MoveUpInRUList(aControl: TControl);
begin
  UpControlInRUL(aControl);
  UpdateRULists;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBar.UpdateControlsVisibility;
begin
  if not FInternalControlPositioning then
  begin
    if FCompact then
    begin
      if Assigned(FSelfClone) and not (csLoading in ComponentState) and not (csDesigning in ComponentState) and FOldAutoPosition and FOldAutoSize and (Parent is TAdvPage) and not FCompactChanging and not FSelfClone.FCompactChanging then
      begin
        // First check for ScrollSelector if it has then show smallest variant other wise largest
        if FCompactSmallest then
        begin
          FSelfClone.GetSequenceControlList(FSelfClone.FSeqControlList);
          FSelfClone.AutoPositionControls := FOldAutoPosition;
          FSelfClone.AutoSize := FOldAutoSize;
          SendMessage(Parent.Handle,WM_SIZE,0,0);
        end;
      end;
    end;  
  end;
end;

//------------------------------------------------------------------------------

{ TRowCollectionItem }

constructor TRowCollectionItem.Create(Collection: TCollection);
begin
  inherited;
  FToolBarList := TDbgList.Create;
end;

//------------------------------------------------------------------------------

destructor TRowCollectionItem.Destroy;
begin
  if Assigned(TRowCollection(Collection).OnDeleteItem) then
    TRowCollection(Collection).OnDeleteItem(TRowCollection(Collection), Index);

  FToolBarList.Free;
  inherited;
end;

//------------------------------------------------------------------------------

function TRowCollectionItem.AddToolBar(
  aAdvToolBar: TAdvCustomToolBar): integer;
var
  OldValue: boolean;
  S: integer;
begin
  Result := -1;
  if FToolBarList.IndexOf(aAdvToolBar) < 0 then
  begin
    if IsAllowed(aAdvToolBar) then
    begin
      Result := FToolBarList.Add(aAdvToolBar);
      OldValue := aAdvToolBar.AllowBoundChange;
      aAdvToolBar.AllowBoundChange := true;

      if TAdvDockPanel(TRowCollection(Collection).FOwner).Align in [daTop, daBottom] then
      begin
        if aAdvToolBar.FullSize then
        begin
          S := (RowRect.Right - RowRect.Left) - TRowCollection(Collection).OffSetX * 2;
          aAdvToolBar.Constraints.MinWidth := 0;
          aAdvToolBar.Constraints.MaxWidth := S;
          aAdvToolBar.Constraints.MinWidth := S;
          aAdvToolBar.Width := S;
          aAdvToolBar.UpdateRULists;   // Since Min/MaxWidth Changes Height Internally, does not call SetBound
        end
        else
        begin
          if Result > 0 then
            aAdvToolBar.Left := TAdvCustomToolBar(FToolBarList[Result - 1]).Left + TAdvCustomToolBar(FToolBarList[Result - 1]).width + TRowCollection(Collection).OffSetX
          else
            aAdvToolBar.Left := (RowRect.Left + TRowCollection(Collection).OffSetX);
            //aAdvToolBar.Left := RowRect.Right - (aAdvToolBar.Width + TRowCollection(Collection).OffSetX);
        end;
      end
      else // daLeft, daRight
      begin
        if aAdvToolBar.FullSize then
        begin
          S := (RowRect.Bottom - RowRect.Top) - TRowCollection(Collection).OffSetX * 2;
          aAdvToolBar.Constraints.MinHeight := 0;
          aAdvToolBar.Constraints.MaxHeight := S;
          aAdvToolBar.Constraints.MinHeight := S;
          aAdvToolBar.Height := S;
          aAdvToolBar.UpdateRULists;  // Since Min/MaxHeight Changes Height Internally, does not call SetBound
        end
        else
        begin
          if Result > 0 then
            aAdvToolBar.Top := TAdvCustomToolBar(FToolBarList[Result - 1]).Top + TAdvCustomToolBar(FToolBarList[Result - 1]).Height + TRowCollection(Collection).OffSetX
          else
            aAdvToolBar.Top := RowRect.Bottom - (aAdvToolBar.Height + TRowCollection(Collection).OffSetX);
        end;
      end;

      aAdvToolBar.AllowBoundChange := OldValue;
      aAdvToolBar.Row := index;

      TRowCollection(Collection).SetRowsPosition;
      //ArrangeToolBars;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TRowCollectionItem.GetHeight: integer;
var
  i: integer;
begin
  Result := DEFAULT_TOOLBARHEIGHT;
  for i := 0 to FToolBarList.count - 1 do
  begin  
    if TRowCollection(Collection).FOwner.Align in [daTop, daBottom] then
      Result := max(Result, TAdvCustomToolBar(FToolBarList[i]).Height)
    else
      Result := max(Result, TAdvCustomToolBar(FToolBarList[i]).Width);
  end;
end;

//------------------------------------------------------------------------------

function TRowCollectionItem.GetRowRect: TRect;
begin
  Result := FRowRect;
end;

//------------------------------------------------------------------------------

procedure TRowCollectionItem.ArrangeToolBars; // FRowRect should already been set before this method call
var
  i, {x, dif,} j, k: integer;
  EmptySpace, expw, shkw, emptsp2: integer;
  aAdvToolBar, atb: TAdvCustomToolBar;
  OldValue: Boolean;
begin
  if TRowCollection(Collection).FOwner.Align in [daTop, daBottom] then
  begin
   { EmptySpace:= TRowCollection(Collection).OffSetX;
    for i:=0 to FToolBarList.Count-1 do
    begin
      EmptySpace:= EmptySpace + TAdvCustomToolBar(FToolBarList[i]).Width + TRowCollection(Collection).OffSetX;
    end;

    if EmptySpace < (FRowRect.Right - FRowRect.Left) then
      EmptySpace:= (FRowRect.Right - FRowRect.Left) - EmptySpace
    else
      EmptySpace:= 0;  }

    //x:= TAdvDockPanel(TRowCollection(Collection).Owner).OffSetX + TRowCollection(Collection).OffSetX;
    for i := 0 to FToolBarList.Count - 1 do
    begin
      // Setting Top
      aAdvToolBar := TAdvCustomToolBar(FToolBarList[i]);
      OldValue := aAdvToolBar.AllowBoundChange;
      aAdvToolBar.AllowBoundChange := true;
      aAdvToolBar.Top := FRowRect.Top; //+ TRowCollection(Collection).OffSetY;
      if aAdvToolBar.Row <> Index then
        aAdvToolBar.Row := Index;
      aAdvToolBar.AllowBoundChange := OldValue;

      if (i = 0) and aAdvToolBar.FullSize then
      begin
        OldValue := aAdvToolBar.AllowBoundChange;
        aAdvToolBar.AllowBoundChange := true;
        //expw := (FRowRect.Right - FRowRect.Left) - TRowCollection(Collection).OffSetX * 2 + 4;
        expw := (FRowRect.Right - FRowRect.Left) - TRowCollection(Collection).OffSetX * 2;
        aAdvToolBar.Constraints.MinWidth := 0;
        aAdvToolBar.Constraints.MaxWidth := expw;
        aAdvToolBar.Constraints.MinWidth := expw;
        //aAdvToolBar.Left := FRowRect.Left -2; //+ TRowCollection(Collection).OffSetX;
        aAdvToolBar.Left := FRowRect.Left + TRowCollection(Collection).OffSetX;
        aAdvToolBar.Width := expw;
        aAdvToolBar.AllowBoundChange := OldValue;
        Break;
      end;

     (* if TAdvCustomToolBar(FToolBarList[i]).Left < x then
      begin
        if EmptySpace = 0 then
        begin
          if i > 0 then
          begin
           { if TAdvCustomToolBar(FToolBarList[i-1]).CanShrink > 0 then
            begin
              expw:= 0;
              for j:= i to FToolBarList.Count-1 do
              begin
                expw:= expw + TAdvCustomToolBar(FToolBarList[j]).CanExpand;
              end;

              dif:= min(min(TAdvCustomToolBar(FToolBarList[i-1]).CanShrink, expw), x - TAdvCustomToolBar(FToolBarList[i]).Left);

            end
            else
              TAdvCustomToolBar(FToolBarList[i]).Left:= x; }
          end
          else
            TAdvCustomToolBar(FToolBarList[i]).Left:= x;
        end
        else
          TAdvCustomToolBar(FToolBarList[i]).Left:= x;
      end
      else if TAdvCustomToolBar(FToolBarList[i]).Left > x then
      begin

      end;
      *)
      //TAdvCustomToolBar(FToolBarList[i]).Width
      //TAdvCustomToolBar(FToolBarList[i]).Left:= x;   // this has to be changed


      if i = FToolBarList.Count - 1 then
        EmptySpace := GetSpace(aAdvToolBar, nil)
      else
        EmptySpace := GetSpace(aAdvToolBar, TAdvCustomToolBar(FToolBarList[i + 1]));

      // Expand Width If empty space next to it, of its and remaining of all its previous ToolBars
      if EmptySpace > 0 then
      begin
        for j := i downto 0 do
        begin
          atb := TAdvCustomToolBar(FToolBarList[j]);
          expw := min(atb.CanExpand, EmptySpace);

          if expw > 0 then
          begin
            OldValue := atb.AllowBoundChange;
            atb.AllowBoundChange := true;
            atb.Width := atb.Width + expw;
            atb.AllowBoundChange := OldValue;

            // moving right to adjust expand width
            for k := j + 1 to i do
            begin
              atb := TAdvCustomToolBar(FToolBarList[k]);
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Left := atb.Left + expw;
              atb.AllowBoundChange := OldValue;
            end;
          end;

          EmptySpace := EmptySpace - expw;
          if EmptySpace <= 0 then
            Break;

        end;

        // (Fix) Expand Width If empty space next to it, of all its Next ToolBars
        if (EmptySpace > 0) then
        begin
          for j := i + 1 to FToolBarList.Count - 1  do
          begin
            atb := TAdvCustomToolBar(FToolBarList[j]);
            expw := min(atb.CanExpand, EmptySpace);

            if expw > 0 then
            begin
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Width := atb.Width + expw;
              atb.AllowBoundChange := OldValue;

              // moving right to adjust expand width
              for k := j + 1 to i do
              begin
                atb := TAdvCustomToolBar(FToolBarList[k]);
                OldValue := atb.AllowBoundChange;
                atb.AllowBoundChange := true;
                atb.Left := atb.Left + expw;
                atb.AllowBoundChange := OldValue;
              end;
            end;

            EmptySpace := EmptySpace - expw;
            if EmptySpace <= 0 then
              Break;

          end;

        end;

      end
      else if EmptySpace < 0 then // If -ve empty space then cover empty space on the left
      begin
        for j := i downto 0 do
        begin
          atb := TAdvCustomToolBar(FToolBarList[j]);
          if j > 0 then
            emptsp2 := GetSpace(TAdvCustomToolBar(FToolBarList[j - 1]), atb)
          else
            emptsp2 := GetSpace(nil, atb);

          emptsp2 := min(emptsp2, abs(EmptySpace));

          if emptsp2 > 0 then
          begin
            OldValue := atb.AllowBoundChange;
            atb.AllowBoundChange := true;
            atb.Left := atb.Left - emptsp2;
            atb.AllowBoundChange := OldValue;

            // moving Left to make space
            for k := j + 1 to i do
            begin
              atb := TAdvCustomToolBar(FToolBarList[k]);
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Left := atb.Left - emptsp2;
              atb.AllowBoundChange := OldValue;
            end;

            EmptySpace := EmptySpace + emptsp2; // Note: EmptySpace is -ve
          end;

          if EmptySpace >= 0 then
            break;
        end;

        // If further Space required then shrink Left side ToolBars
        if EmptySpace < 0 then
        begin
          for j := i downto 0 do
          begin
            atb := TAdvCustomToolBar(FToolBarList[j]);

            shkw := min(atb.CanShrink, abs(EmptySpace));

            if shkw > 0 then
            begin
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Width := atb.Width - shkw;
              atb.AllowBoundChange := OldValue;

              // moving Left to make space
              for k := j + 1 to i do
              begin
                atb := TAdvCustomToolBar(FToolBarList[k]);
                OldValue := atb.AllowBoundChange;
                atb.AllowBoundChange := true;
                atb.Left := atb.Left - shkw;
                atb.AllowBoundChange := OldValue;
              end;

              EmptySpace := EmptySpace + shkw; // Note: EmptySpace is -ve
            end;

            if EmptySpace >= 0 then
              break;
          end;


        end;
      end;

      // if ToolBar is Shrunk the check for the empty space on the left.
      expw := aAdvToolBar.CanExpand;
      if expw > 0 then
      begin
        for j := i downto 0 do
        begin
          atb := TAdvCustomToolBar(FToolBarList[j]);
          if j > 0 then
            emptsp2 := GetSpace(TAdvCustomToolBar(FToolBarList[j - 1]), atb)
          else
            emptsp2 := GetSpace(nil, atb);

          emptsp2 := min(emptsp2, expw);

          if emptsp2 > 0 then
          begin
            OldValue := atb.AllowBoundChange;
            atb.AllowBoundChange := true;
            atb.Left := atb.Left - emptsp2;
            atb.AllowBoundChange := OldValue;

            // moving Left to make space
            for k := j + 1 to i do
            begin
              atb := TAdvCustomToolBar(FToolBarList[k]);
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Left := atb.Left - emptsp2;
              atb.AllowBoundChange := OldValue;
            end;

            atb := TAdvCustomToolBar(FToolBarList[j]);
            OldValue := atb.AllowBoundChange;
            atb.AllowBoundChange := true;
            atb.width := atb.width + emptsp2;
            atb.AllowBoundChange := OldValue;

            expw := expw - emptsp2;
          end;

          if expw <= 0 then
            break;
        end;
      end;

      //x:= x + TRowCollection(Collection).OffSetX + TAdvCustomToolBar(FToolBarList[i]).Width;
    end;

    // checking for the over lapping and cutting ToolBars
    for i := 0 to FToolBarList.Count - 1 do
    begin
      aAdvToolBar := TAdvCustomToolBar(FToolBarList[i]);
      if (i = 0) then    // Checking First ToolBar Front Edge
      begin
        EmptySpace := GetSpace(nil, aAdvToolBar);
        if EmptySpace < 0 then
        begin
          atb := TAdvCustomToolBar(FToolBarList[i]);
          OldValue := atb.AllowBoundChange;
          atb.AllowBoundChange := true;
          atb.Left := atb.Left + abs(EmptySpace);
          atb.AllowBoundChange := OldValue;
        end;
      end;

      if i = FToolBarList.Count - 1 then       // Last or the only ToolBar
      begin
        EmptySpace := GetSpace(aAdvToolBar, nil);
        // checking for cutting last AdvToolBar
        if EmptySpace < 0 then // If -ve empty space the cover empty space on the left
        begin
          for j := i downto 0 do
          begin
            atb := TAdvCustomToolBar(FToolBarList[j]);
            if j > 0 then
              emptsp2 := GetSpace(TAdvCustomToolBar(FToolBarList[j - 1]), atb)
            else
              emptsp2 := GetSpace(nil, atb);

            emptsp2 := min(emptsp2, abs(EmptySpace));

            if emptsp2 > 0 then
            begin
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Left := atb.Left - emptsp2;
              atb.AllowBoundChange := OldValue;

              // moving Left to make space
              for k := j + 1 to i do
              begin
                atb := TAdvCustomToolBar(FToolBarList[k]);
                OldValue := atb.AllowBoundChange;
                atb.AllowBoundChange := true;
                atb.Left := atb.Left - emptsp2;
                atb.AllowBoundChange := OldValue;
              end;

              EmptySpace := EmptySpace + emptsp2; // Note: EmptySpace is -ve
            end;

            if EmptySpace >= 0 then
              break;
          end;

          // If further Space required then shrink Left side ToolBars
          if EmptySpace < 0 then
          begin
            for j := i downto 0 do
            begin
              atb := TAdvCustomToolBar(FToolBarList[j]);

              shkw := min(atb.CanShrink, abs(EmptySpace));

              if shkw > 0 then
              begin
                OldValue := atb.AllowBoundChange;
                atb.AllowBoundChange := true;
                atb.Width := atb.Width - shkw;
                atb.AllowBoundChange := OldValue;

                // moving Left to make space
                for k := j + 1 to i do
                begin
                  atb := TAdvCustomToolBar(FToolBarList[k]);
                  OldValue := atb.AllowBoundChange;
                  atb.AllowBoundChange := true;
                  atb.Left := atb.Left - shkw;
                  atb.AllowBoundChange := OldValue;
                end;

                EmptySpace := EmptySpace + shkw; // Note: EmptySpace is -ve
              end;

              if EmptySpace >= 0 then
                break;
            end;

          end;
        end;

        EmptySpace := 0;
        atb := nil;
      end
      else
      begin
        atb := TAdvCustomToolBar(FToolBarList[i + 1]);
        EmptySpace := GetSpace(aAdvToolBar, atb);
      end;

      if (EmptySpace < 0) and (atb <> nil) then
      begin
        OldValue := atb.AllowBoundChange;
        atb.AllowBoundChange := true;
        atb.Left := atb.Left + abs(EmptySpace);
        atb.AllowBoundChange := OldValue;
      end;
    end;

  end
  else // if Position in [daLeft, daRight] then
  begin
   { for i:=0 to FToolBarList.Count-1 do
    begin
      TAdvCustomToolBar(FToolBarList[i]).Left:= FRowRect.Left + TRowCollection(Collection).OffSetY;
    end;
    }

    for i := 0 to FToolBarList.Count - 1 do
    begin
      // Setting Left
      aAdvToolBar := TAdvCustomToolBar(FToolBarList[i]);
      OldValue := aAdvToolBar.AllowBoundChange;
      aAdvToolBar.AllowBoundChange := true;
      aAdvToolBar.Left := FRowRect.Left;
      if aAdvToolBar.Row <> Index then
        aAdvToolBar.Row := Index;
      aAdvToolBar.AllowBoundChange := OldValue;

      if (i = 0) and aAdvToolBar.FullSize then
      begin
        OldValue := aAdvToolBar.AllowBoundChange;
        aAdvToolBar.AllowBoundChange := true;
        expw := (FRowRect.Bottom - FRowRect.Top) - TRowCollection(Collection).OffSetX * 2;
        aAdvToolBar.Constraints.MinHeight := 0;
        aAdvToolBar.Constraints.MaxHeight := expw;
        aAdvToolBar.Constraints.MinHeight := expw;
        aAdvToolBar.Top := FRowRect.Top + TRowCollection(Collection).OffSetX;
        aAdvToolBar.Height := expw;
        aAdvToolBar.AllowBoundChange := OldValue;

        break;
      end;

      if i = FToolBarList.Count - 1 then
        EmptySpace := GetSpace(aAdvToolBar, nil)
      else
        EmptySpace := GetSpace(aAdvToolBar, TAdvCustomToolBar(FToolBarList[i + 1]));

      // Expand Height If empty space next to it, of its and remaining of all its previous ToolBars
      if EmptySpace > 0 then
      begin
        for j := i downto 0 do
        begin
          atb := TAdvCustomToolBar(FToolBarList[j]);
          expw := min(atb.CanExpand, EmptySpace);

          if expw > 0 then
          begin
            OldValue := atb.AllowBoundChange;
            atb.AllowBoundChange := true;
            //if (atb.Height + expw) = 100 then
              //showmessage('This is1:'+inttostr(atb.Height + expw));
            atb.Height := atb.Height + expw;
            atb.AllowBoundChange := OldValue;

            // moving Down to adjust expand Height
            for k := j + 1 to i do
            begin
              atb := TAdvCustomToolBar(FToolBarList[k]);
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Top := atb.Top + expw;
              atb.AllowBoundChange := OldValue;
            end;
          end;

          EmptySpace := EmptySpace - expw;
          if EmptySpace <= 0 then
            Break;

        end;

        // TODO: if required, Expand Height If empty space next to it, of all its Next ToolBars
        
      end
      else if EmptySpace < 0 then // If -ve empty space then cover empty space on the Top
      begin
        for j := i downto 0 do
        begin
          atb := TAdvCustomToolBar(FToolBarList[j]);
          if j > 0 then
            emptsp2 := GetSpace(TAdvCustomToolBar(FToolBarList[j - 1]), atb)
          else
            emptsp2 := GetSpace(nil, atb);

          emptsp2 := min(emptsp2, abs(EmptySpace));

          if emptsp2 > 0 then
          begin
            OldValue := atb.AllowBoundChange;
            atb.AllowBoundChange := true;
            atb.Top := atb.Top - emptsp2;
            atb.AllowBoundChange := OldValue;

            // moving Left to make space
            for k := j + 1 to i do
            begin
              atb := TAdvCustomToolBar(FToolBarList[k]);
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Top := atb.Top - emptsp2;
              atb.AllowBoundChange := OldValue;
            end;

            EmptySpace := EmptySpace + emptsp2; // Note: EmptySpace is -ve
          end;

          if EmptySpace >= 0 then
            break;
        end;

        // If further Space required then shrink Top ToolBars
        if EmptySpace < 0 then
        begin
          for j := i downto 0 do
          begin
            atb := TAdvCustomToolBar(FToolBarList[j]);

            shkw := min(atb.CanShrink, abs(EmptySpace));

            if shkw > 0 then
            begin
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Height := atb.Height - shkw;
              atb.AllowBoundChange := OldValue;

              // moving up to make space
              for k := j + 1 to i do
              begin
                atb := TAdvCustomToolBar(FToolBarList[k]);
                OldValue := atb.AllowBoundChange;
                atb.AllowBoundChange := true;
                atb.Top := atb.Top - shkw;
                atb.AllowBoundChange := OldValue;
              end;

              EmptySpace := EmptySpace + shkw; // Note: EmptySpace is -ve
            end;

            if EmptySpace >= 0 then
              break;
          end;


        end;
      end;

      // if ToolBar is Shrunk the check for the empty space on Top.
      expw := aAdvToolBar.CanExpand;
      if expw > 0 then
      begin
        for j := i downto 0 do
        begin
          atb := TAdvCustomToolBar(FToolBarList[j]);
          if j > 0 then
            emptsp2 := GetSpace(TAdvCustomToolBar(FToolBarList[j - 1]), atb)
          else
            emptsp2 := GetSpace(nil, atb);

          emptsp2 := min(emptsp2, expw);

          if emptsp2 > 0 then
          begin
            OldValue := atb.AllowBoundChange;
            atb.AllowBoundChange := true;
            atb.Top := atb.Top - emptsp2;
            atb.AllowBoundChange := OldValue;

            // moving up to make space
            for k := j + 1 to i do
            begin
              atb := TAdvCustomToolBar(FToolBarList[k]);
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Top := atb.Top - emptsp2;
              atb.AllowBoundChange := OldValue;
            end;

            atb := TAdvCustomToolBar(FToolBarList[j]);
            OldValue := atb.AllowBoundChange;
            atb.AllowBoundChange := true;
            //if (atb.Height + emptsp2) = 100 then
              //showmessage('This is2: '+inttostr(atb.Height)+' '+ inttostr(emptsp2)+' MH'+inttostr(atb.Constraints.MaxHeight));
            atb.Height := atb.Height + emptsp2;
            atb.AllowBoundChange := OldValue;

            expw := expw - emptsp2;
          end;

          if expw <= 0 then
            break;
        end;
      end;

    end;

    // checking for the over lapping and cutting ToolBars
    for i := 0 to FToolBarList.Count - 1 do
    begin
      aAdvToolBar := TAdvCustomToolBar(FToolBarList[i]);
      if (i = 0) then    // Checking First ToolBar Front Edge
      begin
        EmptySpace := GetSpace(nil, aAdvToolBar);
        if EmptySpace < 0 then
        begin
          atb := TAdvCustomToolBar(FToolBarList[i]);
          OldValue := atb.AllowBoundChange;
          atb.AllowBoundChange := true;
          atb.Top := atb.Top + abs(EmptySpace);
          atb.AllowBoundChange := OldValue;
        end;
      end;

      if i = FToolBarList.Count - 1 then
      begin
        EmptySpace := GetSpace(aAdvToolBar, nil);
        // checking for cutting last AdvToolBar
        if EmptySpace < 0 then // If -ve empty space the cover empty space on the Top
        begin
          for j := i downto 0 do
          begin
            atb := TAdvCustomToolBar(FToolBarList[j]);
            if j > 0 then
              emptsp2 := GetSpace(TAdvCustomToolBar(FToolBarList[j - 1]), atb)
            else
              emptsp2 := GetSpace(nil, atb);

            emptsp2 := min(emptsp2, abs(EmptySpace));

            if emptsp2 > 0 then
            begin
              OldValue := atb.AllowBoundChange;
              atb.AllowBoundChange := true;
              atb.Top := atb.Top - emptsp2;
              atb.AllowBoundChange := OldValue;

              // moving Left to make space
              for k := j + 1 to i do
              begin
                atb := TAdvCustomToolBar(FToolBarList[k]);
                OldValue := atb.AllowBoundChange;
                atb.AllowBoundChange := true;
                atb.Top := atb.Top - emptsp2;
                atb.AllowBoundChange := OldValue;
              end;

              EmptySpace := EmptySpace + emptsp2; // Note: EmptySpace is -ve
            end;

            if EmptySpace >= 0 then
              break;
          end;

          // If further Space required then shrink Top ToolBars
          if EmptySpace < 0 then
          begin
            for j := i downto 0 do
            begin
              atb := TAdvCustomToolBar(FToolBarList[j]);

              shkw := min(atb.CanShrink, abs(EmptySpace));

              if shkw > 0 then
              begin
                OldValue := atb.AllowBoundChange;
                atb.AllowBoundChange := true;
                atb.Height := atb.Height - shkw;
                atb.AllowBoundChange := OldValue;

                // moving up to make space
                for k := j + 1 to i do
                begin
                  atb := TAdvCustomToolBar(FToolBarList[k]);
                  OldValue := atb.AllowBoundChange;
                  atb.AllowBoundChange := true;
                  atb.Top := atb.Top - shkw;
                  atb.AllowBoundChange := OldValue;
                end;

                EmptySpace := EmptySpace + shkw; // Note: EmptySpace is -ve
              end;

              if EmptySpace >= 0 then
                break;
            end;

          end;
        end;

        EmptySpace := 0;
        atb := nil;
      end
      else
      begin
        atb := TAdvCustomToolBar(FToolBarList[i + 1]);
        EmptySpace := GetSpace(aAdvToolBar, atb);
      end;

      if (EmptySpace < 0) and (atb <> nil) then
      begin
        OldValue := atb.AllowBoundChange;
        atb.AllowBoundChange := true;
        atb.Top := atb.Top + abs(EmptySpace);
        atb.AllowBoundChange := OldValue;
      end;
    end;

  end; // end of daLeft, daRight
end;

//------------------------------------------------------------------------------

procedure TRowCollectionItem.SetRowRect(R: TRect);
begin
  FRowRect := R;
end;

//------------------------------------------------------------------------------
{
Rules:
 Allow towards Left when
   *) if self is not full size
   *) there is empty space on left side
   *) if No empty space on the row then allow that much that
      any toolbar is expandable on right(self included) and any tool bar is shrinkale on left
      so that no empty space happened.

 Allow towards Right when
   *) if self is not full size
   *) there is empty space on Right side
   *) if No empty space on the row then allow that much that
      any toolbar is Shrinkable on right(self included) and any tool bar is expandable on left
      so that no empty space happened.
}

procedure TRowCollectionItem.SetToolBarLeftAndWidth(
  aAdvToolBar: TAdvCustomToolBar; var ALeft, AWidth: integer);
var
  tbIdx, exp, i, TotalLeft, TotalWidth: integer;
  OldValue: boolean;
  L, EmptSp, j, k, M: integer;
  ATb: TAdvCustomToolBar;

  function TotalExpand(ToolBarIndex: integer; TowardsRight: boolean): integer;
  var
    i: integer;
  begin
    Result := 0;
    if TowardsRight then
    begin
      for i := ToolBarIndex to FToolBarList.Count - 1 do
        Result := Result + TAdvCustomToolBar(FToolBarList[i]).CanExpand;
    end
    else
    begin
      for i := ToolBarIndex - 1 downto 0 do
        Result := Result + TAdvCustomToolBar(FToolBarList[i]).CanExpand;
    end;
  end;

begin
  tbIdx := FToolBarList.IndexOf(aAdvToolBar);
  if tbIdx < 0 then
    raise exception.Create('Invalid ToolBar Index');

  //dif:= 0;
  //exp:= 0;
  if TAdvDockPanel(TRowCollection(Collection).FOwner).Align in [daTop, daBottom] then
  begin
    if aAdvToolBar.Left > ALeft then // Towards Left
    begin
    
      if (ALeft < (RowRect.Left + TRowCollection(Collection).OffSetX)) then
        ALeft := (RowRect.Left + TRowCollection(Collection).OffSetX);

      TotalLeft := aAdvToolBar.Left - ALeft;
     { if (ALeft <= (RowRect.Left + TRowCollection(Collection).OffSetX)) then
      begin
        if tbIdx = 0 then
          ALeft := RowRect.Left + TRowCollection(Collection).OffSetX
        else
          ALeft := aAdvToolBar.Left;
      end
      else} if (tbIdx = 0) then
      begin
        //do nothing
      end
      else if (tbIdx > 0) then
      begin
           // Covering Empty space on the Left
        for i := tbIdx downto 0 do
        begin
          ATb := TAdvCustomToolBar(FToolBarList[i]);
          if i > 0 then
            EmptSp := GetSpace(TAdvCustomToolBar(FToolBarList[i - 1]), ATb)
          else
            EmptSp := GetSpace(nil, ATb);

          if EmptSp > 0 then
          begin
            //move Atb left to Available and required space
            L := min(EmptSp, TotalLeft);
            TotalLeft := TotalLeft - L;
            for j := i to tbIdx do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[j]);
              OldValue := ATb.AllowBoundChange;
              ATb.AllowBoundChange := true;
              ATb.Left := ATb.Left - L;
              ATb.AllowBoundChange := OldValue;
            end;
          end;
          if TotalLeft <= 0 then
            break;
        end;


        if TotalLeft > 0 then
        begin
          EmptSp := 0;
          // checking empty space on the right
          for i := tbIdx to FToolBarList.Count - 1 do
          begin
            ATb := TAdvCustomToolBar(FToolBarList[i]);
            if i < FToolBarList.Count - 1 then
              EmptSp := GetSpace(ATb, TAdvCustomToolBar(FToolBarList[i + 1]))
            else
              EmptSp := GetSpace(ATb, nil);
          end;

          // if not empty space and left further required then shrink Left ToolBars
          if EmptSp <= 0 then
          begin
            for i := tbIdx - 1 downto 0 do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[i]);
              L := min(TotalLeft, ATb.CanShrink);

              L := min(L, TotalExpand(tbIdx, true)); // TotalExpand toward Right

              TotalLeft := TotalLeft - L;

              if L > 0 then
              begin
                // Shrink ToolBar
                OldValue := ATb.AllowBoundChange;
                ATb.AllowBoundChange := true;
                ATb.Width := ATb.Width - L;
                ATb.AllowBoundChange := OldValue;

                // Updating Left On Shrink
                for j := i + 1 to tbIdx - 1 do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[j]);
                  OldValue := ATb.AllowBoundChange;
                  ATb.AllowBoundChange := true;
                  ATb.Left := ATb.Left - L;
                  ATb.AllowBoundChange := OldValue;
                end;

                // Expand ToolBars
                for k := tbIdx to FToolBarList.Count - 1 do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[k]);
                  exp := min(L, ATb.CanExpand);
                  if (exp > 0) then
                  begin
                    OldValue := ATb.AllowBoundChange;
                    ATb.AllowBoundChange := true;
                    ATb.Width := ATb.Width + exp;
                    //if k > tbIdx then
                    ATb.Left := ATb.Left - exp;
                    ATb.AllowBoundChange := OldValue;

                    //----- Fix Space and overlap toolbar iss
                    for j := k - 1 downto tbIdx + 1 do
                    begin
                      ATb := TAdvCustomToolBar(FToolBarList[j]);
                      OldValue := ATb.AllowBoundChange;
                      ATb.AllowBoundChange := true;
                      ATb.Left := ATb.Left - exp;
                      ATb.AllowBoundChange := OldValue;
                    end;
                    //-----
                  end;

                  L := L - exp;
                  if L <= 0 then
                    break;
                end;
              end;

              if TotalLeft <= 0 then
                break;
            end;
          end;

        end;

        {
        PrevToolBar:= TAdvCustomToolBar(FToolBarList[tbIdx-1]);
        if aAdvToolBar.Left <= (PrevToolBar.Left + PrevToolBar.Width + TRowCollection(Collection).OffSetX) then
        begin
          if PrevToolBar.Left = (TAdvDockPanel(TRowCollection(Collection).Owner).OffSetX + TRowCollection(Collection).OffSetX) then
          begin
            dif:= min(PrevToolBar.CanShrink, (aAdvToolBar.Left - ALeft));
            if dif > 0 then
            begin
              OldValue:= PrevToolBar.AllowBoundChange;
              PrevToolBar.AllowBoundChange:= true;
              PrevToolBar.Width:= PrevToolBar.Width - dif;
              PrevToolBar.AllowBoundChange:= OldValue;
            end;
          end;
        end;
         }

        // OutputDebugString(PChar('TotLf: '+inttostr(TotalLeft)));
        // Inserting ToolBar
        if (TotalLeft > 0)  and not (csLoading in aAdvToolBar.ComponentState) then  // since tbIdx > 0
        begin
          if (aAdvToolBar.Left - TotalLeft) <= (TAdvCustomToolBar(FToolBarList[tbIdx-1]).Left + 5 ) then
          begin
            OldValue := aAdvToolBar.AllowBoundChange;
            aAdvToolBar.AllowBoundChange := true;
            FToolBarList.Move(tbIdx, tbIdx-1);
            aAdvToolBar.Left := TAdvCustomToolBar(FToolBarList[tbIdx-1]).Left;
            self.ArrangeToolBars;
            aAdvToolBar.AllowBoundChange := OldValue;
          end;
        end;

        ALeft := aAdvToolBar.Left;
        AWidth := aAdvToolBar.Width;
      end;
    end
    else if aAdvToolBar.Left < ALeft then // Towards Right
    begin

      TotalLeft := ALeft - aAdvToolBar.Left;
     { if (ALeft >= (RowRect.Right - TRowCollection(Collection).OffSetX)) then
      begin
        if tbIdx = FToolBarList.Count-1 then
          ALeft:= RowRect.Right - TRowCollection(Collection).OffSetX - aAdvToolBar.Width;
      end
      else if (tbIdx = 0) then
      begin
        //do nothing
      end
      else if (tbIdx > 0) then }
      begin
        // Covering Empty space on the Right
        for i := tbIdx to FToolBarList.Count - 1 do
        begin
          ATb := TAdvCustomToolBar(FToolBarList[i]);
          if i < FToolBarList.Count - 1 then
            EmptSp := GetSpace(ATb, TAdvCustomToolBar(FToolBarList[i + 1]))
          else
            EmptSp := GetSpace(ATb, nil);

          if EmptSp > 0 then
          begin
            //move Atb Right to Available and required space
            L := min(EmptSp, TotalLeft);
            TotalLeft := TotalLeft - L;
            for j := tbIdx to i do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[j]);
              OldValue := ATb.AllowBoundChange;
              ATb.AllowBoundChange := true;
              ATb.Left := ATb.Left + L;
              ATb.AllowBoundChange := OldValue;
            end;
          end;

          if TotalLeft <= 0 then
            break;
        end;


        if TotalLeft > 0 then
        begin
          // checking empty space on the Left
          EmptSp := 0;
          for i := tbIdx downto 0 do
          begin
            ATb := TAdvCustomToolBar(FToolBarList[i]);
            if i > 0 then
              EmptSp := EmptSp + GetSpace(TAdvCustomToolBar(FToolBarList[i - 1]), ATb)
            else
              EmptSp := EmptSp + GetSpace(nil, ATb);
          end;

          // if not empty space and Right further required then shrink Right ToolBars
          if EmptSp <= 0 then
          begin
            TotalLeft := min(TotalLeft, TotalExpand(tbIdx, false));

            for i := FToolBarList.Count - 1 downto tbIdx do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[i]);
              L := min(TotalLeft, ATb.CanShrink);
              TotalLeft := TotalLeft - L;

              if L > 0 then
              begin
                // Adjust left
                OldValue := ATb.AllowBoundChange;
                ATb.AllowBoundChange := true;
                ATb.Width := ATb.Width - L;
                ATb.Left := ATb.Left + L;
                ATb.AllowBoundChange := OldValue;

                for j := i - 1 downto tbIdx + 1 do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[j]);
                  OldValue := ATb.AllowBoundChange;
                  ATb.AllowBoundChange := true;
                  ATb.Left := ATb.Left + L;
                  ATb.AllowBoundChange := OldValue;
                end;

                // Expand ToolBars on the Left side
                for k := tbIdx - 1 downto 0 do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[k]);
                  exp := min(L, ATb.CanExpand);
                  OldValue := ATb.AllowBoundChange;
                  ATb.AllowBoundChange := true;
                  ATb.Width := ATb.Width + exp;
                  ATb.AllowBoundChange := OldValue;

                  // Move ToolBars for Increase width
                  for M := k + 1 to tbIdx - 1 do
                  begin
                    ATb := TAdvCustomToolBar(FToolBarList[M]);
                    OldValue := ATb.AllowBoundChange;
                    ATb.AllowBoundChange := true;
                    ATb.Left := ATb.Left + exp;
                    ATb.AllowBoundChange := OldValue;
                  end;

                  L := L - exp;
                  if L <= 0 then
                    break;
                end;


              end;

              if TotalLeft <= 0 then
                break;
            end;
          end;

        end;
       {
        if (TotalLeft > 0) then  // since tbIdx > 0
        begin
          if (aAdvToolBar.Left + TotalLeft) > (TAdvCustomToolBar(FToolBarList[tbIdx+1]).Left + 2 ) then
          begin
            OldValue := aAdvToolBar.AllowBoundChange;
            aAdvToolBar.AllowBoundChange := true;
            FToolBarList.Move(tbIdx, tbIdx+1);
            aAdvToolBar.Left := TAdvCustomToolBar(FToolBarList[tbIdx+1]).Left;
            self.ArrangeToolBars;
            aAdvToolBar.AllowBoundChange := OldValue;
          end;
        end;  }

        ALeft := aAdvToolBar.Left;
        AWidth := aAdvToolBar.Width;
      end;


    end
    else if aAdvToolBar.Width > AWidth then // Decrease width
    begin
      if (FToolBarList.Count = 1) then   // FF: Controls overlaping right handle
      begin
        ArrangeToolBars;
        AWidth := aAdvToolBar.Width;
      end
      else
      begin

      end;
    end
    else if aAdvToolBar.Width < AWidth then // Increase Width
    begin

      TotalWidth := AWidth - aAdvToolBar.Width;
      // Covering Empty space on the Right
      for i := tbIdx to FToolBarList.Count - 1 do
      begin
        ATb := TAdvCustomToolBar(FToolBarList[i]);
        if i < FToolBarList.Count - 1 then
          EmptSp := GetSpace(ATb, TAdvCustomToolBar(FToolBarList[i + 1]))
        else
          EmptSp := GetSpace(ATb, nil);

        if EmptSp > 0 then
        begin
          //move Atb Right to Available and required space
          L := min(EmptSp, TotalWidth);
          TotalWidth := TotalWidth - L;
          for j := tbIdx + 1 to i do
          begin
            ATb := TAdvCustomToolBar(FToolBarList[j]);
            OldValue := ATb.AllowBoundChange;
            ATb.AllowBoundChange := true;
            ATb.Left := ATb.Left + L;
            ATb.AllowBoundChange := OldValue;
          end;

          ATb := TAdvCustomToolBar(FToolBarList[tbIdx]);
          OldValue := ATb.AllowBoundChange;
          ATb.AllowBoundChange := true;
          ATb.Width := ATb.Width + L;
          ATb.AllowBoundChange := OldValue;
        end;

        if TotalWidth <= 0 then
          break;
      end;


      if TotalWidth > 0 then
      begin
        // checking empty space on the Left
        EmptSp := 0;
        for i := tbIdx downto 0 do
        begin
          ATb := TAdvCustomToolBar(FToolBarList[i]);
          if i > 0 then
            EmptSp := EmptSp + GetSpace(TAdvCustomToolBar(FToolBarList[i - 1]), ATb)
          else
            EmptSp := EmptSp + GetSpace(nil, ATb);
        end;

        if EmptSP > 0 then
        begin
          // Covering Empty space on the Left
          for i := tbIdx downto 0 do
          begin
            ATb := TAdvCustomToolBar(FToolBarList[i]);
            if i > 0 then
              EmptSp := GetSpace(TAdvCustomToolBar(FToolBarList[i - 1]), ATb)
            else
              EmptSp := GetSpace(nil, ATb);

            if EmptSp > 0 then
            begin
              //move Atb left to Available and required space
              L := min(EmptSp, TotalWidth);
              TotalWidth := TotalWidth - L;
              for j := i to tbIdx do
              begin
                ATb := TAdvCustomToolBar(FToolBarList[j]);
                OldValue := ATb.AllowBoundChange;
                ATb.AllowBoundChange := true;
                ATb.Left := ATb.Left - L;
                ATb.AllowBoundChange := OldValue;
              end;

              ATb := TAdvCustomToolBar(FToolBarList[tbIdx]);
              OldValue := ATb.AllowBoundChange;
              ATb.AllowBoundChange := true;
              ATb.Width := ATb.Width + L;
              ATb.AllowBoundChange := OldValue;
            end;
            if TotalWidth <= 0 then
              break;
          end;


        end
        else if EmptSp <= 0 then // if not empty space and Inc Width further required then shrink Right ToolBars
        begin
        (*  TotalWidth:= min(TotalWidth, TotalExpand(tbIdx, false));

          for i:= FToolBarList.Count-1 downto tbIdx + 1  do
          begin
            ATb:= TAdvCustomToolBar(FToolBarList[i]);
            L:= min(TotalWidth, ATb.CanShrink);
            TotalWidth:= TotalWidth - L;

            if L > 0 then
            begin
              // Adjust left
              OldValue:= ATb.AllowBoundChange;
              ATb.AllowBoundChange:= true;
              ATb.Width:= ATb.Width - L;
              ATb.Left:= ATb.Left + L;
              ATb.AllowBoundChange:= OldValue;

              for j:= i-1 downto tbIdx+1 do
              begin
                ATb:= TAdvCustomToolBar(FToolBarList[j]);
                OldValue:= ATb.AllowBoundChange;
                ATb.AllowBoundChange:= true;
                ATb.Left:= ATb.Left + L;
                ATb.AllowBoundChange:= OldValue;
              end;

              {
              // Expand ToolBars on the Left side
              for k:= tbIdx-1 downto 0 do
              begin
                ATb:= TAdvCustomToolBar(FToolBarList[k]);
                exp:= min(L, ATb.CanExpand);
                OldValue:= ATb.AllowBoundChange;
                ATb.AllowBoundChange:= true;
                ATb.Width:= ATb.Width + exp;
                ATb.AllowBoundChange:= OldValue;

                // Move ToolBars for Increase width
                for M:= k+1 to tbIdx-1 do
                begin
                  ATb:= TAdvCustomToolBar(FToolBarList[M]);
                  OldValue:= ATb.AllowBoundChange;
                  ATb.AllowBoundChange:= true;
                  ATb.Left:= ATb.Left + exp;
                  ATb.AllowBoundChange:= OldValue;
                end;

                L:= L - exp;
                if L <=0 then
                  break;
              end;
              }

            end;

            if TotalWidth <=0 then
              break;
          end;   *)
        end;

      end;
      ALeft := aAdvToolBar.Left;
      AWidth := aAdvToolBar.Width;

    end;


  end;
end;

//------------------------------------------------------------------------------

procedure TRowCollectionItem.SetToolBarTopAndHeight(
  aAdvToolBar: TAdvCustomToolBar; var ATop, AHeight: integer);
var
  tbIdx, exp, i, TotalUp, TotalHeight: integer;
  OldValue: boolean;
  L, EmptSp, j, k, M: integer;
  ATb: TAdvCustomToolBar;

  function TotalExpand(ToolBarIndex: integer; DownWards: boolean): integer;
  var
    i: integer;
  begin
    Result := 0;
    if DownWards then
    begin
      for i := ToolBarIndex to FToolBarList.Count - 1 do
        Result := Result + TAdvCustomToolBar(FToolBarList[i]).CanExpand;
    end
    else
    begin
      for i := ToolBarIndex - 1 downto 0 do
        Result := Result + TAdvCustomToolBar(FToolBarList[i]).CanExpand;
    end;
  end;

begin
  tbIdx := FToolBarList.IndexOf(aAdvToolBar);
  if tbIdx < 0 then
    raise exception.Create('Invalid ToolBar Index');

  if TAdvDockPanel(TRowCollection(Collection).FOwner).Align in [daLeft, daRight] then
  begin
    if aAdvToolBar.Top > ATop then // Upwards
    begin
      if (ATop < (RowRect.Top + TRowCollection(Collection).OffSetX)) then
        ATop := (RowRect.Top + TRowCollection(Collection).OffSetX);

      TotalUp := aAdvToolBar.Top - ATop;
      {if (ATop <= (RowRect.Top + TRowCollection(Collection).OffSetX)) then
      begin
        if tbIdx = 0 then
          ATop := RowRect.Top + TRowCollection(Collection).OffSetX
        else
          ATop := aAdvToolBar.Top;
      end
      else} if (tbIdx = 0) then
      begin
        //do nothing
      end
      else if (tbIdx > 0) then
      begin
           // Covering Empty space on the Top
        for i := tbIdx downto 0 do
        begin
          ATb := TAdvCustomToolBar(FToolBarList[i]);
          if i > 0 then
            EmptSp := GetSpace(TAdvCustomToolBar(FToolBarList[i - 1]), ATb)
          else
            EmptSp := GetSpace(nil, ATb);

          if EmptSp > 0 then
          begin
            //move Atb Up to Available and required space
            L := min(EmptSp, TotalUp);
            TotalUp := TotalUp - L;
            for j := i to tbIdx do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[j]);
              OldValue := ATb.AllowBoundChange;
              ATb.AllowBoundChange := true;
              ATb.Top := ATb.Top - L;
              ATb.AllowBoundChange := OldValue;
            end;
          end;
          if TotalUp <= 0 then
            break;
        end;


        if TotalUp > 0 then
        begin
          EmptSp := 0;
          // checking empty space towards Down
          for i := tbIdx to FToolBarList.Count - 1 do
          begin
            ATb := TAdvCustomToolBar(FToolBarList[i]);
            if i < FToolBarList.Count - 1 then
              EmptSp := GetSpace(ATb, TAdvCustomToolBar(FToolBarList[i + 1]))
            else
              EmptSp := GetSpace(ATb, nil);
          end;

          // if not empty space and Top further required then shrink Up ToolBars
          if EmptSp <= 0 then
          begin
            for i := tbIdx - 1 downto 0 do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[i]);
              L := min(TotalUp, ATb.CanShrink);

              L := min(L, TotalExpand(tbIdx, true)); // TotalExpand downwards

              TotalUp := TotalUp - L;

              if L > 0 then
              begin
                // Shrink ToolBar
                OldValue := ATb.AllowBoundChange;
                ATb.AllowBoundChange := true;
                ATb.Height := ATb.Height - L;
                ATb.AllowBoundChange := OldValue;

                // Updating Top On Shrink
                for j := i + 1 to tbIdx - 1 do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[j]);
                  OldValue := ATb.AllowBoundChange;
                  ATb.AllowBoundChange := true;
                  ATb.Top := ATb.Top - L;
                  ATb.AllowBoundChange := OldValue;
                end;

                // Expand ToolBars
                for k := tbIdx to FToolBarList.Count - 1 do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[k]);
                  exp := min(L, ATb.CanExpand);
                  OldValue := ATb.AllowBoundChange;
                  ATb.AllowBoundChange := true;
                  ATb.Height := ATb.Height + exp;
                  //if k > tbIdx then
                  ATb.Top := ATb.Top - exp;
                  ATb.AllowBoundChange := OldValue;

                  L := L - exp;
                  if L <= 0 then
                    break;
                end;
              end;

              if TotalUp <= 0 then
                break;
            end;
          end;

        end;

        // Inserting ToolBar
        if (TotalUp > 0) and not (csLoading in aAdvToolBar.ComponentState) then  // since tbIdx > 0
        begin
          if (aAdvToolBar.Top - TotalUp) <= (TAdvCustomToolBar(FToolBarList[tbIdx-1]).Top + 5 ) then
          begin
            OldValue := aAdvToolBar.AllowBoundChange;
            aAdvToolBar.AllowBoundChange := true;
            FToolBarList.Move(tbIdx, tbIdx-1);
            aAdvToolBar.Top := TAdvCustomToolBar(FToolBarList[tbIdx-1]).Top;
            self.ArrangeToolBars;
            aAdvToolBar.AllowBoundChange := OldValue;
          end;
        end;

        ATop := aAdvToolBar.Top;
        AHeight := aAdvToolBar.Height;
      end;
    end
    else if aAdvToolBar.Top < ATop then // DownWards
    begin

      TotalUp := ATop - aAdvToolBar.Top;

      begin
        // Covering Empty space downwards
        for i := tbIdx to FToolBarList.Count - 1 do
        begin
          ATb := TAdvCustomToolBar(FToolBarList[i]);
          if i < FToolBarList.Count - 1 then
            EmptSp := GetSpace(ATb, TAdvCustomToolBar(FToolBarList[i + 1]))
          else
            EmptSp := GetSpace(ATb, nil);

          if EmptSp > 0 then
          begin
            //move Atb Down to Available and required space
            L := min(EmptSp, TotalUp);
            TotalUp := TotalUp - L;
            for j := tbIdx to i do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[j]);
              OldValue := ATb.AllowBoundChange;
              ATb.AllowBoundChange := true;
              ATb.Top := ATb.Top + L;
              ATb.AllowBoundChange := OldValue;
            end;
          end;

          if TotalUp <= 0 then
            break;
        end;


        if TotalUp > 0 then
        begin
          // checking empty space on the Top
          EmptSp := 0;
          for i := tbIdx downto 0 do
          begin
            ATb := TAdvCustomToolBar(FToolBarList[i]);
            if i > 0 then
              EmptSp := EmptSp + GetSpace(TAdvCustomToolBar(FToolBarList[i - 1]), ATb)
            else
              EmptSp := EmptSp + GetSpace(nil, ATb);
          end;

          // if not empty space and Down further required then shrink Down ToolBars
          if EmptSp <= 0 then
          begin
            TotalUp := min(TotalUp, TotalExpand(tbIdx, false));

            for i := FToolBarList.Count - 1 downto tbIdx do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[i]);
              L := min(TotalUp, ATb.CanShrink);
              TotalUp := TotalUp - L;

              if L > 0 then
              begin
                // Adjust Top
                OldValue := ATb.AllowBoundChange;
                ATb.AllowBoundChange := true;
                ATb.Height := ATb.Height - L;
                ATb.Top := ATb.Top + L;
                ATb.AllowBoundChange := OldValue;

                for j := i - 1 downto tbIdx + 1 do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[j]);
                  OldValue := ATb.AllowBoundChange;
                  ATb.AllowBoundChange := true;
                  ATb.Top := ATb.Top + L;
                  ATb.AllowBoundChange := OldValue;
                end;

                // Expand Top ToolBars
                for k := tbIdx - 1 downto 0 do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[k]);
                  exp := min(L, ATb.CanExpand);
                  OldValue := ATb.AllowBoundChange;
                  ATb.AllowBoundChange := true;
                  ATb.Height := ATb.Height + exp;
                  ATb.AllowBoundChange := OldValue;

                  // Move ToolBars for Increase Height
                  for M := k + 1 to tbIdx - 1 do
                  begin
                    ATb := TAdvCustomToolBar(FToolBarList[M]);
                    OldValue := ATb.AllowBoundChange;
                    ATb.AllowBoundChange := true;
                    ATb.Top := ATb.Top + exp;
                    ATb.AllowBoundChange := OldValue;
                  end;

                  L := L - exp;
                  if L <= 0 then
                    break;
                end;


              end;

              if TotalUp <= 0 then
                break;
            end;
          end;

        end;
        ATop := aAdvToolBar.Top;
        AHeight := aAdvToolBar.Height;
      end;


    end
    else if aAdvToolBar.Height > AHeight then // Dec Height
    begin

    end
    else if aAdvToolBar.Height < AHeight then // Inc Height
    begin

      TotalHeight := AHeight - aAdvToolBar.Height;

      begin
        // Covering Empty space downwards
        for i := tbIdx to FToolBarList.Count - 1 do
        begin
          ATb := TAdvCustomToolBar(FToolBarList[i]);
          if i < FToolBarList.Count - 1 then
            EmptSp := GetSpace(ATb, TAdvCustomToolBar(FToolBarList[i + 1]))
          else
            EmptSp := GetSpace(ATb, nil);

          if EmptSp > 0 then
          begin
            //move Atb Down to Available and required space
            L := min(EmptSp, TotalHeight);
            TotalHeight := TotalHeight - L;
            for j := tbIdx + 1 to i do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[j]);
              OldValue := ATb.AllowBoundChange;
              ATb.AllowBoundChange := true;
              ATb.Top := ATb.Top + L;
              ATb.AllowBoundChange := OldValue;
            end;

            ATb := TAdvCustomToolBar(FToolBarList[tbIdx]);
            OldValue := ATb.AllowBoundChange;
            ATb.AllowBoundChange := true;
            ATb.Height := ATb.Height + L;
            ATb.AllowBoundChange := OldValue;
          end;

          if TotalHeight <= 0 then
            break;
        end;


        if TotalHeight > 0 then
        begin
          // checking empty space on the Top
         { EmptSp:= 0;
          for i:= tbIdx downto 0 do
          begin
            ATb:= TAdvCustomToolBar(FToolBarList[i]);
            if i > 0 then
              EmptSp:= EmptSp + GetSpace(TAdvCustomToolBar(FToolBarList[i-1]), ATb)
            else
              EmptSp:= EmptSp + GetSpace(nil, ATb);
          end;  }

          //if EmptSP > 0 then
          begin
            for i := tbIdx downto 0 do
            begin
              ATb := TAdvCustomToolBar(FToolBarList[i]);
              if i > 0 then
                EmptSp := GetSpace(TAdvCustomToolBar(FToolBarList[i - 1]), ATb)
              else
                EmptSp := GetSpace(nil, ATb);

              if EmptSp > 0 then
              begin
                //move Atb Up to Available and required space
                L := min(EmptSp, TotalHeight);
                TotalHeight := TotalHeight - L;
                for j := i to tbIdx do
                begin
                  ATb := TAdvCustomToolBar(FToolBarList[j]);
                  OldValue := ATb.AllowBoundChange;
                  ATb.AllowBoundChange := true;
                  ATb.Top := ATb.Top - L;
                  if i = tbIdx then
                    ATb.Height := ATb.Height + L;
                  ATb.AllowBoundChange := OldValue;
                end;
              end;

              if TotalHeight <= 0 then
                break;
            end;

          end;
          //else if EmptSp <=0 then  // if not empty space and Down further required then shrink Down ToolBars
          if TotalHeight > 0 then
          begin
           { TotalUp:= min(TotalUp, TotalExpand(tbIdx, false));

            for i:= FToolBarList.Count-1 downto tbIdx  do
            begin
              ATb:= TAdvCustomToolBar(FToolBarList[i]);
              L:= min(TotalUp, ATb.CanShrink);
              TotalUp:= TotalUp - L;

              if L > 0 then
              begin
                // Adjust Top
                OldValue:= ATb.AllowBoundChange;
                ATb.AllowBoundChange:= true;
                ATb.Height:= ATb.Height - L;
                ATb.Top:= ATb.Top + L;
                ATb.AllowBoundChange:= OldValue;

                for j:= i-1 downto tbIdx+1 do
                begin
                  ATb:= TAdvCustomToolBar(FToolBarList[j]);
                  OldValue:= ATb.AllowBoundChange;
                  ATb.AllowBoundChange:= true;
                  ATb.Top:= ATb.Top + L;
                  ATb.AllowBoundChange:= OldValue;
                end;

                // Expand Top ToolBars
                for k:= tbIdx-1 downto 0 do
                begin
                  ATb:= TAdvCustomToolBar(FToolBarList[k]);
                  exp:= min(L, ATb.CanExpand);
                  OldValue:= ATb.AllowBoundChange;
                  ATb.AllowBoundChange:= true;
                  ATb.Height:= ATb.Height + exp;
                  ATb.AllowBoundChange:= OldValue;

                  // Move ToolBars for Increase Height
                  for M:= k+1 to tbIdx-1 do
                  begin
                    ATb:= TAdvCustomToolBar(FToolBarList[M]);
                    OldValue:= ATb.AllowBoundChange;
                    ATb.AllowBoundChange:= true;
                    ATb.Top:= ATb.Top + exp;
                    ATb.AllowBoundChange:= OldValue;
                  end;

                  L:= L - exp;
                  if L <=0 then
                    break;
                end;


              end;

              if TotalUp <=0 then
                break;
            end; }
          end;

        end;
        ATop := aAdvToolBar.Top;
        AHeight := aAdvToolBar.Height;
      end;

    end;


  end;

end;

//------------------------------------------------------------------------------

procedure TRowCollectionItem.RemoveToolBar(aAdvToolBar: TAdvCustomToolBar; DeleteIfEmpty: Boolean = True);
var
  i: integer;
begin
  i := FToolBarList.IndexOf(aAdvToolBar);
  if i >= 0 then
  begin
    FToolBarList.Delete(i);
    ArrangeToolBars;
    if DeleteIfEmpty then
      TRowCollection(Collection).DeleteMeIfEmpty(self);
  end;
end;

//------------------------------------------------------------------------------

function TRowCollectionItem.GetSpace(FirstAdvToolBar,
  SecondAdvToolBar: TAdvCustomToolBar): integer;
begin
  if TAdvDockPanel(TRowCollection(Collection).FOwner).Align in [daTop, daBottom] then
  begin
    if (FirstAdvToolBar <> nil) and (SecondAdvToolBar <> nil) then
      Result := SecondAdvToolBar.Left - (FirstAdvToolBar.Left + FirstAdvToolBar.Width + TRowCollection(Collection).OffSetX)
    else if (FirstAdvToolBar <> nil) then
      Result := RowRect.Right - (FirstAdvToolBar.Left + FirstAdvToolBar.Width + TRowCollection(Collection).OffSetX)
    else if (SecondAdvToolBar <> nil) then
      Result := SecondAdvToolBar.Left - (RowRect.Left + TRowCollection(Collection).OffSetX)
    else
      Result := 0;
  end
  else // daLeft, daRight
  begin
    if (FirstAdvToolBar <> nil) and (SecondAdvToolBar <> nil) then
      Result := SecondAdvToolBar.Top - (FirstAdvToolBar.Top + FirstAdvToolBar.Height + TRowCollection(Collection).OffSetX)
    else if (FirstAdvToolBar <> nil) then
      Result := RowRect.Bottom - (FirstAdvToolBar.Top + FirstAdvToolBar.Height + TRowCollection(Collection).OffSetX)
    else if (SecondAdvToolBar <> nil) then
      Result := SecondAdvToolBar.Top - (RowRect.Top + TRowCollection(Collection).OffSetX)
    else
      Result := 0;
  end;
end;

//------------------------------------------------------------------------------

function TRowCollectionItem.IsAllowed(
  aAdvToolBar: TAdvCustomToolBar): Boolean;
begin
  Result := true;
  if ToolBarList.Count >= 1 then
  begin
    Result := not TAdvCustomToolBar(FToolBarList[0]).FullSize;
  end;

  if Result and aAdvToolBar.FullSize then
    Result := ToolBarList.Count = 0;
end;

//------------------------------------------------------------------------------

{ TRowCollection }

function TRowCollection.Add: TRowCollectionItem;
begin
  Result := TRowCollectionItem(inherited Add); 
  SetRowsPosition;
end;

//------------------------------------------------------------------------------

constructor TRowCollection.Create(AOwner: TAdvDockPanel);
begin
  inherited Create(TRowCollectionItem);
  FOwner := AOwner;
  FOffSetX := 2;
  FOffSetY := 1;
end;

//------------------------------------------------------------------------------

procedure TRowCollection.DeleteMeIfEmpty(AItem: TRowCollectionItem);
var
  i: integer;
begin
  i := AItem.Index;
  if (AItem.ToolBarList.Count <= 0) and not (FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded)) then
  begin
    Delete(i);
    SetRowsPosition;
  end;
end;

//------------------------------------------------------------------------------

function TRowCollection.GetItem(Index: Integer): TRowCollectionItem;
begin
  Result := TRowCollectionItem(inherited Items[Index]);
end;

//------------------------------------------------------------------------------

function TRowCollection.GetOwner: TPersistent;
begin
  Result := FOwner;
end;

//------------------------------------------------------------------------------

function TRowCollection.Insert(Index: Integer): TRowCollectionItem;
{var
  i: integer;  }
begin
  Result := TRowCollectionItem(inherited Insert(Index));
  SetRowsPosition;
 { for i:=index+1 to Count-1 do
    items[i].ArrangeToolBars;  }
end;

//------------------------------------------------------------------------------

function TRowCollection.IsToolBarAlreadyAdded(
  aAdvToolBar: TAdvCustomToolBar): Integer;
var
  I: Integer;
begin
  Result := -1;
  for I := 0 to Count - 1 do
  begin
    if Items[I].ToolBarList.IndexOf(aAdvToolBar) >= 0 then
    begin
      Result := I;
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TRowCollection.MoveToolBarToRow(aAdvToolBar: TAdvCustomToolBar;
  ARowIndex: integer);
var
  OldIndex: integer;
begin
  if (ARowIndex < 0) or (ARowIndex >= Count) then
    raise exception.Create('Invalid Row Index');

  if Assigned(aAdvToolBar) and (aAdvToolBar.Row <> ARowIndex) then
  begin
    if Items[ARowIndex].IsAllowed(aAdvToolBar) then
    begin
      OldIndex := aAdvToolBar.Row;
      Items[OldIndex].RemoveToolBar(aAdvToolBar, false);
      Items[ARowIndex].AddToolBar(aAdvToolBar);
      Self.DeleteMeIfEmpty(Items[OldIndex]);
      //Items[OldIndex].RemoveToolBar(aAdvToolBar);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TRowCollection.SetItem(Index: Integer;
  const Value: TRowCollectionItem);
begin
  inherited Items[Index] := Value;
end;

//------------------------------------------------------------------------------

procedure TRowCollection.SetParentSize;
var
  s, df: Integer;
begin
  if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
    Exit;

  if FOwner.Align in [daTop, daBottom] then
  begin
    if FOwner.Align = daTop then
    begin
      if csDesigning in FOwner.ComponentState then
      begin
        if FOwner.UseRunTimeHeight then
        begin
          if Count > 0 then
            FOwner.Height := Items[Count - 1].RowRect.bottom + FOwner.OffSetY
          else
            FOwner.Height := FOwner.MinimumSize;// MINDOCKPANELHEIGHT;
        end
        else
        begin
          if Count > 0 then
            FOwner.Height := Items[Count - 1].RowRect.bottom + FOwner.OffSetY + (DEFAULT_TOOLBARHEIGHT div 2)
          else
            FOwner.Height := (DEFAULT_TOOLBARHEIGHT div 2) + FOwner.OffSetY * 2;
        end;
      end
      else
      begin
        if Count > 0 then
          FOwner.Height := Items[Count - 1].RowRect.bottom + FOwner.OffSetY
        else
          FOwner.Height := FOwner.MinimumSize;// MINDOCKPANELHEIGHT;
      end;
    end
    else   // daBottom
    begin
      if csDesigning in FOwner.ComponentState then
      begin
        if FOwner.UseRunTimeHeight then
        begin
          if Count > 0 then
            s := Items[Count - 1].RowRect.bottom + FOwner.OffSetY
          else
            s := FOwner.MinimumSize;// MINDOCKPANELHEIGHT;
        end
        else
        begin
          if Count > 0 then
            s := Items[Count - 1].RowRect.bottom + FOwner.OffSetY + (DEFAULT_TOOLBARHEIGHT div 2)
          else
            s := (DEFAULT_TOOLBARHEIGHT div 2) + FOwner.OffSetY * 2;
        end;
      end
      else
      begin
        if Count > 0 then
          s := Items[Count - 1].RowRect.bottom + FOwner.OffSetY
        else
          s := FOwner.MinimumSize;// MINDOCKPANELHEIGHT;
      end;

      if FOwner.Height < s then
      begin
        df := s - FOwner.Height;
        FOwner.SetBounds(FOwner.Left, FOwner.Top-df, FOwner.Width, s);
      end
      else
        FOwner.Height := s;
    end;
  end
  else if FOwner.Align in [daLeft, daRight] then
  begin
    if FOwner.Align = daLeft then
    begin
      if csDesigning in FOwner.ComponentState then
      begin
        if FOwner.UseRunTimeHeight then
        begin
          if Count > 0 then
            FOwner.Width := Items[Count - 1].RowRect.Right + FOwner.OffSetX
          else
            FOwner.Width := FOwner.MinimumSize; // MINDOCKPANELHEIGHT;
        end
        else
        begin
          if Count > 0 then
            FOwner.Width := Items[Count - 1].RowRect.Right + FOwner.OffSetX + (DEFAULT_TOOLBARHEIGHT div 2)
          else
            FOwner.Width := (DEFAULT_TOOLBARHEIGHT div 2) + FOwner.OffSetX * 2;
        end;
      end
      else
      begin
        if Count > 0 then
          FOwner.Width := Items[Count - 1].RowRect.Right + FOwner.OffSetX
        else
          FOwner.Width := FOwner.MinimumSize; // MINDOCKPANELHEIGHT;
      end;
    end
    else  // daRight
    begin
      if csDesigning in FOwner.ComponentState then
      begin
        if FOwner.UseRunTimeHeight then
        begin
          if Count > 0 then
            s := Items[Count - 1].RowRect.Right + FOwner.OffSetX
          else
            s := FOwner.MinimumSize; // MINDOCKPANELHEIGHT;
        end
        else
        begin
          if Count > 0 then
            s := Items[Count - 1].RowRect.Right + FOwner.OffSetX + (DEFAULT_TOOLBARHEIGHT div 2)
          else
            s := (DEFAULT_TOOLBARHEIGHT div 2) + FOwner.OffSetX * 2;
        end;
      end
      else
      begin
        if Count > 0 then
          s := Items[Count - 1].RowRect.Right + FOwner.OffSetX
        else
          s := FOwner.MinimumSize; // MINDOCKPANELHEIGHT;
      end;

      if FOwner.Width < s then
      begin
        df := s - FOwner.Width;
        FOwner.SetBounds(FOwner.Left - df, FOwner.Top, s, FOwner.Height);
      end
      else
        FOwner.Width := s;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TRowCollection.SetRowsPosition;
var
  i, y, x: integer;
begin
  if FOwner.Align in [daTop, daBottom] then
  begin
    y := OffSetY;
    for i := 0 to Count - 1 do
    begin  
      Items[i].SetRowRect(Rect(FOwner.OffSetX, y, FOwner.Width - FOwner.OffSetX, y + Items[i].Height + OffSetY));
      Items[i].ArrangeToolBars;
      y := y + items[i].Height + OffSetY;
    end;
  end
  else if FOwner.Align in [daLeft, daRight] then
  begin
    x := OffSetY;
    for i := 0 to Count - 1 do
    begin
      Items[i].SetRowRect(Rect(x, FOwner.OffSetX, x + Items[i].Height + OffSetY, FOwner.Height - FOwner.OffSetX));
      Items[i].ArrangeToolBars;
      x := x + items[i].Height + OffSetY;
    end;
  end;  
  SetParentSize;
end;

//------------------------------------------------------------------------------

// Simple remove space between Toolbars
procedure TRowCollection.ReArrangeAllToolBars;
var
  i, j, k: integer;
  atb: TAdvCustomToolbar;
begin
  if FOwner.Align in [daTop, daBottom] then
  begin
    for i := 0 to Count - 1 do
    begin
      Items[i].ArrangeToolBars;
      k := -1;
      for j := 0 to Items[i].FToolBarList.Count - 1 do
      begin
        atb := TAdvCustomToolBar(Items[i].FToolBarList[j]);
        if not (atb.Visible) then
          Continue;
          
        if (k >= 0) then
          atb.Left := TAdvCustomToolBar(Items[i].FToolBarList[k]).Left + TAdvCustomToolBar(Items[i].FToolBarList[k]).width + OffSetX
        else
          atb.Left := (Items[i].RowRect.Left + OffSetX);

        k := j;
      end;
    end;
  end
  else if FOwner.Align in [daLeft, daRight] then
  begin
    for i := 0 to Count - 1 do
    begin
      Items[i].ArrangeToolBars;
      k := -1;
      for j := 0 to Items[i].FToolBarList.Count - 1 do
      begin
        atb := TAdvCustomToolBar(Items[i].FToolBarList[j]);
        if not (atb.Visible) then
          Continue;

        if (k >= 0) then
          atb.Top := TAdvCustomToolBar(Items[i].FToolBarList[k]).Top + TAdvCustomToolBar(Items[i].FToolBarList[k]).Height + OffSetX
        else
          atb.Top := Items[i].RowRect.Bottom - (atb.Height + OffSetX);

        k := j;
      end;
    end;
  end;  
end;

//------------------------------------------------------------------------------

procedure TRowCollection.SetToolBarFullSize(
  aAdvToolBar: TAdvCustomToolBar);
{var
  OldValue: Boolean;
  S : integer;  }
begin
  if Assigned(aAdvToolBar) and (aAdvToolBar.Row >= 0) and (aAdvToolBar.Row < Count) then
  begin
    Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
    Insert(aAdvToolBar.Row).AddToolBar(aAdvToolBar);

    {
    OldValue:= aAdvToolBar.AllowBoundChange;
    aAdvToolBar.AllowBoundChange:= true;
    if FOwner.Align in [daTop, daBottom] then
    begin
      S:= (Items[aAdvToolBar.Row].RowRect.Right - Items[aAdvToolBar.Row].RowRect.Left) - Self.OffSetX*2;
      aAdvToolBar.Width := S;
      aAdvToolBar.Constraints.MaxWidth := S;
      aAdvToolBar.Constraints.MinWidth := S;
    end
    else // daLeft, daRight
    begin
      S:= (Items[aAdvToolBar.Row].RowRect.Bottom - Items[aAdvToolBar.Row].RowRect.Top) - Self.OffSetX*2;
      aAdvToolBar.Height := S;
      aAdvToolBar.Constraints.MaxHeight := S;
      aAdvToolBar.Constraints.MinHeight := S;
    end;

    aAdvToolBar.AllowBoundChange := OldValue; }
    Items[aAdvToolBar.Row].ArrangeToolBars;
  end;
end;

//------------------------------------------------------------------------------
{
Perform ToolBar Row Management
Rules:
  Add ToolBar in a row when
   *) Row has no fullsize Toolbar
   *) Row has the capacity to add this toolbar with its minlength, including max shrink to all toolbars.
}

procedure TRowCollection.SetToolBarLeftAndWidth(
  aAdvToolBar: TAdvCustomToolBar; var ALeft, AWidth: integer);
var
  Allowed, OldValue: Boolean;
  i: integer;
begin
  if FOwner.Align in [daTop, daBottom] then
  begin
  end
  else
  begin
    if (ALeft <= Items[aAdvToolBar.Row].RowRect.Left - 3) and (ALeft >= Items[aAdvToolBar.Row].RowRect.Left - 5)
      and (Items[aAdvToolBar.Row].ToolBarList.Count > 1) {and (aAdvToolBar.Row > 0)} then
    begin // go up and insert new row
      if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
      begin

      end
      else
      begin
        Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
        Insert(aAdvToolBar.Row).AddToolBar(aAdvToolBar);
      end;
      ALeft := aAdvToolBar.Left;

      //showmessage('1: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end
    else if (ALeft < Items[aAdvToolBar.Row].RowRect.Left - 6) and (aAdvToolBar.Row > 0) then
    begin // go up and Add in existing row
      for i := 0 to aAdvToolBar.Row - 1 do
      begin
        if (ALeft >= Items[i].RowRect.Left) and (ALeft < Items[i].RowRect.Right) then
        begin
          Allowed := Items[i].IsAllowed(aAdvToolBar);
          if Allowed then
          begin
            MoveToolBarToRow(aAdvToolBar, i);
          end
          else
          begin
            if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
            begin

            end
            else
            begin
              Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
              Insert(i).AddToolBar(aAdvToolBar);
            end;
          end;
          break;
        end;
      end;
      {
      Allowed:= Items[aAdvToolBar.Row-1].IsAllowed(aAdvToolBar);
      if Allowed then
      begin
        MoveToolBarToRow(aAdvToolBar, aAdvToolBar.Row-1);
      end; }
      ALeft := aAdvToolBar.Left;

      //showmessage('1: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end
    else if (ALeft >= Items[aAdvToolBar.Row].RowRect.Left + 3) and (ALeft <= Items[aAdvToolBar.Row].RowRect.Left + 5)
      and (Items[aAdvToolBar.Row].ToolBarList.Count > 1) {and (aAdvToolBar.Row < Count-1)} then
    begin // go down and insert a NewRow
      if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
      begin

      end
      else
      begin
        Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
        if (aAdvToolBar.Row + 1) >= Count then
          Add.AddToolBar(aAdvToolBar)
        else
          Insert(aAdvToolBar.Row + 1).AddToolBar(aAdvToolBar);
      end;
      ALeft := aAdvToolBar.Left;

      //showmessage('3: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end
    else if (ALeft > Items[aAdvToolBar.Row].RowRect.Left + 5) and (aAdvToolBar.Row < Count - 1) then
    begin // go down and add in existing row
      for i := aAdvToolBar.Row + 1 to Count - 1 do
      begin
        if {(ATop > Items[i].RowRect.Top) and }(ALeft < Items[i].RowRect.Right) then
        begin
          Allowed := Items[i].IsAllowed(aAdvToolBar);
          if Allowed then
          begin
            MoveToolBarToRow(aAdvToolBar, i);
          end
          else
          begin
            if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
            begin

            end
            else
            begin
              Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
              if i + 1 >= Count then
                Add.AddToolBar(aAdvToolBar)
              else
                Insert(i + 1).AddToolBar(aAdvToolBar);
            end;
          end;
          break;
        end;
      end;
      {
      Allowed:= Items[aAdvToolBar.Row+1].IsAllowed(aAdvToolBar);
      if Allowed then
      begin
        MoveToolBarToRow(aAdvToolBar, aAdvToolBar.Row+1);
      end; }
      ALeft := aAdvToolBar.Left;

      //showmessage('4: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end
    else
    begin
      ALeft := Items[aAdvToolBar.Row].RowRect.Left; // Set Old Top

      //showmessage('5: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end;

    if AWidth <> aAdvToolBar.Width then
    begin
      OldValue := aAdvToolBar.AllowBoundChange;
      aAdvToolBar.AllowBoundChange := true;
      aAdvToolBar.Width := AWidth;
      aAdvToolBar.AllowBoundChange := OldValue;
      SetRowsPosition;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TRowCollection.SetToolBarTopAndHeight(
  aAdvToolBar: TAdvCustomToolBar; var ATop, AHeight: integer);
var
  Allowed, OldValue: Boolean;
  i: integer;
begin
  if FOwner.Align in [daTop, daBottom] then
  begin
    //aAdvToolBar.AllowBoundChange:= true;

    if (ATop <= Items[aAdvToolBar.Row].RowRect.Top - 3) and (ATop >= Items[aAdvToolBar.Row].RowRect.Top - 5)
      and (Items[aAdvToolBar.Row].ToolBarList.Count > 1) {and (aAdvToolBar.Row > 0)} then
    begin // go up and insert new row
      if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
      begin

      end
      else
      begin
        Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
        Insert(aAdvToolBar.Row).AddToolBar(aAdvToolBar);
      end;
      ATop := aAdvToolBar.top;

      //showmessage('1: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end
    else if (ATop < Items[aAdvToolBar.Row].RowRect.Top - 6) and (aAdvToolBar.Row > 0) then
    begin // go up and Add in existing row
      for i := 0 to Count - 1 do
      begin
        if (i <> aAdvToolBar.Row) and (ATop >= Items[i].RowRect.Top) and (ATop < Items[i].RowRect.Bottom) then
        begin
          Allowed := Items[i].IsAllowed(aAdvToolBar);
          if Allowed then
          begin
            MoveToolBarToRow(aAdvToolBar, i);
          end
          else
          begin
            if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
            begin

            end
            else
            begin
              Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
              Insert(i).AddToolBar(aAdvToolBar);
            end;
          end;
          break;
        end;
      end;
     (*
      Allowed:= Items[aAdvToolBar.Row-1].IsAllowed(aAdvToolBar);
      if Allowed then
      begin
       { Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
        Items[aAdvToolBar.Row-1].AddToolBar(aAdvToolBar); }
        MoveToolBarToRow(aAdvToolBar, aAdvToolBar.Row-1);
      end; *)
      ATop := aAdvToolBar.top;

      //showmessage('1: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end
    else if (ATop >= Items[aAdvToolBar.Row].RowRect.Top {+ aAdvToolBar.Height} + 3) and (ATop <= Items[aAdvToolBar.Row].RowRect.Top {+ aAdvToolBar.Height} + 5)
      and (Items[aAdvToolBar.Row].ToolBarList.Count > 1) {and (aAdvToolBar.Row < Count-1)} then
    begin // go down and insert a NewRow

      if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
      begin

      end
      else
      begin
        Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
        if aAdvToolBar.Row + 1 >= Count then
          Add.AddToolBar(aAdvToolBar)
        else
          Insert(aAdvToolBar.Row + 1).AddToolBar(aAdvToolBar);
      end;
      ATop := aAdvToolBar.top;

      //showmessage('3: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end
    else if (ATop > Items[aAdvToolBar.Row].RowRect.Top {+ aAdvToolBar.Height} + 5) and (aAdvToolBar.Row < Count - 1) then
    begin // go down and add in existing row
      for i := aAdvToolBar.Row + 1 to Count - 1 do
      begin
        if {(ATop > Items[i].RowRect.Top) and }(ATop < Items[i].RowRect.Bottom) then
        begin
          Allowed := Items[i].IsAllowed(aAdvToolBar);
          if Allowed then
          begin
            MoveToolBarToRow(aAdvToolBar, i);
          end
          else
          begin
            if FOwner.LockHeight and not (csDesigning in FOwner.ComponentState) and (FOwner.FPropertiesLoaded) then
            begin

            end
            else
            begin
              Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
              if i + 1 >= Count then
                Add.AddToolBar(aAdvToolBar)
              else
                Insert(i + 1).AddToolBar(aAdvToolBar);
            end;
          end;
          break;
        end;
      end;

     (*
      Allowed:= Items[aAdvToolBar.Row+1].IsAllowed(aAdvToolBar);
      if Allowed then
      begin
       { Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
        Items[aAdvToolBar.Row+1].AddToolBar(aAdvToolBar); }
        MoveToolBarToRow(aAdvToolBar, aAdvToolBar.Row+1);
      end;  *)
      ATop := aAdvToolBar.top;

      //showmessage('4: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end
    else
    begin

      if (csDesigning in aAdvToolBar.ComponentState) and (ATop > Items[aAdvToolBar.Row].RowRect.Top + 5) and (aAdvToolBar.Row = Count - 1) and (Items[aAdvToolBar.Row].ToolBarList.Count > 1) then
      begin
        Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar);
        Add.AddToolBar(aAdvToolBar);
      end;

      ATop := Items[aAdvToolBar.Row].RowRect.Top; // Set Old Top

      //showmessage('5: T:'+inttostr(aAdvToolBar.top)+' L:'+inttostr(aAdvToolBar.Left)+' AT:'+inttostr(ATop)+' AL:'+inttostr(ALeft));
    end;

    //aAdvToolBar.AllowBoundChange:= false;

    if AHeight <> aAdvToolBar.Height then
    begin
      OldValue := aAdvToolBar.AllowBoundChange;
      aAdvToolBar.AllowBoundChange := true;
      aAdvToolBar.Height := AHeight;
      aAdvToolBar.AllowBoundChange := OldValue;
      SetRowsPosition;
    end;
  end
  else
  begin

  end;
end;

//------------------------------------------------------------------------------

procedure TRowCollection.UpdateToolBarVisibility(
  aAdvToolBar: TAdvCustomToolBar);
begin
  if Assigned(aAdvToolBar) then
  begin
    if aAdvToolBar.Visible then
    begin
      if IsToolBarAlreadyAdded(aAdvToolBar) < 0 then
      begin
        if FOwner.LockHeight then
        begin
          if (Count > 0) then
            Items[Count-1].AddToolBar(aAdvToolBar)
          else
          begin
            with Add do
              AddToolBar(aAdvToolBar);
          end;
        end
        else
        begin
          with Add do
            AddToolBar(aAdvToolBar);
        end;
      end;
    end
    else
    begin
      if (aAdvToolBar.Row >= 0) and (aAdvToolBar.Row < Count) then
        Items[aAdvToolBar.Row].RemoveToolBar(aAdvToolBar, True);
    end;
    {
    if Items[ARowIndex].IsAllowed(aAdvToolBar) then
    begin
      OldIndex := aAdvToolBar.Row;
      Items[OldIndex].RemoveToolBar(aAdvToolBar, false);
      Items[ARowIndex].AddToolBar(aAdvToolBar);
      Self.DeleteMeIfEmpty(Items[OldIndex]);
      //Items[OldIndex].RemoveToolBar(aAdvToolBar);
    end;
    }
  end;

end;

//------------------------------------------------------------------------------

{ TFloatingWindow }

constructor TFloatingWindow.Create(AOwner: TComponent);
begin
  CreateNew(AOwner);
end;

//------------------------------------------------------------------------------

constructor TFloatingWindow.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
  inherited;
  FOwner := AOwner;
  FBorderWidth := 2;
  FBorderColor := RGB(109, 109, 109);
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);

end;

//------------------------------------------------------------------------------

destructor TFloatingWindow.Destroy;
begin
  inherited;
end;

//------------------------------------------------------------------------------

function TFloatingWindow.GetParentWnd: HWnd;
var
  Last, P: HWnd;
begin
  P := GetParent((Owner as TWinControl).Handle);
  Last := P;
  while P <> 0 do
  begin
    Last := P;
    P := GetParent(P);
  end;
  Result := Last;
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.Loaded;
begin
  inherited;
  FOldCursor := self.Cursor;
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.CMMouseLeave(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  if ssLeft in Shift then
  begin
    if (((X >= Width - 5) and (X <= Width)) {or ((X >= 0) and (X <= 5))}) then
    begin
      FResizing := true;
      FResizingClip := rcRight;
      FResizingDir := 0;
      FMouseX := Width;
      FMouseY := Y;
    end
    else if ((Y >= Height - 5) and (Y <= Height)) {or ((Y >= 0) and (Y <= 5))} then
    begin
      FResizing := true;
      FResizingClip := rcBottom;
      FResizingDir := 0;
      FMouseY := Height;
      FMouseX := X;
    end
    else if ((X >= 0) and (X <= 5)) then
    begin
      FResizing := true;
      FResizingClip := rcLeft;
      FResizingDir := 0;
      FMouseX := 0;
      FMouseY := Y;
    end
    else if ((Y >= 0) and (Y <= 5)) then
    begin
      FResizing := true;
      FResizingClip := rcTop;
      FResizingDir := 0;
      FMouseX := X;
      FMouseY := 0;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.MouseMove(Shift: TShiftState; X, Y: Integer);
var
  ax, ay, h, w, OldV: integer;
begin
  inherited;
  if ((X >= Width - 5) and (X <= Width)) or ((X >= 0) and (X <= 5)) then
  begin
    if (Cursor <> crSizeWE) then
      Cursor := crSizeWE;
  end
  else if ((Y >= Height - 5) and (Y <= Height)) or ((Y >= 0) and (Y <= 5)) then
  begin
    if (Cursor <> crSizeNS) then
      Cursor := crSizeNS;
  end
  else
  begin
    if Cursor <> FoldCursor then
      Cursor := FoldCursor;
  end;

  if (ssLeft in Shift) and FResizing then
  begin
    case FResizingClip of
      rcRight:
        begin
          ax := (X - FMouseX);

          if ((ax > 5) {and (ax < 10)} and (FResizingDir in [0])) or ((ax >= 3) and (FResizingDir in [1])) then
          begin
            OldV := AdvCustomToolBar.FloatingRows;
            AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows - 1;
            FMouseX := Width;
            FResizingDir := 1;
            if OldV <> AdvCustomToolBar.FloatingRows then
              Invalidate;
          end
          else
            if ((ax < -5) {and (ax > -10)} and (FResizingDir in [0])) or ((ax <= -3) and (FResizingDir in [2])) then
            begin
              OldV := AdvCustomToolBar.FloatingRows;
              AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows + 1;
              FMouseX := Width;
              FResizingDir := 2;
              if OldV <> AdvCustomToolBar.FloatingRows then
                Invalidate;
          //OutputDebugString(PChar(inttostr(ax)+inttostr(x)));
            end
            else if (FResizingDir = 1) then
            begin
              if AdvCustomToolBar.GetFloatingWindowSizes(AdvCustomToolBar.FloatingRows + 1, h, w) then
              begin
                if X <= (w + BorderWidth * 2) then
                begin
                  AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows + 1;
                  FMouseX := Width;
                  Invalidate;
              //OutputDebugString(PChar(inttostr(ax)+inttostr(x)));
                end;
              end;
            end
            else if (FResizingDir = 2) then
            begin
              if AdvCustomToolBar.GetFloatingWindowSizes(AdvCustomToolBar.FloatingRows - 1, h, w) then
              begin
                if X >= (w + BorderWidth * 2) then
                begin
                  AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows - 1;
                  FMouseX := Width;
                  Invalidate;
              //OutputDebugString(PChar(inttostr(ax)+inttostr(x)));
                end;
              end;
            end;
        end;
      rcBottom:
        begin
          ay := (Y - FMouseY);

          if ((ay > 5) {and (ay < 10)} and (FResizingDir in [0])) or ((ay >= 3) and (FResizingDir in [1])) then
          begin
            OldV := AdvCustomToolBar.FloatingRows;
            AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows + 1;
            FMouseY := Height;
            FResizingDir := 1;
            if OldV <> AdvCustomToolBar.FloatingRows then
              Invalidate;
          //OutputDebugString(PChar(inttostr(ay)+inttostr(y)));
          end
          else
            if ((ay < -5) {and (ay > -10)} and (FResizingDir in [0])) or ((ay <= -3) and (FResizingDir in [2])) then
            begin
              OldV := AdvCustomToolBar.FloatingRows;
              AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows - 1;
              FMouseY := Height;
              FResizingDir := 2;
              if OldV <> AdvCustomToolBar.FloatingRows then
                Invalidate;
          //OutputDebugString(PChar(inttostr(ay)+inttostr(y)));
            end
            else if (FResizingDir = 1) then
            begin
              if AdvCustomToolBar.GetFloatingWindowSizes(AdvCustomToolBar.FloatingRows - 1, h, w) then
              begin
                if (Y <= (h + (BorderWidth + 1) * 2)) then
                begin
                  OldV := AdvCustomToolBar.FloatingRows;
                  AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows - 1;
                  FMouseY := Height;
                  if OldV <> AdvCustomToolBar.FloatingRows then
                    Invalidate;
              //OutputDebugString(PChar(inttostr(ay)+inttostr(y)));
                end;
              end;
            end
            else if (FResizingDir = 2) then
            begin
              if AdvCustomToolBar.GetFloatingWindowSizes(AdvCustomToolBar.FloatingRows + 1, h, w) then
              begin
                if Y >= (H + BorderWidth * 2) then
                begin
                  OldV := AdvCustomToolBar.FloatingRows;
                  AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows + 1;
                  FMouseY := Height;
                  if OldV <> AdvCustomToolBar.FloatingRows then
                    Invalidate;
              //OutputDebugString(PChar(inttostr(ay)+inttostr(y)));
                end;
              end;
            end;
        end;
      rcLeft:
        begin
          ax := (X - FMouseX);

          if ((ax < -5) and (FResizingDir in [0])) or ((ax <= -3) and (FResizingDir in [1])) then
          begin
            w := self.Width;
            OldV := AdvCustomToolBar.FloatingRows;
            AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows - 1;
            Left := Left - (Width - w);
            FMouseX := 0;
            FResizingDir := 1;
            if OldV <> AdvCustomToolBar.FloatingRows then
              Invalidate;
          end
          else
            if ((ax > 5) and (FResizingDir in [0])) or ((ax >= 3) and (FResizingDir in [2])) then
            begin
              w := self.Width;
              OldV := AdvCustomToolBar.FloatingRows;
              AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows + 1;
              Left := Left + w - Width;
              FMouseX := 0;
              FResizingDir := 2;
              if OldV <> AdvCustomToolBar.FloatingRows then
                Invalidate;
          //OutputDebugString(PChar(inttostr(ax)+inttostr(x)));
            end
            else if (FResizingDir = 1) then
            begin
              if AdvCustomToolBar.GetFloatingWindowSizes(AdvCustomToolBar.FloatingRows + 1, h, w) then
              begin
                if X >= (Width - (w + BorderWidth * 2)) then
                begin
                  w := self.Width;
                  AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows + 1;
                  Left := Left + w - Width;
                  FMouseX := 0;
                  Invalidate;
              //OutputDebugString(PChar(inttostr(ax)+inttostr(x)));
                end;
              end;
            end
            else if (FResizingDir = 2) then
            begin
              if AdvCustomToolBar.GetFloatingWindowSizes(AdvCustomToolBar.FloatingRows - 1, h, w) then
              begin
                if X <= (Width - (w + BorderWidth * 2)) then
                begin
                  w := self.Width;
                  AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows - 1;
                  Left := Left - (Width - w);
                  FMouseX := 0;
                  Invalidate;
              //OutputDebugString(PChar(inttostr(ax)+inttostr(x)));
                end;
              end;
            end;
        end;
      rcTop:
        begin
          ay := (Y - FMouseY);

          if ((ay < -5) and (FResizingDir in [0])) or ((ay <= -3) and (FResizingDir in [1])) then
          begin
            h := self.Height;
            OldV := AdvCustomToolBar.FloatingRows;
            AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows + 1;
            Top := Top - (Height - h);
            FMouseY := 0;
            FResizingDir := 1;
            if OldV <> AdvCustomToolBar.FloatingRows then
              Invalidate;
          //OutputDebugString(PChar(inttostr(ay)+inttostr(y)));
          end
          else
            if ((ay > 5) and (FResizingDir in [0])) or ((ay >= 3) and (FResizingDir in [2])) then
            begin
              h := self.Height;
              OldV := AdvCustomToolBar.FloatingRows;
              AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows - 1;
              Top := Top + h - Height;
              FMouseY := 0;
              FResizingDir := 2;
              if OldV <> AdvCustomToolBar.FloatingRows then
                Invalidate;
          //OutputDebugString(PChar(inttostr(ay)+inttostr(y)));
            end
            else if (FResizingDir = 1) then
            begin
              if AdvCustomToolBar.GetFloatingWindowSizes(AdvCustomToolBar.FloatingRows - 1, h, w) then
              begin
                if (Y >= (Height - (h + (BorderWidth + 1) * 2))) then
                begin
                  h := self.Height;
                  OldV := AdvCustomToolBar.FloatingRows;
                  AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows - 1;
                  Top := Top + h - Height;
                  FMouseY := 0;
                  if OldV <> AdvCustomToolBar.FloatingRows then
                    Invalidate;
              //OutputDebugString(PChar(inttostr(ay)+inttostr(y)));
                end;
              end;
            end
            else if (FResizingDir = 2) then
            begin
              if AdvCustomToolBar.GetFloatingWindowSizes(AdvCustomToolBar.FloatingRows + 1, h, w) then
              begin
                if Y <= (Height - (h + BorderWidth * 2)) then
                begin
                  h := self.Height;
                  OldV := AdvCustomToolBar.FloatingRows;
                  AdvCustomToolBar.FloatingRows := AdvCustomToolBar.FloatingRows + 1;
                  Top := Top - (Height - h);
                  FMouseY := 0;
                  if OldV <> AdvCustomToolBar.FloatingRows then
                    Invalidate;
              //OutputDebugString(PChar(inttostr(ay)+inttostr(y)));
                end;
              end;
            end;
        end;

    end;

    {
    ax:= (X - FMouseX);

    if (FResizingDir = 1) and (ax >= 0) then
      FResizingDir:= 0
    else if (FResizingDir = 2) and (ax <= 0) then
      FResizingDir:= 0;

    if (ax > 5) and (ax < 10) and (FResizingDir in [0, 1]) then
    begin
      AdvCustomToolBar.FloatingRows:= AdvCustomToolBar.FloatingRows - 1;
      FMouseX:= Width - 2;
      FResizingDir:= 1;
      Invalidate;
    end
    else
    if (ax < -5) and (ax > -10) and (FResizingDir in [0, 2]) then
    begin
      AdvCustomToolBar.FloatingRows:= AdvCustomToolBar.FloatingRows + 1;
      FMouseX:= Width - 2;
      FResizingDir:= 2;
      Invalidate;
    end;
    }
    //OutputDebugString(PChar('ax: '+inttostr(ax)));
    {
    if (P.X > Left + Width + 5) and (P.X < Left + Width +10) then
      AdvCustomToolBar.FloatingRows:= AdvCustomToolBar.FloatingRows - 1
    else if (P.X < Left + Width -5) and (P.X > Left + Width -10) then
      AdvCustomToolBar.FloatingRows:= AdvCustomToolBar.FloatingRows + 1;
    }
  end;

end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.MouseUp(Button: TMouseButton; Shift: TShiftState;
  X, Y: Integer);
begin
  inherited;
  if FResizing then
  begin
    FResizing := false;
    FResizingDir := 0;
    FMouseX := 0;
    FMouseY := 0;
  end;

end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.Paint;
begin
  inherited;
  with Canvas do
  begin
    if BorderColor <> clNone then
    begin
      Pen.Color := BorderColor;
      Pen.Width := BorderWidth;

      Rectangle(1, 1, Width, Height);

      Pixels[BorderWidth, BorderWidth] := BorderColor;
      Pixels[Width - BorderWidth - 1, BorderWidth] := BorderColor;
      Pixels[BorderWidth, Height - BorderWidth - 1] := BorderColor;
      Pixels[Width - BorderWidth - 1, Height - BorderWidth - 1] := BorderColor;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.SetBorderColor(const Value: TColor);
begin
  FBorderColor := Value;
end;

procedure TFloatingWindow.SetBorderWidth(const Value: integer);
begin
  if FBorderWidth <> Value then
  begin
    FBorderWidth := Value;
    SetWindowSize;
  end;
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.SetWindowSize;
begin
  if Assigned(FAdvCustomToolBar) then
  begin
    Height := FAdvCustomToolBar.Height + (BorderWidth + 1) * 2; // .GetVisibleHeight;
    Width := FAdvCustomToolBar.Width + (BorderWidth + 1) * 2;
    FAdvCustomToolBar.Left := BorderWidth + 1;
    FAdvCustomToolBar.Top := BorderWidth + 1;
    Self.Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.WMActivate(var Message: TWMActivate);
begin
  inherited;

  if Message.Active = integer(False) then
  begin
  end
  else if Assigned(FAdvCustomToolBar) then
  begin
    //FAdvCustomToolBar.SetFocus;
    //SendMessage(getParentWnd, WM_NCACTIVATE, 1, 0);
  end;
end;

//------------------------------------------------------------------------------

procedure TFloatingWindow.WMNCHitTest(var Message: TWMNCHitTest);
var
  pt: TPoint;
begin
  inherited;
  Exit;

  // Make the hint sizable
  pt := ScreenToClient(Point(Message.XPos, Message.YPos));

  if (pt.X > Width - 10) and (pt.Y > Height - 10) then
    message.Result := HTBOTTOMRIGHT
end;

//------------------------------------------------------------------------------

{ TButtonAppearance }

procedure TButtonAppearance.Assign(Source: TPersistent);
begin
  if Source is TButtonAppearance then
  begin
    FColor := TButtonAppearance(Source).Color;
    FColorTo := TButtonAppearance(Source).ColorTo;
    FColorHot := TButtonAppearance(Source).ColorHot;
    FColorHotTo := TButtonAppearance(Source).ColorHotTo;
    FColorDown := TButtonAppearance(Source).ColorDown;
    FColorDownTo := TButtonAppearance(Source).ColorDownTo;
    FColorChecked := TButtonAppearance(Source).FColorChecked;
    FColorCheckedTo := TButtonAppearance(Source).FColorCheckedTo;
    FCaptionTextColor := TButtonAppearance(Source).FCaptionTextColor;
    FCaptionTextColorHot := TButtonAppearance(Source).FCaptionTextColorHot;
    FCaptionTextColorDown := TButtonAppearance(Source).FCaptionTextColorDown;
    FCaptionTextColorChecked := TButtonAppearance(Source).FCaptionTextColorChecked;
    FGradientDirection := TButtonAppearance(Source).GradientDirection;
    FBorderColor := TButtonAppearance(Source).BorderColor;
    FBorderHotColor := TButtonAppearance(Source).BorderHotColor;
    FBorderDownColor := TButtonAppearance(Source).BorderDownColor;
    FBorderCheckedColor := TButtonAppearance(Source).FBorderCheckedColor;
    //inherited Assign(Source);
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.Change;
begin
  if Assigned(FOnChange) then
    FOnChange(self);
end;

//------------------------------------------------------------------------------

constructor TButtonAppearance.Create;
begin
  inherited;

  FColor := clNone;
  FColorTo := clNone;
  FColorHot := $00D2BDB6;
  FColorHotTo := clNone;
  FColorDown := $00B59285;
  FColorDownTo := clNone;
  FGradientDirection := gdHorizontal;

  FBorderColor := clNone;
  FBorderDownColor := RGB(10, 36, 106);
  FBorderHotColor := RGB(10, 36, 106);
  FBorderCheckedColor := RGB(10, 36, 106);
  
  FColorChecked := $00D8D5D4;
  FColorCheckedTo := clNone;
  FCaptionTextColor := clBlack;
  FCaptionTextColorHot := clBlack;
  FCaptionTextColorDown := clBlack;
  FCaptionTextColorChecked := clBlack;
  FCaptionFont := TFont.Create;
  FGlyphPosition := gpLeft;
  FGradientDirection := gdVertical;
  FGradientDirectionChecked := gdVertical;
  FGradientDirectionDown := gdVertical;
  FGradientDirectionHot := gdVertical;

  FSystemFont := true;

  if IsVista then
    CaptionFont.Name := 'Segoe UI'
  else
    CaptionFont.Name := 'Tahoma';
end;

//------------------------------------------------------------------------------

destructor TButtonAppearance.Destroy;
begin
  FCaptionFont.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetBorderColor(const Value: TColor);
begin
  if FBorderColor <> Value then
  begin
    FBorderColor := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetBorderCheckedColor(const Value: TColor);
begin
  if FBorderCheckedColor <> Value then
  begin
    FBorderCheckedColor := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetCaptionFont(const Value: TFont);
begin
  FCaptionFont.Assign(Value);
  Change;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetCaptionTextColor(const Value: TColor);
begin
  if FCaptionTextColor <> Value then
  begin
    FCaptionTextColor := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetCaptionTextColorDown(const Value: TColor);
begin
  if FCaptionTextColorDown <> Value then
  begin
    FCaptionTextColorDown := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetCaptionTextColorHot(const Value: TColor);
begin
  if FCaptionTextColorHot <> Value then
  begin
    FCaptionTextColorHot := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetCaptionTextColorChecked(
  const Value: TColor);
begin
  if FCaptionTextColorChecked <> Value then
  begin
    FCaptionTextColorChecked := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetColor(const Value: TColor);
begin
  if FColor <> Value then
  begin
    FColor := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetColorDown(const Value: TColor);
begin
  if FColorDown <> Value then
  begin
    FColorDown := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetColorDownTo(const Value: TColor);
begin
  if FColorDownTo <> Value then
  begin
    FColorDownTo := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetColorHot(const Value: TColor);
begin
  if FColorHot <> Value then
  begin
    FColorHot := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetColorHotTo(const Value: TColor);
begin
  if FColorHotTo <> Value then
  begin
    FColorHotTo := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetColorChecked(const Value: TColor);
begin
  if FColorChecked <> Value then
  begin
    FColorChecked := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetColorCheckedTo(const Value: TColor);
begin
  if FColorCheckedTo <> Value then
  begin
    FColorCheckedTo := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetColorTo(const Value: TColor);
begin
  if FColorTo <> Value then
  begin
    FColorTo := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetGradientDirection(
  const Value: TGradientDirection);
begin
  if FGradientDirection <> Value then
  begin
    FGradientDirection := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetGlyphPosition(const Value: TGlyphPosition);
begin
  if FGlyphPosition <> Value then
  begin
    FGlyphPosition := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonAppearance.SetGradientDirectionChecked(
  const Value: TGradientDirection);
begin
  FGradientDirectionChecked := Value;
end;

procedure TButtonAppearance.SetGradientDirectionDown(
  const Value: TGradientDirection);
begin
  FGradientDirectionDown := Value;
end;

procedure TButtonAppearance.SetGradientDirectionHot(
  const Value: TGradientDirection);
begin
  FGradientDirectionHot := Value;
end;

procedure TButtonAppearance.SetSystemFont(const Value: Boolean);
begin
  if (FSystemFont <> Value) then
  begin
    FSystemFont := Value;

    if Value then
    begin
      if IsVista then
        FCaptionFont.Name := 'Segoe UI'
      else
        FCaptionFont.Name := 'Tahoma';
    end;
  end;
end;

//------------------------------------------------------------------------------

{ TAdvCustomToolBarButton }

constructor TAdvCustomToolBarButton.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FGlyph := TBitmap.Create;
  FGlyph.OnChange := GlyphChanged;
  FGlyphHot := TBitmap.Create;
  //FGlyphHot.OnChange := GlyphChanged;
  FGlyphDown := TBitmap.Create;
  //FGlyphDown.OnChange := GlyphChanged;
  FGlyphDisabled := TBitmap.Create;
  //FGlyphDisabled.OnChange := GlyphChanged;
  FGlyphChecked := TBitMap.Create;
  //FGlyphChecked.OnChange := GlyphChanged;
  FGlyphShade := TBitmap.Create;

  FDrawPosition := TAdvToolBarButtonDrawPosition.Create;
  FDrawPosition.OnChange := PositionChanged;

  SetBounds(0, 0, 23, 22);
  ControlStyle := [csCaptureMouse, csDoubleClicks];
  ParentFont := True;

  FAppearance:= TButtonAppearance.create;
  FAppearance.OnChange:= OnAppearanceChange;
  
  FGlyphPosition := gpLeft;
  AutoSize := True;

  // make sure to use a Truetype font
  Font.Name := 'Tahoma';

  FSpacing := 4;
  //FMargin := -1;
  FOffSet := 4;
  Flat := True;
  FTransparent := True;
  FShaded := True;

  FDropDownButton := false;
  FStyle := tasButton;
  FGroupIndex := 0;
  FGrouped := true;
  FPosition := daTop;
  FMenuItem := nil;

  //AutoSize := false;
  FImageIndex := -1;

  FPicture := TPicture.Create;
  FPicture.OnChange := GlyphChanged;

  FPictureDisabled := TPicture.Create;
  FPictureDisabled.OnChange := GlyphChanged;

  FParentStyler := true;

  FDropDownSectWidth := 12;

  FInternalTag := 0;
  FDropDownSplit := true;

  FUnHotTimer := TTimer.Create(self);
  FUnHotTimer.Interval := 1;
  FUnHotTimer.Enabled := false;
  FUnHotTimer.OnTimer := UnHotTimerOnTime;

  FOfficeHint := TAdvHintInfo.Create;
  FCommandID := -1;
end;

//------------------------------------------------------------------------------

destructor TAdvCustomToolBarButton.Destroy;
begin
  FGlyph.Free;
  FGlyphHot.Free;
  FGlyphDown.Free;
  FGlyphDisabled.Free;
  FGlyphChecked.Free;
  FGlyphShade.Free;
  FDrawPosition.Free;
  FAppearance.Free;
  FPicture.Free;
  FPictureDisabled.Free;
  FUnHotTimer.Free;
  FOfficeHint.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.Click;
begin
  if Assigned(AdvToolBar) then
  begin
    AdvToolBar.HideOptionWindow;
  end
  else if Assigned(AdvQuickAccessToolBar) then
  begin
    AdvQuickAccessToolBar.HideOverflowWindow;
  end;

  inherited;
  if Assigned(AdvToolBar) then
    AdvToolBar.UpControlInRUL(self);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.CMDialogChar(var Message: TCMDialogChar);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.CMEnabledChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.CMFontChanged(var Message: TMessage);
begin
  inherited;
  // TODO : here
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.CMMouseEnter(var Message: TMessage);
begin
  inherited;

  if (csDesigning in ComponentState) then
    Exit;

  FMouseInControl := true;
  //FHot := true;
  if Enabled then
  begin
    if Assigned(FAdvToolBar) or Assigned(AdvQuickAccessToolBar) then
    begin
      //if FAdvToolBar.FInMenuLoop and FAdvToolBar.FMenuFocused then
        Hot := True;
    end;
    InvalidateMe;
  end;
  FUnHotTimer.Enabled := True;

  if Assigned(FOnMouseEnter) then
     FOnMouseEnter(Self);

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.CMMouseLeave(var Message: TMessage);
begin
  inherited;

  if (csDesigning in ComponentState) then
    exit;

  FUnHotTimer.Enabled := False;
  FMouseInControl := false;
  FHot := false;

  if Assigned(FAdvToolBar) then
  begin
    if not (FAdvToolBar.FInMenuLoop and FAdvToolBar.FMenuFocused) then
      Hot := False;
  end
  else if Assigned(AdvQuickAccessToolBar) then
  begin
    Hot := False;
  end;

  if Enabled then
    InvalidateMe;

  if Assigned(FOnMouseLeave) then
     FOnMouseLeave(Self);

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.CMSysColorChange(var Message: TMessage);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.CMTextChanged(var Message: TMessage);
begin
  inherited;
  AdjustSize;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.GlyphChanged(Sender: TObject);
begin
  AdjustSize;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.Loaded;
begin
  inherited;

  if (Down <> FInitialDown) then
    Down := FInitialDown;

  if FShaded then
    GenerateShade;
  AdjustSize;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  pt:TPoint;
  InBottomDrop,InRightDrop: boolean;
begin
  //OutputDebugString(PChar(BoolToStr(FMenuBeingClosed) +' : '+ BoolToStr(FInternalClick)+' : '+ BoolToStr(FAdvToolBar.FMenuDropped)));
  inherited;

  if (Button <> mbLeft) or not Enabled or (csDesigning in ComponentState) then
    Exit;

  FMouseDownInControl := true;

  InBottomDrop := (Position in [daTop, daBottom]) and (X > (Width - DropDownSectWidth));
  InRightDrop := (Position in [daLeft, daRight]) and (Y > (Height - DropDownSectWidth));


  if not DropDownButton and IsMenuButton and (Assigned(FDropDownMenu) or (MenuItem <> nil)) then
  begin
    InvalidateMe;
    // FF: (Comented) mouse disable after menu show
   { if not (csDesigning in ComponentState) and ((DropdownMenu <> nil) and
       DropdownMenu.AutoPopup or (MenuItem <> nil)) and (FAdvToolBar <> nil) and not(FAdvToolBar.FInMenuLoop) then
      FAdvToolBar.TrackMenu(self)
    else }
      //DoDropDown;

    if (not FAdvToolBar.FMenuDropped and not FMenuBeingClosed and not FMenuDisplayed) or FInternalClick then
    begin
      FInternalClick := False;
      DoDropDown;
    end
    else if FMenuBeingClosed then
      FMenuBeingClosed := False;
  end
  else
  begin
    if Style in [tasButton, tasCheck] then
    begin
//      if FDropDownButton and ( ((Self.Position in [daTop, daBottom]) and
//         (X > (Width - FDropDownSectWidth))) or ((Self.Position in [daLeft, daRight]) and (Y > (Height - FDropDownSectWidth))) ) then
      if FDropDownButton and (InBottomDrop or InRightDrop or not FDropDownSplit) then
      begin
        FState := absUp;
        FMouseInControl := False;
        FMouseDownInControl := False;

        PopupBtnDown;

        if Assigned(FDropDownMenu) then
        begin
          if Style = tasButton then
            FDown := false;
          FHot := false;
          FMenuSel := true;
          Repaint;
          pt := Point(Left, Top + Height);
          pt := Parent.ClientToScreen(pt);
          if Assigned(AdvToolBar) then
          begin
            FDropDownMenu.MenuStyler := AdvToolBar.FCurrentToolBarStyler.CurrentAdvMenuStyler;
          end
          else if Assigned(AdvQuickAccessToolBar) then
          begin
            if Assigned(AdvQuickAccessToolBar.CurrentToolBarStyler) then
              FDropDownMenu.MenuStyler := AdvQuickAccessToolBar.CurrentToolBarStyler.CurrentAdvMenuStyler;
          end;

          FDropDownMenu.Popup(pt.X,pt.Y);

          FMenuSel := false;
          Repaint;
        end;

        InvalidateMe;
        Exit;
      end
      else
      begin
        ButtonDown;

        if not FDown then
        begin
          FState := absDown;
          Invalidate;
        end;

        if Style = tasCheck then
        begin
          FState := absDown;
          Repaint;
        end;

        FDragging := True;
      end;
    end
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.MouseMove(Shift: TShiftState; X,
  Y: Integer);
var
  NewState: TAdvButtonState;
begin
  inherited;

  if (csDesigning in ComponentState) then
    Exit;

  if FDragging then
  begin
    if (not FDown) then NewState := absUp
    else NewState := absExclusive;

    if (X >= 0) and (X < ClientWidth) and (Y >= 0) and (Y <= ClientHeight) then
      if FDown then NewState := absExclusive else NewState := absDown;

    if (Style = tasCheck) and FDown then
    begin
      NewState := absDown;
    end;

    if NewState <> FState then
    begin
      FState := NewState;
      Invalidate;
    end;
  end
  else if not FMouseInControl then
    UpdateTracking;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.MouseUp(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  DoClick: Boolean;
begin
  inherited;

  if FMenuBeingClosed then
    FMenuBeingClosed := False;
  if FMenuDisplayed then
    FMenuDisplayed := False;
    
  if (csDesigning in ComponentState) then
    exit;

  FMouseDownInControl := false;
  InvalidateMe;

  if not DropDownButton and IsMenuButton and (Assigned(FDropDownMenu) or (MenuItem <> nil)) then
  begin
    //InvalidateMe;
    //DoDropDown;
  end
  else
  begin
  {  if Style in [tasButton , tasCheck] then
    begin
      if FDropDownButton and (X > (Width - FDropDownSectWidth)) then
      begin
        //PopupBtnDown;
      end
      else
        Click;
    end;  }

    if FDragging then
    begin
      FDragging := False;
      DoClick := (X >= 0) and (X < ClientWidth) and (Y >= 0) and (Y <= ClientHeight);
      if FGroupIndex = 0 then
      begin
        // Redraw face in-case mouse is captured
        FState := absUp;
        FMouseInControl := False;
        FHot := false;
        
        if Style = tasCheck then
        begin
          SetDown(not FDown);
          FState := absUp;
        end;

        if DoClick and not (FState in [absExclusive, absDown]) then
          Invalidate;
      end
      else
        if DoClick then
        begin
          SetDown(not FDown);
          if FDown then Repaint;
        end
        else
        begin
          if FDown then
            FState := absExclusive;
          Repaint;
        end;
      if DoClick then Click;
      UpdateTracking;
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.Notification(AComponent: TComponent;
  AOperation: TOperation);
begin
  inherited;

  if not (csDestroying in ComponentState) and (AOperation = opRemove) then
  begin
    if AComponent = DropdownMenu then
      DropdownMenu := nil
    else if AComponent = MenuItem then
      MenuItem := nil;

    if Assigned(FAdvToolBar) and (AComponent = FAdvToolBar.Images) then
    begin
      ImageIndex := -1
    end
    else if Assigned(AdvQuickAccessToolBar) then
    begin
      if (AComponent = AdvQuickAccessToolBar.Images) then
        ImageIndex := -1;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.WMLButtonDblClk(var Message: TWMLButtonDown);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.WndProc(var Message: TMessage);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.Paint;
begin
  if not Enabled then
  begin
    FState := absDisabled;
    FDragging := False;
  end
  else
  begin
    if (FState = absDisabled) then
      if FDown and (GroupIndex <> 0) then
        FState := absExclusive
      else
        FState := absUp;
  end;

  if (Style = tasCheck) and (Down) then
  begin
    FState := absDown;
  end;

  inherited;

  DrawButton(Canvas);
end;

//------------------------------------------------------------------------------

// Draw BackGround and border

procedure TAdvCustomToolBarButton.DrawButton(ACanvas: TCanvas);
var
  Clr, ClrTo, BrClr, TxtClr, DwClr, DwClrTo: TColor;
  R, {TextR,} BtnR, DwR: TRect;
  aGlyph: TBitmap;
  GDHoriztl: Boolean;
  AP: TPoint;
  ToolBarStyler: TCustomAdvToolBarStyler;

  procedure DrawArrow(ArP: TPoint; ArClr: TColor);
  begin
    if Position in [daTop, daBottom] then
    begin
      Canvas.Pen.Color := ArClr;
      Canvas.MoveTo(ArP.X, ArP.Y);
      Canvas.LineTo(ArP.X + 5, ArP.Y);
      Canvas.MoveTo(ArP.X + 1, ArP.Y + 1);
      Canvas.LineTo(ArP.X + 4, ArP.Y + 1);
      Canvas.Pixels[ArP.X + 2, ArP.Y + 2] := ArClr;
    end
    else
    begin
      Canvas.Pen.Color := ArClr;
      Canvas.MoveTo(ArP.X, ArP.Y);
      Canvas.LineTo(ArP.X, ArP.Y + 5);
      Canvas.MoveTo(ArP.X - 1, ArP.Y + 1);
      Canvas.LineTo(ArP.X - 1, ArP.Y + 4);
      Canvas.Pixels[ArP.X - 2, ArP.Y + 2] := ArClr;
    end;
  end;

begin
  R := ClientRect;
  BtnR := R;
  if Position in [daTop, daBottom] then
    DwR := Rect(BtnR.Right - FDropDownSectWidth, BtnR.Top, BtnR.Right, BtnR.Bottom)
  else
    DwR := Rect(BtnR.Left, BtnR.Bottom - FDropDownSectWidth, BtnR.Right, BtnR.Bottom);

  if FDropDownButton {and (Style <> tasCheck)} then
  begin
    if Position in [daTop, daBottom] then
      BtnR.Right := DwR.Left
    else
      BtnR.Bottom := DwR.Top;
  end;


  aGlyph := nil;
  Clr := clNone;
  ClrTo := clNone;
  BrClr := clNone;
  TxtClr := clNone;
  GDHoriztl := true;
  DwClr := clNone;
  DwClrTo := clNone;
  ToolBarStyler := nil;

  if Assigned(AdvToolBar) then
  begin
    ToolBarStyler := AdvToolBar.FCurrentToolBarStyler;
  end
  else if Assigned(AdvQuickAccessToolBar) then
  begin
    ToolBarStyler := AdvQuickAccessToolBar.CurrentToolBarStyler;
  end;

  if Style in [tasButton, tasCheck] then
  begin
    with ACanvas, FAppearance do
    begin
      if (State = absDisabled) or not Enabled then
      begin
        if Transparent then
        begin
          Clr := clNone;
          ClrTo := clNone;
          BrClr := clNone;
        end
        else
        begin
          Clr := Color;
          ClrTo := ColorTo;
          BrClr := BorderColor;
        end;

        DwClr := Clr;
        DwClrTo := ClrTo;
        TxtClr := CaptionTextColor;
        GDHoriztl := GradientDirection = gdHorizontal;
        aGlyph := GlyphDisabled;
      end
      else if State = absDropDown then
      begin

      end
      else if ((State = absDown) or ((FHot or FPropHot) and (State = absExclusive)) or (FMouseDownInControl)) and not((Style = tasCheck) and (State = absDown)) then
      begin
        if ParentStyler and Assigned(ToolBarStyler) then
        begin
          with ToolBarStyler.ButtonAppearance do  // AdvToolBar.FCurrentToolBarStyler.ButtonAppearance
          begin
            Clr := ColorDown;
            ClrTo := ColorDownTo;
            TxtClr := CaptionTextColorDown;
            BrClr := BorderDownColor;
            DwClr := ColorHot;
            DwClrTo := ColorHotTo;
            GDHoriztl := GradientDirectionDown = gdHorizontal;
            aGlyph := GlyphDown;
          end;
        end
        else
        begin
          Clr := ColorDown;
          ClrTo := ColorDownTo;
          TxtClr := CaptionTextColorDown;
          BrClr := BorderDownColor;
          DwClr := ColorHot;
          DwClrTo := ColorHotTo;
          GDHoriztl := GradientDirectionDown = gdHorizontal;
          aGlyph := GlyphDown;
        end;

      end
      else if (State = absExclusive) or ((Style = tasCheck) and (State = absDown)) then
      begin
        if ParentStyler and Assigned(ToolBarStyler) then
        begin
          with ToolBarStyler.ButtonAppearance do
          begin
            Clr := ColorChecked;
            ClrTo := ColorCheckedTo;
            TxtClr := CaptionTextColorChecked;
            BrClr := BorderCheckedColor;
            DwClr := Clr;
            DwClrTo := ClrTo;
            GDHoriztl := GradientDirectionChecked = gdHorizontal;
            aGlyph := GlyphChecked;
          end;
        end
        else
        begin
          Clr := ColorChecked;
          ClrTo := ColorCheckedTo;
          TxtClr := CaptionTextColorChecked;
          BrClr := BorderCheckedColor;
          DwClr := Clr;
          DwClrTo := ClrTo;
          GDHoriztl := GradientDirectionChecked = gdHorizontal;
          aGlyph := GlyphChecked;
        end;
      end
      else // if State = absUp then
      begin
        if (FHot or FPropHot) then
        begin
          if ParentStyler and Assigned(ToolBarStyler) then
          begin
            with ToolBarStyler.ButtonAppearance do
            begin
              Clr := ColorHot;
              ClrTo := ColorHotTo;
              TxtClr := CaptionTextColorHot;
              BrClr := BorderHotColor;
              GDHoriztl := GradientDirectionHot = gdHorizontal;
              aGlyph := GlyphHot;
            end;
          end
          else
          begin
            Clr := ColorHot;
            ClrTo := ColorHotTo;
            TxtClr := CaptionTextColorHot;
            BrClr := BorderHotColor;
            GDHoriztl := GradientDirectionHot = gdHorizontal;
            aGlyph := GlyphHot;
          end;

          DwClr := Clr;
          DwClrTo := ClrTo;
        end
        else // Normal Draw
        begin
          if self.Transparent then
          begin
            Clr := clNone;
            ClrTo := clNone;
            BrClr := clNone;
          end
          else
          begin
            Clr := Color;
            ClrTo := ColorTo;
            BrClr := BorderColor;
          end;

          if ParentStyler and Assigned(ToolBarStyler) then
          begin
            with ToolBarStyler.ButtonAppearance do
            begin
              TxtClr := CaptionTextColor;
            end;
          end
          else
            TxtClr := CaptionTextColor;

          DwClr := Clr;
          DwClrTo := ClrTo;
          GDHoriztl := GradientDirection = gdHorizontal;
          aGlyph := Glyph;
        end;
      end;

      // BackGround
      if (Clr <> clNone) and (ClrTo <> clNone) then
      begin
        if FDropDownButton {and (Style <> tasCheck)} then
          DrawGradient(aCanvas, DwClr, DwClrTo, 40, R, GDHoriztl);

        DrawGradient(aCanvas, Clr, ClrTo, 40, BtnR, GDHoriztl);
      end
      else
      if (Clr <> clNone) then
      begin
        if FDropDownButton {and (Style <> tasCheck)} then
        begin
          Brush.Color := DwClr;
          Pen.Color := DwClr;
          Rectangle(R)
        end;

        Brush.Color := Clr;
        Pen.Color := Clr;
        Rectangle(BtnR);
      end;

      // Border
      if BrClr <> clNone then
      begin
        Brush.Style := bsClear;
        Pen.Color := BrClr;
        if FDropDownButton and FDropDownSplit {and (Style <> tasCheck)} then
          Rectangle(R);

        if FDropDownButton and not FDropDownSplit {and (Style <> tasCheck)} then
          Rectangle(BtnR.Left, BtnR.Top, R.Right, BtnR.Bottom)
        else
          Rectangle(BtnR);
      end;

      if FMenuSel then
      begin
        if ParentStyler and Assigned(ToolBarStyler) then
        begin
          if Assigned(ToolBarStyler.CurrentAdvMenuStyler) then
            Pen.Color := ToolBarStyler.CurrentAdvMenuStyler.MenuBorderColor
        end;

        Pen.Color := clNavy;

        if FDropDownSplit then
        begin
          if Position in [daTop, daBottom] then
          begin
            MoveTo(BtnR.Left, DwR.Bottom);
            LineTo(BtnR.Left, DwR.Top);
            LineTo(DwR.Right - 1, DwR.Top);
            LineTo(DwR.Right - 1, DwR.Bottom);
          end
          else
          begin
            MoveTo(BtnR.Left, DwR.Bottom);
            LineTo(BtnR.Left, BtnR.Top);
            LineTo(DwR.Right - 1, BtnR.Top);
            LineTo(DwR.Right - 1, DwR.Bottom);
          end;
        end;
      end;

      if FDropDownButton {and (Style <> tasCheck)} then
      begin
        if Position in [daTop, daBottom] then
        begin
          AP.X := DwR.Left + ((DwR.Right - DwR.Left - 5) div 2);
          AP.Y := DwR.Top + ((DwR.Bottom - DwR.Top - 3) div 2) + 1;
        end
        else
        begin
          AP.X := DwR.Left + ((DwR.Right - DwR.Left - 3) div 2) + 1;
          AP.Y := DwR.Top + ((DwR.Bottom - DwR.Top - 5) div 2);
        end;
        DrawArrow(AP, clBlack);
      end;

      if Assigned(aGlyph) and (aGlyph.Empty) and not Glyph.Empty then
        aGlyph := Glyph;

      DrawGlyphAndCaption(ACanvas, BtnR, TxtClr, aGlyph);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.DrawGlyphAndCaption(ACanvas: TCanvas; R: TRect; TxtClr: TColor; aGlyph: TBitMap);
var
  GP, CP: TPoint;
  Tw, Th: integer;
  TextR, R2: TRect;
  uFormat: Cardinal;
  aWidth, aHeight: integer;
  sp: integer;
  tf: TFont;
  lf: TLogFont;
  imgidx: Integer;
  images: TCustomImageList;
  ToolBarStyler: TCustomAdvToolBarStyler;
begin
  TextR := R;
  ACanvas.Font.Assign(Font);

  Tw := 0;
  Th := Height;

  ToolBarStyler := nil;
  if Assigned(AdvToolBar) then
  begin
    ToolBarStyler := AdvToolBar.FCurrentToolBarStyler;
  end
  else if Assigned(AdvQuickAccessToolBar) then
  begin
    ToolBarStyler := AdvQuickAccessToolBar.CurrentToolBarStyler;
  end;


  if ShowCaption then
  begin
    if ParentStyler and Assigned(ToolBarStyler) then
    begin
      if IsMenuButton then
        ACanvas.Font.Assign(ToolBarStyler.CurrentAdvMenuStyler.RootItem.font)
      else
        ACanvas.Font.Assign(ToolBarStyler.ButtonAppearance.CaptionFont);
    end
    else
      ACanvas.Font.Assign(Font);

    R2 := Rect(0,0,1000,100);
    DrawText(ACanvas.Handle,PChar(Caption),Length(Caption), R2, DT_CALCRECT or DT_LEFT or DT_SINGlELINE);
    Tw := R2.Right;//ACanvas.TextWidth(Caption);
    Th := R2.Bottom;//ACanvas.TextHeight(Caption);
  end;

  uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
  aWidth := R.Right - R.Left;
  aHeight := R.Bottom - R.Top;

  if Position in [daTop, daBottom] then
    CP := Point(TextR.Left, TextR.Top)
  else
    CP := Point(TextR.Right+1 - (((TextR.Right - TextR.Left) - Th) div 2), TextR.Top + ((TextR.Bottom - TextR.Top) - Tw) div 2);

  if (Tw <= 0) or (Th <= 0) then
    sp := 0
  else
    sp := Spacing;

  images := nil;
  if Assigned(AdvToolBar) then
  begin
    images := AdvToolBar.Images;
  end
  else if Assigned(AdvQuickAccessToolBar) then
  begin
    images := AdvQuickAccessToolBar.Images;
  end;

  imgidx := ImageIndex;

  if (Action is TCustomAction) then
  begin
    if Assigned((Action as TCustomAction).ActionList) then
    begin
      if Assigned((Action as TCustomAction).ActionList.Images) then
        images := (Action as TCustomAction).ActionList.Images;

      imgidx := (Action as TCustomAction).ImageIndex;
    end;
  end;

  if FForceImageIndex and (ImageIndex >= 0) and (Assigned(AdvToolBar) or Assigned(AdvQuickAccessToolBar)) then
  begin
    if Assigned(AdvToolBar) then
    begin
      images := AdvToolBar.Images;
    end
    else if Assigned(AdvQuickAccessToolBar) then
    begin
      images := AdvQuickAccessToolBar.Images;
    end;
    imgidx := ImageIndex;
  end;

  if Assigned(AdvToolBar) and not Enabled and Assigned(AdvToolBar.DisabledImages) and (images <> nil) then
  begin
    images := AdvToolBar.DisabledImages;
  end
  else if Assigned(AdvQuickAccessToolBar) and not Enabled and Assigned(AdvQuickAccessToolBar.DisabledImages) and (images <> nil) then
  begin
    images := AdvQuickAccessToolBar.DisabledImages;
  end;

  if (imgidx >= 0) and (images <> nil) then
  begin
    if Position in [daTop, daBottom] then
    begin
      case GlyphPosition of
        gpLeft:
          begin
            GP.X := (aWidth - (Images.Width + Sp + Tw)) div 2;
            GP.Y := (Height - Images.Height) div 2;

            TextR := Rect(GP.X + Images.Width + Sp, R.Top, R.Right, R.Bottom);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_LEFT;
          end;
        gpRight:
          begin
            GP.X := aWidth - ((aWidth - (Images.Width + Sp + Tw)) div 2) - Images.Width;
            GP.Y := (Height - Images.Height) div 2;

            TextR := Rect(((aWidth - (Images.Width + Sp + Tw)) div 2), R.Top, GP.X - sp, R.Bottom);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_RIGHT;
          end;
        gpTop:
          begin
            GP.X := (aWidth - (Images.Width)) div 2;
            GP.Y := (Height - (Images.Height + Sp + Th)) div 2;

            TextR := Rect(R.Left, GP.Y + Images.Height + Sp, R.Right, R.Bottom);
            uFormat := DT_SINGLELINE or DT_TOP or DT_CENTER;
          end;
        gpBottom:
          begin
            GP.X := (aWidth - Images.Width) div 2;
            GP.Y := Height - ((Height - (Images.Height + Sp + Th)) div 2) - Images.Height;

            TextR := Rect(R.Left, GP.Y - Sp - Th, R.Right, GP.Y);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
      end;
    end
    else // if Position in [daLeft, daRight] then
    begin
      case GlyphPosition of
        gpLeft:
          begin
            GP.X := (aWidth - (Images.Width)) div 2;
            GP.Y := (aHeight - (Images.Height + Sp + Tw)) div 2;

          //TextR := Rect(R.Left , GP.Y + AdvToolBar.Images.Height + Sp, R.Right, R.Bottom);
            TextR := Rect(R.Right - ((aWidth - th) div 2), GP.Y + Images.Height + Sp, R.Right, R.Bottom);
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_CENTER or DT_TOP;
          end;
        gpRight:
          begin
            GP.X := (aWidth - (Images.Width)) div 2;
            GP.Y := aHeight - ((aHeight - (Images.Height + Sp + Tw)) div 2) - Images.Height;

          //TextR := Rect(R.Left , R.Top, R.Right, GP.Y - Sp);
            TextR := Rect(R.Right - ((aWidth - th) div 2), R.Top + ((aHeight - (Images.Height + Sp + Tw)) div 2), R.Right, GP.Y - Sp);
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_CENTER or DT_BOTTOM;
          end;
        gpTop:
          begin
            GP.X := aWidth - ((aWidth - (Images.Width + Sp + Th)) div 2) - Images.Width;
            GP.Y := (aHeight - Images.Height) div 2;

          //TextR := Rect(R.Left , R.Top, GP.X - sp, R.Bottom);
            TextR := Rect(R.Left, R.Top + (aHeight - Tw) div 2, GP.X - sp, R.Bottom);
            TextR.Left := TextR.Right - (TextR.Right - TextR.Left - Th) div 2;
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
        gpBottom:
          begin
            GP.X := (aWidth - (Images.Width + Sp + Th)) div 2;
            GP.Y := (aHeight - Images.Height) div 2;

          //TextR := Rect(GP.X + sp, R.Top, R.Right, R.Bottom);
            TextR := Rect(GP.X + sp + Images.Width, R.Top, R.Right, R.Bottom);
            TextR.Left := TextR.Right - (TextR.Right - TextR.Left - Th) div 2;
            CP := Point(TextR.Left, TextR.Top + (TextR.Bottom - TextR.Top - Tw) div 2);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
      end;
    end;

    if not AutoSize then
    begin
      if Position in [daTop, daBottom] then
      begin
        if GP.X < 0 then
        begin
          TextR.Left := TextR.Left + Abs(GP.X)+1;
          GP.X := GP.X + Abs(GP.X)+1;
          uFormat := uFormat or DT_END_ELLIPSIS;
        end;
      end
      else  // daLeft, daRight
      begin
        if GP.Y < 0 then
        begin
          TextR.Top := TextR.Top + Abs(GP.Y)+1;
          Cp.Y := Cp.Y + Abs(GP.Y)+1;
          GP.Y := GP.Y + Abs(GP.Y)+1;
          uFormat := uFormat or DT_END_ELLIPSIS;
        end;
      end;
    end;

    if DrawPosition.Enabled then
    begin
      GP.X := DrawPosition.ImageX;
      GP.Y := DrawPosition.ImageY;      
    end;
    
    if FMouseInControl and (FHot or FPropHot) and Shaded and Enabled and (FState = absUp)
      and not FMouseDownInControl and not FGlyphShade.Empty then
    begin
      if FShadedForGlyph then
        GenerateShade;
      FGlyphShade.TransparentMode := tmAuto;
      FGlyphShade.Transparent := True;
      ACanvas.Draw(GP.X + 2, GP.Y + 2, FGlyphShade);
    end;

    if not Enabled and ((Assigned(AdvToolBar) and Assigned(AdvToolBar.DisabledImages)) or
       (Assigned(AdvQuickAccessToolBar) and Assigned(AdvQuickAccessToolBar.DisabledImages))) then
      Images.Draw(ACanvas, GP.X, GP.Y, imgidx, True)
    else
      Images.Draw(ACanvas, GP.X, GP.Y, imgidx, Enabled);
  end
  else if (aGlyph <> nil) and not (aGlyph.Empty) then
  begin
    if Position in [daTop, daBottom] then
    begin
      case GlyphPosition of
        gpLeft:
          begin
            GP.X := (aWidth - (aGlyph.Width + Sp + Tw)) div 2;
            GP.Y := (Height - aGlyph.Height) div 2;

            TextR := Rect(GP.X + aGlyph.Width + Sp, R.Top, R.Right, R.Bottom);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_LEFT;
          end;
        gpRight:
          begin
            GP.X := aWidth - ((aWidth - (aGlyph.Width + Sp + Tw)) div 2) - aGlyph.Width;
            GP.Y := (Height - aGlyph.Height) div 2;

            TextR := Rect(((aWidth - (aGlyph.Width + Sp + Tw)) div 2), R.Top, GP.X - Sp, R.Bottom);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_RIGHT;
          end;
        gpTop:
          begin
            GP.X := (aWidth - (aGlyph.Width)) div 2;
            GP.Y := (Height - (aGlyph.Height + Sp + Th)) div 2;

            TextR := Rect(R.Left, GP.Y + aGlyph.Height + Sp, R.Right, R.Bottom);
            uFormat := DT_SINGLELINE or DT_TOP or DT_CENTER;
          end;
        gpBottom:
          begin
            GP.X := (aWidth - aGlyph.Width) div 2;
            GP.Y := Height - ((Height - (aGlyph.Height + Sp + Th)) div 2) - aGlyph.Height;

            TextR := Rect(R.Left, GP.Y - Sp - Th, R.Right, GP.Y);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
      end;
    end
    else // if Position in [daLeft, daRight] then
    begin

      case GlyphPosition of
        gpLeft:
          begin
            GP.X := (aWidth - (aGlyph.Width)) div 2;
            GP.Y := (aHeight - (aGlyph.Height + Sp + Tw)) div 2;

            //TextR := Rect(R.Left, GP.Y + aGlyph.Height + Sp, R.Right, R.Bottom);
            TextR := Rect(R.Right - ((aWidth - th) div 2), GP.Y + aGlyph.Height + Sp, R.Right, R.Bottom);
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_CENTER or DT_TOP;
          end;
        gpRight:
          begin
            GP.X := (aWidth - (aGlyph.Width)) div 2;
            GP.Y := aHeight - ((aHeight - (aGlyph.Height + Sp + Tw)) div 2) - aGlyph.Height;

            TextR := Rect(R.Left, R.Top, R.Right, GP.Y - Sp);
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_CENTER or DT_BOTTOM;
          end;
        gpTop:
          begin
            GP.X := aWidth - ((aWidth - (aGlyph.Width + Sp + Th)) div 2) - aGlyph.Width;
            GP.Y := (aHeight - aGlyph.Height) div 2;

            TextR := Rect(R.Left, R.Top, GP.X - sp, R.Bottom);
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
        gpBottom:
          begin
            GP.X := (aWidth - (aGlyph.Width + Sp + Th)) div 2;
            GP.Y := (aHeight - aGlyph.Height) div 2;

            TextR := Rect(GP.X + sp + aGlyph.Width, R.Top, R.Right, R.Bottom);
            TextR.Left := TextR.Right - (TextR.Right - TextR.Left - Th) div 2;
            CP := Point(TextR.Left, TextR.Top + (TextR.Bottom - TextR.Top - Tw) div 2);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
      end;
    end;

    if not AutoSize then
    begin
      if Position in [daTop, daBottom] then
      begin
        if GP.X < 0 then
        begin
          TextR.Left := TextR.Left + Abs(GP.X)+1;
          GP.X := GP.X + Abs(GP.X)+1;
          uFormat := uFormat or DT_END_ELLIPSIS;
        end;
      end
      else  // daLeft, daRight
      begin
        if GP.Y < 0 then
        begin
          TextR.Top := TextR.Top + Abs(GP.Y)+1;
          Cp.Y := Cp.Y + Abs(GP.Y)+1;
          GP.Y := GP.Y + Abs(GP.Y)+1;
          uFormat := uFormat or DT_END_ELLIPSIS;
        end;
      end;
    end;

    if DrawPosition.Enabled then
    begin
      GP.X := DrawPosition.ImageX;
      GP.Y := DrawPosition.ImageY;      
    end;

    if FMouseInControl and (FHot or FPropHot) and Shaded and Enabled and (FState = absUp)
      and not FMouseDownInControl and not FGlyphShade.Empty then
    begin
      if not FShadedForGlyph then
        GenerateShade;

      FGlyphShade.TransparentMode := tmAuto;
      FGlyphShade.Transparent := True;
      ACanvas.Draw(GP.X + 2, GP.Y + 2, FGlyphShade);
    end;

    AGlyph.TransparentMode := tmAuto;
    AGlyph.Transparent := true;
    ACanvas.Draw(GP.X, GP.Y, aGlyph);
  end
  else if Assigned(FPicture.Graphic) and not (FPicture.Graphic.Empty) then
  begin

    if Position in [daTop, daBottom] then
    begin
      case GlyphPosition of
        gpLeft:
          begin
            GP.X := (aWidth - (FPicture.Graphic.Width + Sp + Tw)) div 2;
            GP.Y := (Height - FPicture.Graphic.Height) div 2;

            TextR := Rect(GP.X + FPicture.Graphic.Width + Sp, R.Top, R.Right, R.Bottom);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_LEFT;
          end;
        gpRight:
          begin
            GP.X := aWidth - ((aWidth - (FPicture.Graphic.Width + Sp + Tw)) div 2) - FPicture.Graphic.Width;
            GP.Y := (Height - FPicture.Graphic.Height) div 2;

            TextR := Rect(((aWidth - (FPicture.Graphic.Width + Sp + Tw)) div 2), R.Top, GP.X, R.Bottom);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_RIGHT;
          end;
        gpTop:
          begin
            GP.X := (aWidth - (FPicture.Graphic.Width)) div 2;
            GP.Y := (Height - (FPicture.Graphic.Height + Sp + Th)) div 2;

            TextR := Rect(R.Left, GP.Y + FPicture.Graphic.Height + Sp, R.Right, R.Bottom);
            uFormat := DT_SINGLELINE or DT_TOP or DT_CENTER;
          end;
        gpBottom:
          begin
            GP.X := (aWidth - FPicture.Graphic.Width) div 2;
            GP.Y := Height - ((Height - (FPicture.Graphic.Height + Sp + Th)) div 2) - FPicture.Graphic.Height;

            TextR := Rect(R.Left, GP.Y - Sp - Th, R.Right, GP.Y);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
      end;
    end
    else // if Position in [daLeft, daRight] then
    begin

      case GlyphPosition of
        gpLeft:
          begin
            GP.X := (aWidth - (FPicture.Graphic.Width)) div 2;
            GP.Y := (aHeight - (FPicture.Graphic.Height + Sp + Tw)) div 2;

            //TextR := Rect(R.Left, GP.Y + FPicture.Graphic.Height + Sp, R.Right, R.Bottom);
            TextR := Rect(R.Right - ((aWidth - th) div 2), GP.Y + FPicture.Graphic.Height + Sp, R.Right, R.Bottom);
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_CENTER or DT_TOP;
          end;
        gpRight:
          begin
            GP.X := (aWidth - (FPicture.Graphic.Width)) div 2;
            GP.Y := aHeight - ((aHeight - (FPicture.Graphic.Height + Sp + Tw)) div 2) - FPicture.Graphic.Height;

            TextR := Rect(R.Left, R.Top, R.Right, GP.Y - Sp);
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_CENTER or DT_BOTTOM;
          end;
        gpTop:
          begin
            GP.X := aWidth - ((aWidth - (FPicture.Graphic.Width + Sp + Th)) div 2) - FPicture.Graphic.Width;
            GP.Y := (aHeight - FPicture.Graphic.Height) div 2;

            TextR := Rect(R.Left, R.Top, GP.X - sp, R.Bottom);
            CP := Point(TextR.Left, TextR.Top);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
        gpBottom:
          begin
            GP.X := (aWidth - (FPicture.Graphic.Width + Sp + Th)) div 2;
            GP.Y := (aHeight - FPicture.Graphic.Height) div 2;

            TextR := Rect(GP.X + sp + FPicture.Graphic.Width, R.Top, R.Right, R.Bottom);
            TextR.Left := TextR.Right - (TextR.Right - TextR.Left - Th) div 2;
            CP := Point(TextR.Left, TextR.Top + (TextR.Bottom - TextR.Top - Tw) div 2);
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER;
          end;
      end;

    end;

    if not AutoSize then
    begin
      if Position in [daTop, daBottom] then
      begin
        if GP.X < 0 then
        begin
          TextR.Left := TextR.Left + Abs(GP.X)+1;
          GP.X := GP.X + Abs(GP.X)+1;
          uFormat := uFormat or DT_END_ELLIPSIS;
        end;
      end
      else  // daLeft, daRight
      begin
        if GP.Y < 0 then
        begin
          TextR.Top := TextR.Top + Abs(GP.Y)+1;
          Cp.Y := Cp.Y + Abs(GP.Y)+1;
          GP.Y := GP.Y + Abs(GP.Y)+1;
          uFormat := uFormat or DT_END_ELLIPSIS;
        end;
      end;
    end;

    if DrawPosition.Enabled then
    begin
      GP.X := DrawPosition.ImageX;
      GP.Y := DrawPosition.ImageY;      
    end;

    if FMouseInControl and (FHot or FPropHot) and Shaded and Enabled and (FState = absUp)
      and not FMouseDownInControl and not FGlyphShade.Empty then
    begin
      if not FShadedForGlyph then
        GenerateShade;

      FGlyphShade.TransparentMode := tmAuto;
      FGlyphShade.Transparent := True;
      ACanvas.Draw(GP.X + 2, GP.Y + 2, FGlyphShade);
    end;

    //FPicture.Graphic.TransparentMode := tmAuto;

    if Enabled or not (Assigned(FPictureDisabled.Graphic) and not FPictureDisabled.Graphic.Empty) then
    begin
      FPicture.Graphic.Transparent := true;
      ACanvas.Draw(GP.X, GP.Y, FPicture.Graphic);
    end
    else
    begin
      FPictureDisabled.Graphic.Transparent := true;
      ACanvas.Draw(GP.X, GP.Y, FPictureDisabled.Graphic);
    end;
  end;

  if (Caption <> '') and ShowCaption then
  begin
    if ParentStyler and Assigned(ToolBarStyler) then
    begin
      if IsMenuButton then
        ACanvas.Font.Assign(ToolBarStyler.CurrentAdvMenuStyler.RootItem.font)
      else
        ACanvas.Font.Assign(ToolBarStyler.ButtonAppearance.CaptionFont);
    end
    else
      ACanvas.Font.Assign(Font);

    // Make sure to use a truetype font!
    // Font.Name := 'Tahoma';

    if Position in [daLeft, daRight] then
    begin
      tf := TFont.Create;
      try
{$IFNDEF TMSDOTNET}
        FillChar(lf, SizeOf(lf), 0);
{$ENDIF}
        tf.Assign(aCanvas.Font);
{$IFNDEF TMSDOTNET}
        GetObject(tf.Handle, SizeOf(Lf), @Lf);
{$ENDIF}
{$IFDEF TMSDOTNET}
        GetObject(tf.Handle, Marshal.SizeOf(TypeOf(Lf)), Lf);
{$ENDIF}

        lf.lfEscapement := -900;
        lf.lfOrientation := 30;

        tf.Handle := CreateFontIndirect(Lf);
        aCanvas.Font.Assign(tf);
      finally
        tf.Free;
      end;
    end;

    aCanvas.font.Color := TxtClr;
    aCanvas.Brush.Style := bsClear;
    //DrawText(aCanvas.Handle, PChar(Caption), -1, TextR , DT_SINGLELINE or DT_VCENTER or DT_CENTER);

    with aCanvas do
    begin

      if not AutoSize then
      begin
        if Position in [daTop, daBottom] then
        begin
          if (TextR.Left < 0) then
          begin
            TextR.Left := 1;
            uFormat := DT_SINGLELINE or DT_VCENTER or DT_CENTER or DT_END_ELLIPSIS;
          end;
        end
        else  // daLeft, daRight
        begin
          if (CP.Y < 0) then
          begin
            CP.Y := 1;
            uFormat := uFormat or DT_END_ELLIPSIS;
          end;
        end;
      end;

      if DrawPosition.Enabled then
      begin
        uFormat := DT_SINGLELINE or DT_LEFT or DT_END_ELLIPSIS;
        TextR.Left := DrawPosition.TextX;
        TextR.Top := DrawPosition.TextY;
        TextR.Right := Width;
        TextR.Bottom := Height;
      end;


      if Position in [daTop, daBottom] then
      begin
        if State = absDisabled then
        begin
          OffsetRect(TextR, 1, 1);
          Font.Color := clBtnHighlight;
          DrawText(Handle, PChar(Caption), -1, TextR, uFormat);
          OffsetRect(TextR, -1, -1);
          Font.Color := clBtnShadow;
          DrawText(Handle, PChar(Caption), -1, TextR, uFormat);
        end else
          DrawText(Handle, PChar(Caption), -1, TextR, uFormat);
      end
      else
      begin
        if State = absDisabled then
        begin
          OffsetRect(TextR, 1, 1);
          Font.Color := clBtnHighlight;
       //   TextOut(CP.X, CP.Y, Caption);
          DrawVerticalText(ACanvas, Caption, CP);
               //DrawText(Handle, PChar(Caption), -1, TextR, uFormat);
               //OffsetRect(TextR, -1, -1);
          CP := Point(CP.X - 1, CP.Y - 1);
          Font.Color := clBtnShadow;
               //DrawText(Handle, PChar(Caption), -1, TextR, uFormat);
       //   TextOut(CP.X, CP.Y, Caption);
          DrawVerticalText(ACanvas, Caption, CP);
        end else
       //   TextOut(CP.X {TextR.Right - (((TextR.Right - TextR.Left)- Th) div 2)}, CP.Y, Caption);
          DrawVerticalText(ACanvas, Caption, CP);
               //DrawText(Handle, PChar(Caption), -1, TextR, uFormat);
      end;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.GenerateShade;
var
  r: TRect;
  bmp, bmp2: TBitmap;
begin
  if (ImageIndex >= 0) and ((Assigned(AdvToolBar) and (AdvToolBar.Images <> nil)) or
     (Assigned(AdvQuickAccessToolBar) and (AdvQuickAccessToolBar.Images <> nil))) then
  begin
    FShadedForGlyph := false;

    bmp2 := TBitMap.Create;
    if (Assigned(AdvToolBar) and (AdvToolBar.Images <> nil)) then
    begin
      bmp2.Width := FAdvToolBar.Images.Width;
      bmp2.Height := FAdvToolBar.Images.Height;
      FAdvToolBar.Images.Draw(bmp2.Canvas, 0, 0, ImageIndex);
    end
    else if Assigned(AdvQuickAccessToolBar) and (AdvQuickAccessToolBar.Images <> nil) then
    begin
      bmp2.Width := AdvQuickAccessToolBar.Images.Width;
      bmp2.Height := AdvQuickAccessToolBar.Images.Height;
      AdvQuickAccessToolBar.Images.Draw(bmp2.Canvas, 0, 0, ImageIndex);
    end;

    FGlyphShade.Width := bmp2.Width;
    FGlyphShade.Height := bmp2.Height;

    r := Rect(0, 0, FGlyphShade.Width, FGlyphShade.Height);
    FGlyphShade.Canvas.Brush.Color := ColorToRGB(clBlack);
    FGlyphShade.Canvas.BrushCopy(r, bmp2, r, bmp2.Canvas.Pixels[0, bmp2.Height - 1]);
    FGlyphShade.Canvas.CopyMode := cmSrcInvert;
    FGlyphShade.Canvas.CopyRect(r, bmp2.Canvas, r);

    bmp := TBitmap.Create;
    bmp.Width := bmp2.Width;
    bmp.Height := bmp2.Height;
    bmp.Canvas.Brush.Color := ColorToRGB(clGray);
    bmp.Canvas.BrushCopy(r, FGlyphShade, r, ColorToRGB(clBlack));

    FGlyphShade.Canvas.CopyMode := cmSrcCopy;
    FGlyphShade.Canvas.CopyRect(r, bmp.Canvas, r);
    bmp.Free;
    bmp2.Free;
  end
  else if not FGlyph.Empty then
  begin
    FShadedForGlyph := true;

    FGlyphShade.Width := FGlyph.Width;
    FGlyphShade.Height := FGlyph.Height;

    r := Rect(0, 0, FGlyphShade.Width, FGlyphShade.Height);
    FGlyphShade.Canvas.Brush.Color := ColorToRGB(clBlack);
    FGlyphShade.Canvas.BrushCopy(r, FGlyph, r, FGlyph.Canvas.Pixels[0, FGlyph.Height - 1]);
    FGlyphShade.Canvas.CopyMode := cmSrcInvert;
    FGlyphShade.Canvas.CopyRect(r, FGlyph.Canvas, r);

    bmp := TBitmap.Create;
    bmp.Width := FGlyph.Width;
    bmp.Height := FGlyph.Height;
    bmp.Canvas.Brush.Color := ColorToRGB(clGray);
    bmp.Canvas.BrushCopy(r, FGlyphShade, r, ColorToRGB(clBlack));

    FGlyphShade.Canvas.CopyMode := cmSrcCopy;
    FGlyphShade.Canvas.CopyRect(r, bmp.Canvas, r);
    bmp.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.ThemeAdapt;
begin

end;

//------------------------------------------------------------------------------

{$IFNDEF TMSDOTNET}

procedure TAdvCustomToolBarButton.UpdateExclusive;
var
  Msg: TMessage;
begin
  if (FGroupIndex <> 0) and (Parent <> nil) then
  begin
    Msg.Msg := CM_BUTTONPRESSED;
    Msg.WParam := FGroupIndex;
    Msg.LParam := Longint(Self);
    Msg.Result := 0;
    Parent.Broadcast(Msg);

    if Assigned(FAdvToolBar) and not (Parent is TAdvCustomToolBar) then
      FAdvToolBar.Broadcast(Msg)
    else if Assigned(AdvToolBar) and (Parent is TAdvCustomToolBar) and Assigned(AdvToolBar.FOptionWindowPanel) then
      FAdvToolBar.FOptionWindowPanel.Broadcast(Msg)
    else if Assigned(AdvQuickAccessToolBar) then
      AdvQuickAccessToolBar.Broadcast(Msg);
  end;
end;
{$ENDIF}

//------------------------------------------------------------------------------

{$IFDEF TMSDOTNET}

procedure TAdvCustomToolBarButton.ButtonPressed(Group: Integer; Button: TAdvCustomToolBarButton);
begin
  if (Group = FGroupIndex) and (Button <> Self) then
  begin
    if Button.Down and FDown then
    begin
      FDown := False;
      FState := absUp;
      if (Action is TCustomAction) then
        TCustomAction(Action).Checked := False;
      Invalidate;
    end;
    FAllowAllUp := Button.AllowAllUp;
  end;
end;

procedure TAdvCustomToolBarButton.UpdateExclusive;
var
  I: Integer;
begin
  if (FGroupIndex <> 0) and (Parent <> nil) then
  begin
    for I := 0 to Parent.ControlCount - 1 do
      if Parent.Controls[I] is TSpeedButton then
        TAdvToolButton(Parent.Controls[I]).ButtonPressed(FGroupIndex, Self);
  end;
end;
{$ENDIF}

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.UpdateTracking;
var
  P: TPoint;
begin
  if FFlat then
  begin
    if Enabled then
    begin
      GetCursorPos(P);
      FMouseInControl := not (FindDragTarget(P, True) = Self);
      if FMouseInControl then
        Perform(CM_MOUSELEAVE, 0, 0)
      else
        Perform(CM_MOUSEENTER, 0, 0);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetAllowAllUp(Value: Boolean);
begin
  if FAllowAllUp <> Value then
  begin
    FAllowAllUp := Value;
    UpdateExclusive;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetAutoThemeAdapt(const Value: Boolean);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetDown(Value: Boolean);
begin
  if (csLoading in ComponentState) then
    FInitialDown := Value;

  if (FGroupIndex = 0) and (Style = tasButton) then
    Value := False;

  if (Style = tasCheck) then
  begin
    FDown := Value;
    if FDown then
      FState := absDown
    else
      FState := absUp;
    Repaint;
    Exit;
  end;

  if Value <> FDown then
  begin
    if FDown and (not FAllowAllUp) then Exit;
    FDown := Value;
    if Value then
    begin
      if FState = absUp then Invalidate;
      FState := absExclusive
    end
    else
    begin
      FState := absUp;
      Repaint;
    end;
    if Value then UpdateExclusive;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetDropDownButton(const Value: Boolean);
begin
  if FDropDownButton <> Value then
  begin
    //if (Value and not (Style = tasCheck)) or not Value then
      FDropDownButton := Value;
    AdjustSize;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetFlat(Value: Boolean);
begin
  FFlat := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetGlyph(Value: TBitmap);
var
  x, y: Integer;
  PxlColor: TColor;
  c: byte;
begin
  FGlyph.Assign(Value);
  //if no disabled glyph is given... add this automatically...
  if FGlyphDisabled.Empty then
  begin
    FGlyphDisabled.Assign(Value);
    for x := 0 to FGlyphDisabled.Width - 1 do
      for y := 0 to FGlyphDisabled.Height - 1 do
      begin
        PxlColor := ColorToRGB(FGlyphDisabled.Canvas.Pixels[x, y]);
        c := Round((((PxlColor shr 16) + ((PxlColor shr 8) and $00FF) +
          (PxlColor and $0000FF)) div 3)) div 2 + 96;
        FGlyphDisabled.Canvas.Pixels[x, y] := RGB(c, c, c);
      end;
  end;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetGlyphDisabled(const Value: TBitmap);
begin
  FGlyphDisabled.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetGlyphDown(const Value: TBitmap);
begin
  FGlyphDown.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetGlyphHot(const Value: TBitmap);
begin
  FGlyphHot.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetGlyphPosition(
  const Value: TGlyphPosition);
begin
  if FGlyphPosition <> Value then
  begin
    FGlyphPosition := Value;
    AdjustSize;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetGroupIndex(Value: Integer);
begin
  if FGroupIndex <> Value then
  begin
    FGroupIndex := Value;
    UpdateExclusive;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetParentStyler(const Value: Boolean);
begin
  if FParentStyler <> Value then
  begin
    FParentStyler := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetShaded(const Value: Boolean);
begin
  FShaded := Value;
  if FShaded then
    if not (csLoading in ComponentState) then
    begin
      GenerateShade;
    end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetSpacing(Value: Integer);
begin
  if FSpacing <> Value then
  begin
    FSpacing := Value;
    AdjustSize;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetState(const Value: TAdvButtonState);
begin
  if FState <> Value then
  begin
    FState := Value;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetStyle(const Value: TAdvToolButtonStyle);
begin
  if FStyle <> Value then
  begin
    FStyle := Value;
    //if (Value = tasCheck) and DropDownButton then
    //  DropDownButton := false;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetTransparent(const Value: Boolean);
begin
  if FTransparent <> Value then
  begin
    FTransparent := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBarButton.IsMenuButton: Boolean;
begin
  Result := false;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetRounded(const Value: Boolean);
begin
  FRounded := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.DoDropDown;
begin
  if IsMenuButton then
  begin
    State := absDropDown;
    InvalidateMe;
    CheckMenuDropdown;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetGlyphChecked(const Value: TBitmap);
begin
  FGlyphChecked.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.InvalidateMe;
begin
  invalidate;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBarButton.CheckMenuDropdown: Boolean;
begin
  Result := not (csDesigning in ComponentState) and ((DropdownMenu <> nil) and
    DropdownMenu.AutoPopup or (MenuItem <> nil)) and (FAdvToolBar <> nil) and
    FAdvToolBar.CheckMenuDropdown(Self);
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBarButton.GetIndex: Integer;
begin
  if FAdvToolBar <> nil then
    Result := FAdvToolBar.FATBControls.IndexOf(Self)
  else
    Result := -1;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetBounds(ALeft, ATop, AWidth,
  AHeight: Integer);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetGrouped(const Value: Boolean);
begin
  FGrouped := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetMenuItem(const Value: TMenuItem);
begin
  { Copy all appropriate values from menu item }
  if Value <> nil then
  begin
    if FMenuItem <> Value then
      Value.FreeNotification(Self);
    Action := Value.Action;
    Caption := Value.Caption;
    Down := Value.Checked;
    Enabled := Value.Enabled;
    Hint := Value.Hint;
    ImageIndex := Value.ImageIndex;
    Visible := Value.Visible;
  end;
  FMenuItem := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.OnDropDownHide;
begin
  FMouseDownInControl := false;
  FMouseInControl := false;
  FHot := false;
  State := absUp;
  InvalidateMe;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetImageIndex(const Value: integer);
begin
  if FImageIndex <> Value then
  begin
    FImageIndex := Value;
   {
    if (FImageIndex >= 0) then
    begin
      if not Assigned(FAdvToolBar) then
        FImageIndex := -1;

      if Assigned(FAdvToolBar) and not Assigned(FAdvToolBar.Images) then
        FImageIndex := -1;
    end;
   }
    if FShaded then
      GenerateShade;

    AdjustSize;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.ButtonDown;
begin
  //State:= absDown;
//InvalidateMe;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.PopupBtnDown;
begin
  //State:= absDropDown;
  InvalidateMe;
  if Assigned(FOnDropDown) then
    FOnDropDown(self);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetAutoSize(Value: Boolean);
begin
  {$IFNDEF DELPHI6_LVL}
  if Value then
    AdjustSize;
  FAutoSize := Value;
  {$ENDIF}
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.AdjustSize;
var
  ImgS, CS, W, H: integer;
  images: TCustomImageList;
  imgidx: Integer;
  R: TRect;
  ToolBarStyler: TCustomAdvToolBarStyler;
begin
  if not Assigned(Parent) then
    Exit;

  if AutoSize then
  begin
    ImgS := 0;
    W := 0;
    H := 0;

    images := nil;
    ToolBarStyler := nil;
    
    if Assigned(AdvToolBar) then
    begin
      images := AdvToolBar.Images;
      ToolBarStyler := AdvToolBar.FCurrentToolBarStyler;
    end
    else if Assigned(AdvQuickAccessToolBar) then
    begin
      images := AdvQuickAccessToolBar.Images;
      ToolBarStyler := AdvQuickAccessToolBar.CurrentToolBarStyler;
    end;

    imgidx := ImageIndex;

    if (Action is TCustomAction) then
    begin
      if Assigned((Action as TCustomAction).ActionList) then
      begin
        if Assigned((Action as TCustomAction).ActionList.Images) then
          images := (Action as TCustomAction).ActionList.Images;
        imgidx := (Action as TCustomAction).ImageIndex;
      end;
    end;

    if Position in [daTop, daBottom] then
    begin
      if (imgidx >= 0) and (Images <> nil) then
      begin
        ImgS := Images.Width;
        H := Images.Height;
      end
      else
      begin
        if not Glyph.Empty then
        begin
          ImgS := Glyph.Width;
          H := Glyph.Height;
        end;
        if not GlyphHot.Empty then
        begin
          ImgS := max(ImgS, GlyphHot.Width);
          H := Max(H, GlyphHot.Height);
        end;
        if not GlyphDown.Empty then
        begin
          ImgS := max(ImgS, GlyphDown.Width);
          H := Max(H, GlyphDown.Height);
        end;
        if not GlyphChecked.Empty then
        begin
          ImgS := max(ImgS, GlyphChecked.Width);
          H := Max(H, GlyphChecked.Height);
        end;
        if not GlyphDisabled.Empty then
        begin
          ImgS := max(ImgS, GlyphDisabled.Width);
          H := Max(H, GlyphDisabled.Height);
        end;

        // Checking Picture
        if (Glyph.Empty) and (GlyphHot.Empty) and GlyphDown.Empty and GlyphChecked.Empty and Assigned(FPicture) then
        begin
          if Assigned(FPicture.Graphic) and not Fpicture.Graphic.Empty then
          begin
            ImgS := Fpicture.Width;
            H := Fpicture.Height;
          end;
        end;

      end;

      if ParentStyler and Assigned(ToolBarStyler) and Assigned(ToolBarStyler.CurrentAdvMenuStyler) then
      begin
        if IsMenuButton then
          Canvas.Font.Assign(ToolBarStyler.CurrentAdvMenuStyler.RootItem.font)
        else
          Canvas.Font.Assign(ToolBarStyler.ButtonAppearance.CaptionFont);
      end
      else
        Canvas.Font.Assign(Font);

     { if ParentStyler and Assigned(AdvToolBar) and Assigned(AdvToolBar.ToolBarStyler) then
        Canvas.Font.Assign(AdvToolBar.ToolBarStyler.AdvMenuStyler.RootItem.font)
      else
        Canvas.Font.Assign(Font);
      }
      CS := 0;

      if ShowCaption and (Caption <> '') then
      begin
        R := Rect(0,0,1000,100);
        DrawText(Canvas.Handle,PChar(Caption),Length(Caption), R, DT_CALCRECT or DT_LEFT or DT_SINGlELINE);
        CS := R.Right;
      end;
      // CS := Canvas.TextWidth(Caption);

      if GlyphPosition in [gpLeft, gpRight] then
      begin
        if (ImgS > 0) and (CS > 0) then
          W := ImgS + Spacing + CS
        else if ImgS > 0 then
          W := ImgS
        else if CS > 0 then
          W := CS;

        W := W + FOffSet * 2;
        if Assigned(AdvQuickAccessToolBar) then
          W := W + FOffSet * 2;

        H := Max(H, Canvas.TextHeight('gh'));

        H := H + FOffSet * 2;
      end
      else if GlyphPosition in [gpTop, gpBottom] then
      begin
        W := Max(ImgS, CS);
        W := W + FOffSet * 2;
        H := H + Spacing + Canvas.TextHeight('gh') + FOffSet * 2;
      end
      else
      begin
        W := CS + Spacing * 2;
        H := Max(H, Canvas.TextHeight('gh'));
      end;

      //Inc(H, FOffSet*2);

      W := Max(W, MIN_BUTTONSIZE);
      if DropDownButton then
        W := W + FDropDownSectWidth;

      Width := W;

      //if Assigned(FAdvToolBar) then
        //Height := FAdvToolBar.Height - 4;
      if Assigned(FAdvToolBar) then
      begin
        if (FAdvToolBar.ToolBarState = tsFloating) then
          H := max(H, FAdvToolBar.FSizeAtDock - 4)
        else
        begin
          if FAdvToolBar.ShowCaption then
            H := max(H, FAdvToolBar.Height - 4 - FAdvToolBar.CaptionHeight)
          else
            H := max(H, FAdvToolBar.Height - 4);
          {EH := 0;
          EW := 0;
          FAdvToolBar.GetMaxExternalControlSize(EW, EH);
          if EH > 0 then
            H := max(H, EH);  }
        end;
      end
      else if Assigned(AdvQuickAccessToolBar) then
      begin
        H := max(H, AdvQuickAccessToolBar.GetMyClientRect.Bottom - AdvQuickAccessToolBar.GetMyClientRect.Top - 1);
      end;

      if Assigned(FAdvToolBar) then
      begin
        if not FAdvToolBar.AutoPositionControls and (FAdvToolBar.ToolBarState <> tsFloating) then
        begin
          // do nothing
        end
        else
          Height := H;
      end
      else if Assigned(AdvQuickAccessToolBar) then
      begin
        Height := H;
      end;
    end
    else // if Position in [daLeft, daRight] then
    begin
      if (imgidx >= 0) and Assigned(Images) then
      begin
        ImgS := Images.Height;
        W := Images.Width;
      end
      else
      begin
        if not Glyph.Empty then
        begin
          ImgS := Glyph.Height;
          W := Glyph.Width;
        end;
        if not GlyphHot.Empty then
        begin
          ImgS := max(ImgS, GlyphHot.Height);
          W := Max(W, GlyphHot.Width);
        end;
        if not GlyphDown.Empty then
        begin
          ImgS := max(ImgS, GlyphDown.Height);
          W := Max(W, GlyphDown.Width);
        end;
        if not GlyphChecked.Empty then
        begin
          ImgS := max(ImgS, GlyphChecked.Height);
          W := Max(W, GlyphChecked.Width);
        end;
        if not GlyphDisabled.Empty then
        begin
          ImgS := max(ImgS, GlyphDisabled.Height);
          W := Max(W, GlyphDisabled.Width);
        end;

        // Checking Picture
        if (Glyph.Empty) and (GlyphHot.Empty) and GlyphDown.Empty and GlyphChecked.Empty and Assigned(FPicture) then
        begin
          if Assigned(FPicture.Graphic) and not Fpicture.Graphic.Empty then
          begin
            ImgS := Fpicture.Height;
            W := Fpicture.Width;
          end;
        end;

      end;

      // Assigning Font
      if ParentStyler and Assigned(AdvToolBar) and Assigned(AdvToolBar.FCurrentToolBarStyler) and Assigned(AdvToolBar.FCurrentToolBarStyler.CurrentAdvMenuStyler) then
      begin
        if IsMenuButton then
          Canvas.Font.Assign(AdvToolBar.FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.font)
        else
          Canvas.Font.Assign(AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.CaptionFont);
      end
      else
        Canvas.Font.Assign(Font);

      CS := 0;
      if ShowCaption and (Caption <> '') then
      begin
        R := Rect(0,0,1000,100);
        DrawText(Canvas.Handle,PChar(Caption),Length(Caption), R, DT_CALCRECT or DT_LEFT or DT_SINGlELINE);
        CS := R.Right;
      end;
      //CS := Canvas.TextWidth(Caption);

      if GlyphPosition in [gpLeft, gpRight] then
      begin
        if (ImgS > 0) and (CS > 0) then
          H := ImgS + Spacing + CS
        else if ImgS > 0 then
          H := ImgS
        else if CS > 0 then
          H := CS;

        H := H + FOffSet * 2;
        W := Max(W, Canvas.TextHeight('gh'));

        W := W + FOffSet * 2;
      end
      else if GlyphPosition in [gpTop, gpBottom] then
      begin
        H := Max(ImgS, CS);
        H := H + FOffSet * 2;
        W := W + Spacing + Canvas.TextHeight('gh') + FOffSet * 2;
      end
      else
      begin
        H := CS + Spacing * 2;
        W := Max(W, Canvas.TextHeight('gh'));
      end;

      //Inc(W, FOffSet*2);

      H := Max(H, MIN_BUTTONSIZE);
      if DropDownButton then
        H := H + FDropDownSectWidth;

      Height := H;
      //if Assigned(FAdvToolBar) then
        //Width := FAdvToolBar.Width - 4;
      if Assigned(FAdvToolBar) then
        if (FAdvToolBar.ToolBarState = tsFloating) then
          W := Max(W, FAdvToolBar.FSizeAtDock - 4)
        else
        begin
          if FAdvToolBar.ShowCaption then
            W := Max(W, FAdvToolBar.Width - 4 - FAdvToolBar.CaptionHeight)
          else
            W := Max(W, FAdvToolBar.Width - 4);
          {EH := 0;
          EW := 0;
          FAdvToolBar.GetMaxExternalControlSize(EW, EH);
          if EW > 0 then
            W := max(W, EW);}
        end;

      if Assigned(FAdvToolBar) and not FAdvToolBar.AutoPositionControls and (FAdvToolBar.ToolBarState <> tsFloating) then
      begin
        // do nothing 
      end
      else
        Width := W;
    end;
  end;
end;

//------------------------------------------------------------------------------

{$IFNDEF TMSDOTNET}

procedure TAdvCustomToolBarButton.CMButtonPressed(var Message: TMessage);
var
  Sender: TAdvCustomToolBarButton;
begin
  if Message.WParam = FGroupIndex then
  begin
    Sender := TAdvCustomToolBarButton(Message.LParam);
    if Sender <> Self then
    begin
      if Sender.Down and FDown then
      begin
        FDown := False;
        FState := absUp;
        if (Action is TCustomAction) then
          TCustomAction(Action).Checked := False;
        Invalidate;
      end;
      FAllowAllUp := Sender.AllowAllUp;
    end;
  end;
end;
{$ENDIF}

//------------------------------------------------------------------------------

{$IFDEF DELPHI6_LVL}

procedure TAdvCustomToolBarButton.ActionChange(Sender: TObject; CheckDefaults: Boolean);
begin
  inherited ActionChange(Sender, CheckDefaults);
  if Sender is TCustomAction then
    with TCustomAction(Sender) do
    begin
      if CheckDefaults or (Self.GroupIndex = 0) then
        Self.GroupIndex := GroupIndex;
      Self.ImageIndex := ImageIndex;
    end;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBarButton.GetActionLinkClass: TControlActionLinkClass;
begin
  Result := TAdvToolBarButtonActionLink;
end;
{$ENDIF}

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetAppearance(
  const Value: TButtonAppearance);
begin
  FAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.OnAppearanceChange(Sender: TObject);
begin
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetShowCaption(const Value: Boolean);
begin
  FShowCaption := Value;
  AdjustSize;
  Invalidate;
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBarButton.GetAutoSize: Boolean;
begin
  {$IFNDEF DELPHI6_LVL}
  Result := FAutoSize;
  {$ELSE}
  Result := inherited AutoSize;
  {$ENDIF}
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBarButton.GetVersionNr: integer;
begin
  Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;

//------------------------------------------------------------------------------

function TAdvCustomToolBarButton.GetVersion: string;
var
  vn: Integer;
begin
  vn := GetVersionNr;
  Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn)));
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetVersion(const Value: string);
begin

end;

//------------------------------------------------------------------------------

function TAdvCustomToolBarButton.GetHot: Boolean;
begin
  Result := FPropHot;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetHot(const Value: Boolean);
var
  OldV: Boolean;
begin
  OldV := FPropHot;
  FPropHot := Value;
  if (State <> absUp) then
    FPropHot := false;

  if Assigned(FAdvToolBar) then
    FAdvToolBar.UpdateButtonHot(self)
  else if Assigned(AdvQuickAccessToolBar) then
  begin
  
  end
  else
    FPropHot := false;
  if OldV <> FPropHot then
    InvalidateMe;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetPicture(const Value: TPicture);
begin
  FPicture.Assign(Value);
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetPictureDisabled(const Value: TPicture);
begin
  FPictureDisabled.Assign(Value);
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.UnHotTimerOnTime(Sender: TObject);
var
  CurP: TPoint;
begin
  GetCursorPos(CurP);
  CurP := ScreenToClient(CurP);
  if (not PtInRect(ClientRect, CurP)) or (DropDownButton and IsMenuButton and FMenuSel and (Assigned(DropDownMenu) or (MenuItem <> nil))) then
  begin
    FUnHotTimer.Enabled := False;
    FMouseInControl := false;
    FHot := false;

    if Assigned(FAdvToolBar) then
    begin
      if not (FAdvToolBar.FInMenuLoop and FAdvToolBar.FMenuFocused) then
        Hot := False;
    end
    else if Assigned(AdvQuickAccessToolBar) then
    begin
      Hot := False;
    end;

    if Enabled then
      InvalidateMe;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetDrawPosition(
  const Value: TAdvToolBarButtonDrawPosition);
begin
  FDrawPosition.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.PositionChanged(Sender: TObject);
begin
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetParent(AParent: TWinControl);
begin
  inherited;
  if (Parent is TAdvToolBarContainer) then
    FAdvToolBar := TAdvToolBarContainer(Parent).AdvToolBar;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetOfficeHint(const Value: TAdvHintInfo);
begin
  FOfficeHint.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarButton.SetForceImageIndex(const Value: Boolean);
begin
  FForceImageIndex := Value;
end;

//------------------------------------------------------------------------------

{ TAdvCustomToolBarControl }

constructor TAdvCustomToolBarControl.Create(AOwner: TComponent);
begin
  inherited;
  FPosition := daTop;
  FAdvToolBar := nil;
  FAdvQuickAccessToolBar := nil;
end;

//------------------------------------------------------------------------------

destructor TAdvCustomToolBarControl.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarControl.ReadState(Reader: TReader);
begin
  inherited ReadState(Reader);
  if Reader.Parent is TAdvToolBar then
  begin
    AdvToolBar := TAdvToolBar(Reader.Parent);
  end
  else if (Reader.Parent is TAdvQuickAccessToolBar) then
  begin
    AdvQuickAccessToolBar := TAdvQuickAccessToolBar(Reader.Parent);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarControl.SetAdvToolBar(
  const Value: TAdvCustomToolBar);
begin
  if FAdvToolBar <> Value then
  begin
    if FAdvToolBar <> nil then
      FAdvToolBar.RemoveControl(self);

    Parent := Value;

    if Value <> nil then
      Value.InsertControl(self);

    if (Value <> nil) and (FAdvToolBar = nil) then
      raise exception.Create('AdvToolBar not set');
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarControl.SetPosition(const Value: TDockAlign);
begin
  if FPosition <> Value then
  begin
    FPosition := Value;
    AdjustSize;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomToolBarControl.SetAdvQuickAccessToolBar(
  const Value: TAdvQuickAccessToolBar);
begin
  if (FAdvQuickAccessToolBar <> Value) then
  begin
    FAdvQuickAccessToolBar := Value;
  end;
end;

//------------------------------------------------------------------------------

{ TAdvToolBarSeparator }

procedure TAdvToolBarSeparator.AdjustSize;
begin
  if AutoSize then
  begin
    if Position in [daTop, daBottom] then
    begin
      Width := DEFAULT_SEPARATORWIDTH;
      if Assigned(FAdvToolBar) then
        Height := FAdvToolBar.Height - 4;
    end
    else // if Position in [daLeft, daRight] then
    begin
      Height := DEFAULT_SEPARATORWIDTH;
      if Assigned(FAdvToolBar) then
        Width := FAdvToolBar.Width - 4;
    end;
  end;
end;

//------------------------------------------------------------------------------

constructor TAdvToolBarSeparator.Create(AOwner: TComponent);
begin
  inherited;
  AutoSize := true;
  FLineColor := clBtnShadow;
  FSeparatorStyle := ssOffice2003;
  SetBounds(0, 0, DEFAULT_SEPARATORWIDTH, 22);
end;

//------------------------------------------------------------------------------

destructor TAdvToolBarSeparator.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarSeparator.Assign(Source: TPersistent);
begin
  if Source is TAdvToolBarSeparator then
  begin
    SeparatorStyle := (Source as TAdvToolBarSeparator).SeparatorStyle;
    LineColor := (Source as TAdvToolBarSeparator).LineColor;
  end
  else
    inherited Assign(Source);                               
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarSeparator.Paint;
var
  R: TRect;

  procedure DrawSepLine(FromPoint, ToPoint: TPoint; Embossed: Boolean);
  begin
    with Canvas do
    begin
      if Embossed then
        Pen.Color := clWhite
      else
        Pen.Color := FLineColor; //clBtnShadow;

      MoveTo(FromPoint.X, FromPoint.Y);
      LineTo(ToPoint.X, ToPoint.Y);

      if Embossed then
        Pen.Color := FLineColor //clBtnShadow
      else
        Pen.Color := clWhite;

      MoveTo(FromPoint.X + 1, FromPoint.Y + 1);
      LineTo(ToPoint.X + 1, ToPoint.Y + 1);
    end;
  end;

begin
  inherited;
  R := ClientRect;

  case FSeparatorStyle of
    ssOffice2003:
      begin
        if Position in [daTop, daBottom] then
          DrawSepLine(Point(R.Left + ((R.Right - R.Left) div 2), R.Top + 3), Point(R.Left + ((R.Right - R.Left) div 2), R.Bottom - 3), false)
        else
        begin
          DrawSepLine(Point(R.Left + 3, R.Top + ((R.Bottom - R.Top) div 2)), Point(R.Right - 3, R.Top + ((R.Bottom - R.Top) div 2)), false)
        end;
      end;
    ssBlank:
      begin
      // do nothing
      end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarSeparator.SetLineColor(const Value: TColor);
begin
  if FLineColor <> Value then
  begin
    FLineColor := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarSeparator.SetSeparatorStyle(
  const Value: TAdvSeparatorStyle);
begin
  if FSeparatorStyle <> Value then
  begin
    FSeparatorStyle := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

{ TAdvToolBarMenuButton }

constructor TAdvToolBarMenuButton.Create(AOwner: TComponent);
begin
  inherited;
  ParentStyler := true;
end;

//------------------------------------------------------------------------------

destructor TAdvToolBarMenuButton.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarMenuButton.DrawButton(aCanvas: TCanvas);
var
  Clr, ClrTo, BrClr, TxtClr, DwClr, DwClrTo: TColor;
  R, BtnR, DwR: TRect;
  aGlyph: TBitmap;
  GDHoriztl: Boolean;
  AP: TPoint;
  ToolBarStyler: TCustomAdvToolBarStyler;
  TBMenu: Boolean;

  procedure DrawArrow(ArP: TPoint; ArClr: TColor);
  begin
    if Position in [daTop, daBottom] then
    begin
      Canvas.Pen.Color := ArClr;
      Canvas.MoveTo(ArP.X, ArP.Y);
      Canvas.LineTo(ArP.X + 5, ArP.Y);
      Canvas.MoveTo(ArP.X + 1, ArP.Y + 1);
      Canvas.LineTo(ArP.X + 4, ArP.Y + 1);
      Canvas.Pixels[ArP.X + 2, ArP.Y + 2] := ArClr;
    end
    else
    begin
      Canvas.Pen.Color := ArClr;
      Canvas.MoveTo(ArP.X, ArP.Y);
      Canvas.LineTo(ArP.X, ArP.Y + 5);
      Canvas.MoveTo(ArP.X - 1, ArP.Y + 1);
      Canvas.LineTo(ArP.X - 1, ArP.Y + 4);
      Canvas.Pixels[ArP.X - 2, ArP.Y + 2] := ArClr;
    end;
  end;
begin
  R := ClientRect;
  BtnR := R;

  if Position in [daTop, daBottom] then
    DwR := Rect(BtnR.Right - FDropDownSectWidth, BtnR.Top, BtnR.Right, BtnR.Bottom)
  else
    DwR := Rect(BtnR.Left, BtnR.Bottom - FDropDownSectWidth, BtnR.Right, BtnR.Bottom);

  if FDropDownButton {and (Style <> tasCheck)} then
  begin
    if Position in [daTop, daBottom] then
      BtnR.Right := DwR.Left
    else
      BtnR.Bottom := DwR.Top;
  end;

  aGlyph := nil;

  Clr := clNone;
  ClrTo := clNone;
  TxtClr := clNone;
  BrClr := clNone;
  GDHoriztl := true;
  DwClr := clNone;
  DwClrTo := clNone;

  ToolBarStyler := nil;
  TBMenu := false;

  if Assigned(AdvToolBar) then
  begin
    ToolBarStyler := AdvToolBar.FCurrentToolBarStyler;
    TBMenu := Assigned(AdvToolBar.Menu);
  end
  else if Assigned(AdvQuickAccessToolBar) then
  begin
    ToolBarStyler := AdvQuickAccessToolBar.CurrentToolBarStyler;
  end;

  with ACanvas, FAppearance do
  begin
    if (State = absDisabled) or not Enabled then
    begin
      if Transparent then
      begin
        Clr := clNone;
        ClrTo := clNone;
        BrClr := clNone;
      end
      else
      begin
        Clr := Color;
        ClrTo := ColorTo;
        BrClr := BorderColor;
      end;

      DwClr := Clr;
      DwClrTo := ClrTo;
      TxtClr := CaptionTextColor;
      GDHoriztl := GradientDirection = gdHorizontal;
      aGlyph := GlyphDisabled;
    end
    else if (State = absDropDown) and false then
    begin

    end
    else if (State = absDown) or ((FHot or FPropHot) and (State = absExclusive)) or (FMouseDownInControl) or (State = absDropDown) then
    begin
      if ParentStyler and Assigned(ToolBarStyler) then
      begin
        if TBMenu then
        begin
          with ToolBarStyler.CurrentAdvMenuStyler.RootItem do
          begin
            Clr := SelectedColor;
            ClrTo := SelectedColorTo;
            TxtClr := SelectedTextColor;
            BrClr := SelectedBorderColor;
            DwClr := HoverColor;
            DwClrTo := HoverColorTo;
            GDHoriztl := SelectedGradientDirection = AdvMenus.gdHorizontal;
            aGlyph := GlyphDown;
          end;
        end
        else
        begin
          with ToolBarStyler.ButtonAppearance do
          begin
            Clr := ColorDown;
            ClrTo := ColorDownTo;
            TxtClr := CaptionTextColorDown;
            BrClr := BorderDownColor;
            DwClr := ColorHot;
            DwClrTo := ColorHotTo;
            GDHoriztl := GradientDirectionDown = gdHorizontal;
            aGlyph := GlyphDown;
          end;
        end;
      end
      else
      begin
        Clr := ColorDown;
        ClrTo := ColorDownTo;
        TxtClr := CaptionTextColorDown;
        BrClr := BorderDownColor;
        DwClr := ColorHot;
        DwClrTo := ColorHotTo;
        GDHoriztl := GradientDirectionDown = gdHorizontal;
        aGlyph := GlyphDown;
      end;

    end
    else if State = absExclusive then
    begin
      Clr := ColorChecked;
      ClrTo := ColorCheckedTo;
      TxtClr := CaptionTextColorChecked;
      BrClr := BorderCheckedColor;
      DwClr := Clr;
      DwClrTo := ClrTo;
      GDHoriztl := GradientDirectionChecked = gdHorizontal;
      aGlyph := GlyphChecked;
    end
    else //if State = absUp then
    begin
      if (FHot or FPropHot) then
      begin
        if ParentStyler and Assigned(ToolBarStyler) then
        begin
          if TBMenu then
          begin
            with ToolBarStyler.CurrentAdvMenuStyler.RootItem do
            begin
              Clr := HoverColor;
              ClrTo := HoverColorTo;
              TxtClr := HoverTextColor;
              BrClr := HoverBorderColor;
              GDHoriztl := HoverGradientDirection = AdvMenus.gdHorizontal;
              aGlyph := GlyphHot;
            end;
          end
          else
          begin
            with ToolBarStyler.ButtonAppearance do
            begin
              Clr := ColorHot;
              ClrTo := ColorHotTo;
              TxtClr := CaptionTextColorHot;
              BrClr := BorderHotColor;
              GDHoriztl := GradientDirectionHot = gdHorizontal;
              aGlyph := GlyphHot;
            end;

          end;
        end
        else
        begin
          Clr := ColorHot;
          ClrTo := ColorHotTo;
          TxtClr := CaptionTextColorHot;
          BrClr := BorderHotColor;
          GDHoriztl := GradientDirectionHot = gdHorizontal;
          aGlyph := GlyphHot;
        end;

        DwClr := Clr;
        DwClrTo := ClrTo;
      end
      else // Normal draw
      begin
        if Transparent then
        begin
          Clr := clNone;
          ClrTo := clNone;
          BrClr := clNone;
          DwClr := clNone;
          DwClrTo := clNone; 
          if ParentStyler and Assigned(ToolBarStyler) and TBMenu then
          begin
            TxtClr := ToolBarStyler.CurrentAdvMenuStyler.RootItem.Font.Color;
          end
          else
            TxtClr := CaptionTextColor;
        end
        else
        begin
          if ParentStyler and Assigned(ToolBarStyler) and TBMenu then
          begin
            with ToolBarStyler.CurrentAdvMenuStyler.RootItem do
            begin
              Clr := Color;
              ClrTo := ColorTo;
              TxtClr := ToolBarStyler.CurrentAdvMenuStyler.RootItem.Font.Color;
              BrClr := BorderColor;
              GDHoriztl := GradientDirection = AdvMenus.gdHorizontal;
            end;
          end
          else
          begin
            Clr := Color;
            ClrTo := ColorTo;
            TxtClr := CaptionTextColor;
            BrClr := BorderColor;
            GDHoriztl := GradientDirection = gdHorizontal;
          end;
          
          DwClr := Clr;
          DwClrTo := ClrTo;
        end;
        aGlyph := Glyph;
      end;
    end;

    // BackGround
    if (Clr <> clNone) and (ClrTo <> clNone) then
    begin
      if FDropDownButton {and (Style <> tasCheck)} then
        DrawGradient(aCanvas, DwClr, DwClrTo, 40, R, GDHoriztl);

      DrawGradient(aCanvas, Clr, ClrTo, 40, BtnR, GDHoriztl);
    end
    else if (Clr <> clNone) then
    begin
      if FDropDownButton {and (Style <> tasCheck)} then
      begin
        Brush.Color := DwClr;
        Pen.Color := DwClr;
        Rectangle(R)
      end;
      Brush.Color := Clr;
      Pen.Color := Clr;
      Rectangle(BtnR);
    end;

    // Border
    if BrClr <> clNone then
    begin
      Brush.Style := bsClear;
      Pen.Color := BrClr;
      
      if FDropDownButton and FDropDownSplit {and (Style <> tasCheck)} then
        Rectangle(R);

      if FDropDownButton and not FDropDownSplit {and (Style <> tasCheck)} then
      begin
        Rectangle(Rect(BtnR.Left, BtnR.Top, R.Right, BtnR.Bottom));
      end
      else
        Rectangle(BtnR);
    end;

    if FMenuSel then
    begin
      if ParentStyler and Assigned(ToolBarStyler) then
      begin
        if Assigned(ToolBarStyler.CurrentAdvMenuStyler) then
          Pen.Color := ToolBarStyler.CurrentAdvMenuStyler.MenuBorderColor
      end;

      Pen.Color := clNavy;

      if FDropDownSplit then
      begin
        if Position in [daTop, daBottom] then
        begin
          MoveTo(BtnR.Left, DwR.Bottom);
          LineTo(BtnR.Left, DwR.Top);
          LineTo(DwR.Right - 1, DwR.Top);
          LineTo(DwR.Right - 1, DwR.Bottom);
        end
        else
        begin
          MoveTo(BtnR.Left, DwR.Bottom);
          LineTo(BtnR.Left, BtnR.Top);
          LineTo(DwR.Right - 1, BtnR.Top);
          LineTo(DwR.Right - 1, DwR.Bottom);
        end;
      end;
    end;

    if FDropDownButton {and (Style <> tasCheck)} then
    begin
      if Position in [daTop, daBottom] then
      begin
        AP.X := DwR.Left + ((DwR.Right - DwR.Left - 5) div 2);
        AP.Y := DwR.Top + ((DwR.Bottom - DwR.Top - 3) div 2) + 1;
      end
      else
      begin
        AP.X := DwR.Left + ((DwR.Right - DwR.Left - 3) div 2) + 1;
        AP.Y := DwR.Top + ((DwR.Bottom - DwR.Top - 5) div 2);
      end;
      DrawArrow(AP, clBlack);
    end;

    if Assigned(aGlyph) and (aGlyph.Empty) and not Glyph.Empty then
      aGlyph := Glyph;

    DrawGlyphAndCaption(aCanvas, BtnR, TxtClr, aGlyph);

  end;

end;

//------------------------------------------------------------------------------

function TAdvToolBarMenuButton.IsMenuButton: Boolean;
begin
  Result := true;
end;

//------------------------------------------------------------------------------

{ TOptionSelectorWindow }

constructor TOptionSelectorWindow.Create(AOwner: TComponent);
begin
  inherited;
  FHideOnDeActivate := true;
  FHideTimer := TTimer.Create(self);
  FHideTimer.Interval := 1;
  FHideTimer.Enabled := false;
  FHideTimer.OnTimer := HideTimerOnTime;
end;

//------------------------------------------------------------------------------

constructor TOptionSelectorWindow.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
  inherited;
  FOwner := AOwner;
  FHideOnDeActivate := true;
  FHideTimer := TTimer.Create(self);
  FHideTimer.Interval := 1;
  FHideTimer.Enabled := false;
  FHideTimer.OnTimer := HideTimerOnTime;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorWindow.CreateParams(var Params: TCreateParams);
const
  CS_DROPSHADOW = $00020000;
begin
  inherited CreateParams(Params);
  // FF: D2005
  Params.Style := Params.Style or WS_POPUP;
  Params.Style := Params.Style - WS_CHILD;
  //Params.ExStyle := Params.ExStyle or WS_EX_NOPARENTNOTIFY;

  //Params.Style := Params.Style - WS_BORDER;
  {
  if (Win32Platform = VER_PLATFORM_WIN32_NT) and
     ((Win32MajorVersion > 5) or
      ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1))) then
    Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;

  Params.ExStyle := Params.ExStyle or WS_EX_TOPMOST; }
end;

//------------------------------------------------------------------------------

destructor TOptionSelectorWindow.Destroy;
begin
  FHideTimer.Free;
  inherited;
end;

//------------------------------------------------------------------------------

function TOptionSelectorWindow.GetParentWnd: HWnd;
var
  Last, P: HWnd;
begin
  P := GetParent((Owner as TWinControl).Handle);
  Last := P;
  while P <> 0 do
  begin
    Last := P;
    P := GetParent(P);
  end;
  Result := Last;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorWindow.DoHide;
begin
  inherited;
  if Assigned(FOptionsPanel) then
    FOptionsPanel.DoHide;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorWindow.HideTimerOnTime(Sender: TObject);
begin
  Hide;
  FHideTimer.Enabled := false;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorWindow.Paint;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorWindow.SetWindowSize;
begin
  if Assigned(FOptionsPanel) then
  begin
    Height := FOptionsPanel.GetVisibleHeight;
    Width := FOptionsPanel.Width;
  end;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorWindow.WMActivate(var Message: TWMActivate);
begin
  if Message.Active = integer(False) then
  begin
    if HideOnDeActivate and Visible then
    begin
      FHideTimer.Enabled := true;
    end;
  end
  else if Assigned(FOptionsPanel) then
  begin
    if Self.Visible then
    begin
      FOptionsPanel.SetFocus;
      SendMessage(getParentWnd, WM_NCACTIVATE, 1, 0);
    end
    else
    begin
      if Assigned(AdvToolbar) then
        AdvToolbar.SetFocus;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorWindow.WMNCHitTest(var Message: TWMNCHitTest);
var
  pt: TPoint;
begin
  // Make the hint sizable
  pt := ScreenToClient(Point(Message.XPos, Message.YPos));

  if (pt.X > Width - 10) and (pt.Y > Height - 10) then
    message.Result := HTBOTTOMRIGHT
end;

//------------------------------------------------------------------------------

{ TOptionSelectorPanel }

constructor TOptionSelectorPanel.Create(AOwner: TComponent);
begin
  inherited;
  FOwner := AOwner;
  BevelOuter := bvNone;
  BevelWidth := 1;
  Color := $00F7F8F9;
  FColorTo := clNone;
  FWindowBorderColor := clGray;
  FGradientDirection := gdHorizontal;
  FMarginX := 3;
  FMarginY := 3;
  FAdvQuickAccessToolBar := nil;
end;

//------------------------------------------------------------------------------

function TOptionSelectorPanel.GetVisibleHeight: integer;
begin
  Result := Height;
end;
//------------------------------------------------------------------------------

procedure TOptionSelectorPanel.DoHide;
begin

end;

//------------------------------------------------------------------------------

procedure TOptionSelectorPanel.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TOptionSelectorPanel.Paint;
var
  R: TRect;
begin
  inherited;
  R := Rect(0, 0, Width, Height);

  if ColorTo <> clNone then
    DrawGradient(Canvas, Color, ColorTo, 40, R, FGradientDirection = gdHorizontal);

  Canvas.Brush.Style := bsClear;
  Canvas.Pen.Color := FWindowBorderColor;

  Canvas.MoveTo(0, 0);
  Canvas.LineTo(0, Height);

  //if TSelectorDropDownWindow(FOwner).ShowFullBorder then
  //begin
  Canvas.MoveTo(0, 0);
  Canvas.LineTo(Width - 1, 0);
  Canvas.MoveTo(0, Height - 1);
  Canvas.LineTo(Width - 1, Height - 1);
{  end
  else
  begin

  end;
  }
  Canvas.MoveTo(Width - 1, Height);
  Canvas.LineTo(Width - 1, {0} -1);
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorPanel.SetColorTo(const Value: TColor);
begin
  FColorTo := Value;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorPanel.SetGradientDirection(
  const Value: TGradientDirection);
begin
  FGradientDirection := Value;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorPanel.SetMarginX(const Value: Integer);
begin
  FMarginX := Value;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorPanel.SetMarginY(const Value: Integer);
begin
  FMarginY := Value;
end;

//------------------------------------------------------------------------------

procedure TOptionSelectorPanel.SetWindowBorderColor(const Value: TColor);
begin
  FWindowBorderColor := Value;
end;

//------------------------------------------------------------------------------

{$IFDEF DELPHI6_LVL}

{ TAdvToolBarButtonActionLink }

procedure TAdvToolBarButtonActionLink.AssignClient(AClient: TObject);
begin
  inherited AssignClient(AClient);
  FClient := AClient as TAdvCustomToolBarButton;
end;

//------------------------------------------------------------------------------

function TAdvToolBarButtonActionLink.IsCheckedLinked: Boolean;
begin
  Result := inherited IsCheckedLinked {and (FClient.GroupIndex <> 0) and
    FClient.AllowAllUp} and (FClient.Down = (Action as TCustomAction).Checked);
end;

//------------------------------------------------------------------------------

function TAdvToolBarButtonActionLink.IsGroupIndexLinked: Boolean;
begin
  Result := (FClient is TAdvCustomToolBarButton) and
    (TAdvCustomToolBarButton(FClient).GroupIndex = (Action as TCustomAction).GroupIndex);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarButtonActionLink.SetChecked(Value: Boolean);
begin
  if IsCheckedLinked then TAdvCustomToolBarButton(FClient).Down := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarButtonActionLink.SetGroupIndex(Value: Integer);
begin
  if IsGroupIndexLinked then TAdvCustomToolBarButton(FClient).GroupIndex := Value;
end;

{$ENDIF}

//------------------------------------------------------------------------------

{ TGradientBackground }

procedure TGradientBackground.Assign(Source: TPersistent);
begin
  if (Source is TGradientBackground) then
  begin
    FColor := (Source as TGradientBackground).Color;
    FColorTo := (Source as TGradientBackground).ColorTo;
    FDirection := (Source as TGradientBackground).Direction;
    FSteps := (Source as TGradientBackground).Steps;
  end;
end;

//------------------------------------------------------------------------------

procedure TGradientBackground.Changed;
begin
  if Assigned(OnChange) then
    OnChange(Self);
end;

//------------------------------------------------------------------------------

constructor TGradientBackground.Create;
begin
  inherited;
  Color := clWhite;
  ColorTo := clBtnFace;
  Steps := 64;
  Direction := gdHorizontal;
end;

//------------------------------------------------------------------------------

procedure TGradientBackground.SetColor(const Value: TColor);
begin
  FColor := Value;
  Changed;
end;

//------------------------------------------------------------------------------

procedure TGradientBackground.SetColorTo(const Value: TColor);
begin
  FColorTo := Value;
  Changed;
end;

//------------------------------------------------------------------------------

procedure TGradientBackground.SetDirection(
  const Value: TGradientDirection);
begin
  FDirection := Value;
  Changed;
end;

//------------------------------------------------------------------------------

procedure TGradientBackground.SetSteps(const Value: Integer);
begin
  FSteps := Value;
  Changed;
end;

//------------------------------------------------------------------------------

{ TVistaGradientBackground }

procedure TVistaGradientBackground.Assign(Source: TPersistent);
begin
  inherited;
  if (Source is TVistaGradientBackground) then
  begin
    FMirror.Assign(TVistaGradientBackground(Source).Mirror);
  end;
end;

//------------------------------------------------------------------------------

constructor TVistaGradientBackground.Create;
begin
  inherited;
  FMirror := TMirrorGradient.Create;
end;

//------------------------------------------------------------------------------

destructor TVistaGradientBackground.Destroy;
begin
  FMirror.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TVistaGradientBackground.SetMirror(const Value: TMirrorGradient);
begin
  FMirror.Assign(Value);
end;

//------------------------------------------------------------------------------

{ TMirrorGradient }

procedure TMirrorGradient.Assign(Source: TPersistent);
begin
  if (Source is TMirrorGradient) then
  begin
    FColor := TMirrorGradient(Source).Color;
    FColorTo := TMirrorGradient(Source).ColorTo;
    FColorMirror := TMirrorGradient(Source).ColorMirror;
    FColorMirrorTo := TMirrorGradient(Source).ColorMirrorTo;
  end
  else
    inherited;
end;

//------------------------------------------------------------------------------

constructor TMirrorGradient.Create;
begin
  inherited;
  FColor := clWhite;
  FColorTo := clBtnFace;
  FColorMirror := RGB(200, 217, 237);
  FColorMirrorTo := RGB(227, 244, 255);
end;

//------------------------------------------------------------------------------

procedure TMirrorGradient.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

procedure TMirrorGradient.SetColor(const Value: TColor);
begin
  if (FColor <> Value) then
  begin
    FColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TMirrorGradient.SetColorMirror(const Value: TColor);
begin
  if (FColorMirror <> Value) then
  begin
    FColorMirror := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TMirrorGradient.SetColorMirrorTo(const Value: TColor);
begin
  if (FColorMirrorTo <> Value) then
  begin
    FColorMirrorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TMirrorGradient.SetColorTo(const Value: TColor);
begin
  if (FColorTo <> Value) then
  begin
    FColorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

{ TPersistence }

procedure TPersistence.Assign(Source: TPersistent);
begin
  if Source is TPersistence then
  begin
    FLocation:= TPersistence(Source).Location;
    FKey:= TPersistence(Source).Key;
    FSection:= TPersistence(Source).Section;
    FEnabled:= TPersistence(Source).Enabled;
    inherited Assign(Source);
  end;
end;

//------------------------------------------------------------------------------

constructor TPersistence.Create(AOwner: TComponent);
begin
  inherited Create;
  FOwner:= AOwner;
end;

//------------------------------------------------------------------------------

destructor TPersistence.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TPersistence.Change;
begin
  if Assigned(FOnChange) then
    FOnChange(self);
end;

//------------------------------------------------------------------------------

procedure TPersistence.SetEnabled(const Value: Boolean);
begin
  if FEnabled <> Value then
  begin
    FEnabled := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TPersistence.SetKey(const Value: string);
begin
  if FKey <> Value then
  begin
    FKey := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TPersistence.SetLocation(const Value: TPersistenceLocation);
begin
  if FLocation <> Value then
  begin
    FLocation := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TPersistence.SetSection(const Value: string);
begin
  if FSection <> Value then
  begin
    FSection := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

{ TControlSelectorPanel }

constructor TControlSelectorPanel.Create(AOwner: TComponent);
begin
  inherited;
  FControlList := TDbgList.Create;
  FAddAndRemoveBtn := TSelectorItem.Create;
  FAddAndRemoveBtn.Caption := 'Add or Remove Buttons';
  FAddAndRemoveBtn.Width := 130;
  FItemColorHot := $00D2BDB6;
  FItemColorHotTo := clNone;
  FItemColorDown := clGray;
  FItemColorDownTo := clNone;
  FItemTextColorHot := clWhite;
  FItemTextColor := clBlack;
  FItemTextColorDown := clBlack;

  FSeparatorSize := 8;
  FShowAddAndRemoveBtn := True;

  FOptionsMenu := nil;
  FOptionsBtn := TSelectorItem.Create;
  FOptionsBtn.Caption := 'Options';
  FOptionsBtn.Width := 130;

  FTimer := TTimer.Create(self);
  FTimer.Interval := 1;
  FTimer.Enabled := false;
  FTimer.OnTimer := TimerOnTime;

  FSeparatorList := TDbgList.Create;
end;

//------------------------------------------------------------------------------

destructor TControlSelectorPanel.Destroy;
begin
  FControlList.Free;
  FAddAndRemoveBtn.Free;
  FOptionsBtn.Free;
  FTimer.Free;
  FSeparatorList.Free;
  if Assigned(FCustomizeOptionWindow) then
    FCustomizeOptionWindow.Free;
  inherited;
end;

//------------------------------------------------------------------------------

function TControlSelectorPanel.AddControl(AControl: TControl): Integer;
begin
  Result := -1;
  if Assigned(AControl) then
  begin
    AControl.Parent := self;
    Result := FControlList.IndexOf(AControl);
    if Result < 0 then
    begin
      Result := FControlList.Add(AControl);
      //ArrangeControls;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.DoHide;
var
  i: Integer;
begin
  for i:= 0 to FSeparatorList.Count -1 do
  begin
    if TObject(FSeparatorList[i]) is TAdvToolBarSeparator then
      TAdvToolBarSeparator(FSeparatorList[i]).Free;
  end;
  FSeparatorList.Clear;
end;

//------------------------------------------------------------------------------

function TControlSelectorPanel.AddCopySeparator(ASeparator: TAdvToolBarSeparator): TAdvToolBarSeparator;
begin
  Result := TAdvToolBarSeparator.Create(self);
  Result.Assign(ASeparator);
  FSeparatorList.Add(Result);
  AddControl(Result);
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.ArrangeControls;
var
  i, j, W, H, L, T: Integer;
begin
  // Hiding Separator at Start or End
  for i := 0 to ControlCount - 1 do
  begin
    j := ControlList.IndexOf(Controls[i]);
    if (j < 0) then
    begin
      Controls[i].Top := - Controls[i].Height - 2;
    end;
  end;

  W := FAddAndRemoveBtn.Width;
  for i := 0 to ControlList.Count -1 do
  begin
    if (TObject(ControlList[i]) is TControl) then
    begin
      W := Max(W, TControl(ControlList[i]).Width);
    end;
  end;

  L := MarginX;
  T := MarginY;
  j := 0;
  for i := 0 to ControlList.Count -1 do
  begin
    if (TObject(ControlList[i]) is TControl) then
    begin
      if TControl(ControlList[i]).Width > (W - L) then
      begin
        L := MarginX;
        T := T + j;
        j := 0;
      end;
      TControl(ControlList[i]).Left := L;
      TControl(ControlList[i]).Top := T;
      L := L + TControl(ControlList[i]).Width;
      j := Max(j, TControl(ControlList[i]).Height);
     { if L >= W then
      begin
        L := MarginX;
        T := j;
        j := 0;
      end; }
    end;
  end;
  //w := Max(w, );
  if FShowAddAndRemoveBtn then
    H := T + j + FAddAndRemoveBtn.Height
  else
    H := T + j;

  if ShowOptionsBtn then
    H := H + FOptionsBtn.Height;  

  if (ControlList.Count > 0) and (FShowAddAndRemoveBtn or ShowOptionsBtn)then
    H := H + FSeparatorSize;
    
  self.Width := w + MarginX*2;
  self.Height := H + MarginY;

  FAddAndRemoveBtn.BRect := Rect(0, 0, 0, 0);
  if FShowAddAndRemoveBtn then
    FAddAndRemoveBtn.BRect := Rect(MarginX, Height-MarginY - FAddAndRemoveBtn.Height, Width - MarginX, Height-MarginY);


  FOptionsBtn.BRect := Rect(0, 0, 0, 0);  
  if ShowOptionsBtn then
  begin
    if FShowAddAndRemoveBtn then
      FOptionsBtn.BRect := Rect(MarginX, FAddAndRemoveBtn.BRect.Top - FOptionsBtn.Height, Width - MarginX, FAddAndRemoveBtn.BRect.Top)
    else
      FOptionsBtn.BRect := Rect(MarginX, Height-MarginY - FOptionsBtn.Height, Width - MarginX, Height-MarginY);
  end;
  
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.CMControlChange(
  var Message: TCMControlChange);
begin
  inherited;
 {
  with Message do
    if Inserting then
      InsertControl(Control)
    else
      RemoveControl(Control);
   }
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.MouseMove(Shift: TShiftState; X,
  Y: Integer);
var
  i: Integer;  
begin
  inherited;
  if PtInRect(FAddAndRemoveBtn.BRect, Point(X, Y)) then
  begin
    if not FAddAndRemoveBtnHot and not (ssLeft in Shift) then
    begin
      FAddAndRemoveBtnHot := True;
      FAddAndRemoveBtnDown := True;
      Invalidate;

      if Assigned(FCustomizeOptionWindow) then
      begin
        FInternalHiding := True;
        FCustomizeOptionWindow.Hide;
        FInternalHiding := False;
      end;

      ShowAddAndRemovePopup;
    end;
  end
  else if FAddAndRemoveBtnHot then
  begin
    FAddAndRemoveBtnHot := False;
    FAddAndRemoveBtnDown := False;
    Invalidate;
    //HideAddAndRemovePopup
  end;

  if PtInRect(FOptionsBtn.BRect, Point(X, Y)) then
  begin
    if not FOptionsBtnHot and not (ssLeft in Shift) then
    begin
      FOptionsBtnHot := True;
      FOptionsBtnDown := True;
      Invalidate;

      ShowOptionsBtnPopup;
    end;
  end
  else if FOptionsBtnHot then
  begin
    FOptionsBtnHot := False;
    FOptionsBtnDown := False;
    Invalidate;

    i := FOptionsBtn.BRect.Top - 4;
    if Assigned(FCustomizeOptionWindow) and (y < i) then
    begin
      FInternalHiding := True;
      FCustomizeOptionWindow.Hide;
      FInternalHiding := False;
    end;
    //HideOptionsBtnPopup
  end;

end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.RemoveControl(AControl: TControl);
begin
  if FControlList.IndexOf(AControl) >= 0 then
  begin
    FControlList.Remove(AControl);
    ArrangeControls;
  end;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.Paint;
var
  TextR: TRect;
  ArClr, Clr, ClrTo: TColor;
begin
  inherited;

  with Canvas do
  begin
    if FShowAddAndRemoveBtn or ShowOptionsBtn then
    begin
      if ShowOptionsBtn then
      begin
        pen.Color := clGray;
        MoveTo(0, FOptionsBtn.BRect.top - 4);
        LineTo(Width, FOptionsBtn.BRect.top - 4);
      end
      else
      begin
        pen.Color := clGray;
        MoveTo(0, FAddAndRemoveBtn.BRect.top - 4);
        LineTo(Width, FAddAndRemoveBtn.BRect.top - 4);
      end;
    end;

    if FShowAddAndRemoveBtn then
    begin
      {pen.Color := clGray;
      MoveTo(0, FAddAndRemoveBtn.BRect.top - 4);
      LineTo(Width, FAddAndRemoveBtn.BRect.top - 4);
      }
      Clr := clNone;
      ClrTo := clNone;
      if FAddAndRemoveBtnDown then
      begin
        Clr := ItemColorDown;
        ClrTo := ItemColorDownTo;
        Pen.Color := clBlack;
        Font.Color := ItemTextColorDown;
      end
      else if FAddAndRemoveBtnHot then
      begin
        Clr := ItemColorHot;
        ClrTo := ItemColorHotTo;
        Pen.Color := clBlack;
        Font.Color := ItemTextColorHot;
      end
      else
      begin
        Font.Color := ItemTextColor;
      end;

      if (Clr <> clNone) and (ClrTo <> clNone) then
      begin
        DrawGradient(Canvas, Clr, ClrTo, 40, FAddAndRemoveBtn.BRect, False);
        Brush.Style := bsClear;
        Pen.Color := clBlack;
        Rectangle(FAddAndRemoveBtn.BRect);
      end
      else if (Clr <> clNone) then
      begin
        Brush.Color := Clr;
        Rectangle(FAddAndRemoveBtn.BRect);
      end;

      TextR := FAddAndRemoveBtn.BRect;
      TextR.Right := TextR.Right - 8;
      Canvas.Font.Name := 'Tahoma';
      Canvas.Font.Size := 8;
      Canvas.Brush.Style := bsClear;
      DrawText(Canvas.Handle, PChar(FAddAndRemoveBtn.Caption), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_CENTER);

      ArClr := Font.Color;
      Pen.Color := ArClr;
      moveto(FAddAndRemoveBtn.BRect.Right - 9, FAddAndRemoveBtn.BRect.Bottom - 10);
      LineTo(FAddAndRemoveBtn.BRect.Right - 4, FAddAndRemoveBtn.BRect.Bottom - 10);
      moveto(FAddAndRemoveBtn.BRect.Right - 8, FAddAndRemoveBtn.BRect.Bottom - 9);
      LineTo(FAddAndRemoveBtn.BRect.Right - 5, FAddAndRemoveBtn.BRect.Bottom - 9);
      Pixels[FAddAndRemoveBtn.BRect.Right - 7, FAddAndRemoveBtn.BRect.Bottom - 8] := ArClr;

    end;

    if ShowOptionsBtn then
    begin
      Clr := clNone;
      ClrTo := clNone;
      if FOptionsBtnDown then
      begin
        Clr := ItemColorDown;
        ClrTo := ItemColorDownTo;
        Pen.Color := clBlack;
        Font.Color := ItemTextColorDown;
      end
      else if FOptionsBtnHot then
      begin
        Clr := ItemColorHot;
        ClrTo := ItemColorHotTo;
        Pen.Color := clBlack;
        Font.Color := ItemTextColorHot;
      end
      else
      begin
        Font.Color := ItemTextColor;
      end;

      if (Clr <> clNone) and (ClrTo <> clNone) then
      begin
        DrawGradient(Canvas, Clr, ClrTo, 40, FOptionsBtn.BRect, False);
        Brush.Style := bsClear;
        Pen.Color := clBlack;
        Rectangle(FOptionsBtn.BRect);
      end
      else if (Clr <> clNone) then
      begin
        Brush.Color := Clr;
        Rectangle(FOptionsBtn.BRect);
      end;

      TextR := FOptionsBtn.BRect;
      TextR.Right := TextR.Right - 8;
      Canvas.Brush.Style := bsClear;
      DrawText(Canvas.Handle, PChar(FOptionsBtn.Caption), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_CENTER);

      ArClr := Font.Color;
      Pen.Color := ArClr;
      moveto(FOptionsBtn.BRect.Right - 8, FOptionsBtn.BRect.Top + 7);
      LineTo(FOptionsBtn.BRect.Right - 8, FOptionsBtn.BRect.Top + 12);
      moveto(FOptionsBtn.BRect.Right - 7, FOptionsBtn.BRect.Top + 8);
      LineTo(FOptionsBtn.BRect.Right - 7, FOptionsBtn.BRect.Top + 11);
      Pixels[FOptionsBtn.BRect.Right - 6, FOptionsBtn.BRect.Top + 9] := ArClr;
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetItemColorDown(const Value: TColor);
begin
  FItemColorDown := Value;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetItemColorHot(const Value: TColor);
begin
  FItemColorHot := Value;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.CMMouseLeave(var Message: TMessage);
begin
  if FAddAndRemoveBtnHot or FAddAndRemoveBtnDown then
  begin
    FAddAndRemoveBtnHot := False;
    FAddAndRemoveBtnDown := False;
    if Assigned(FAddAndRemovePopup) and FAddAndRemovePopup.Visible then
      FAddAndRemoveBtnDown := True;
    Invalidate;
  end;

  if FOptionsBtnHot or FOptionsBtnDown then
  begin
    FOptionsBtnHot := False;
    FOptionsBtnDown := False;
    //if Assigned(FOptionsMenu) and FOptionsBtnPopup.Visible then
      //FOptionsBtnDown := True;
    Invalidate;
  end;

end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.MouseUp(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetItemColorDownTo(const Value: TColor);
begin
  FItemColorDownTo := Value;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetItemColorHotTo(const Value: TColor);
begin
  FItemColorHotTo := Value;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetItemTextColor(const Value: TColor);
begin
  FItemTextColor := Value;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetItemTextColorHot(const Value: TColor);
begin
  FItemTextColorHot := Value;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetItemTextColorDown(const Value: TColor);
begin
  FItemTextColorDown := Value;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.ShowAddAndRemovePopup;
var
  I: Integer;
  P : TPoint;
  R: TRect;
begin
  if Assigned(FAddAndRemovePopup) and FAddAndRemovePopup.Visible then
    Exit;

  if not FShowAddAndRemoveBtn then
    Exit;

  if not Assigned(FAddAndRemovePopup) then
  begin
    FAddAndRemovePopup:= TATBPopupWindow.CreateNew(self{TOptionSelectorWindow(Parent).AdvToolBar});
    FAddAndRemovePopup.CreateItems;
    FAddAndRemovePopup.BorderIcons := [];
    FAddAndRemovePopup.BorderStyle := bsNone;
    FAddAndRemovePopup.Ctl3D := false;
    FAddAndRemovePopup.FormStyle := fsStayOnTop;
    FAddAndRemovePopup.Visible := False;
    FAddAndRemovePopup.Width := 10;
    FAddAndRemovePopup.Height := 10;
    FAddAndRemovePopup.AutoScroll := False;
    FAddAndRemovePopup.BorderWidth := 0;
    FAddAndRemovePopup.AdvToolBar := TOptionSelectorWindow(Parent).AdvToolBar;
    FAddAndRemovePopup.OnHide := OnAddAndRemoveWindowHide;
    FAddAndRemovePopup.OnDeActivateHide := OnAARWindowDeActivateHide;
  end;

  FAddAndRemovePopup.PopupPanel.Items.Clear;
  FAddAndRemovePopup.PopupPanel.ShowIconBar := True;

  if Assigned(TOptionSelectorWindow(Parent).AdvToolBar) then
  begin
    FAddAndRemovePopup.PopupPanel.AdvMenuStyler := TOptionSelectorWindow(Parent).AdvToolBar.FCurrentToolBarStyler.CurrentAdvMenuStyler;

    with FAddAndRemovePopup.PopupPanel.Items.Add do
    begin
      Caption := TOptionSelectorWindow(Parent).AdvToolBar.Caption;
      for I:= 0 to TOptionSelectorWindow(Parent).AdvToolBar.FATBControls.Count -1 do
      begin
        if not (TObject(TOptionSelectorWindow(Parent).AdvToolBar.FATBControls[i]) is TAdvToolBarSeparator) then
        with Add do
        begin
          AutoCheck := True;
          Checked := TControl(TOptionSelectorWindow(Parent).AdvToolBar.FATBControls[I]).Visible;
          Objects := TControl(TOptionSelectorWindow(Parent).AdvToolBar.FATBControls[I]);
          if TControl(TOptionSelectorWindow(Parent).AdvToolBar.FATBControls[I]) is TAdvCustomToolBarButton then
            Caption := TAdvCustomToolBarButton(TOptionSelectorWindow(Parent).AdvToolBar.FATBControls[I]).Caption
          else if TControl(TOptionSelectorWindow(Parent).AdvToolBar.FATBControls[I]) is TAdvCustomGlowButton then
            Caption := TAdvCustomGlowButton(TOptionSelectorWindow(Parent).AdvToolBar.FATBControls[I]).Caption
          else
            Caption := TControl(TOptionSelectorWindow(Parent).AdvToolBar.FATBControls[I]).Name;
        end;
      end;
    end;
  end;
  FAddAndRemovePopup.PopupPanel.ArrangeItems;
  FAddAndRemovePopup.SetWindowSize;

  TOptionSelectorWindow(Parent).HideOnDeActivate := False;
  // Positioning Window

  //P := ClientToScreen(Point(Left, Top));

{$IFNDEF TMSDOTNET}
  SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
{$ENDIF}
{$IFDEF TMSDOTNET}
  SystemParametersInfo(SPI_GETWORKAREA, 0, R, 0);
{$ENDIF}

  P := ClientToScreen(Point(FAddAndRemoveBtn.BRect.Right, FAddAndRemoveBtn.BRect.Top));

  if R.Bottom < (P.Y + FAddAndRemovePopup.Height + 2) then
    P.Y := P.Y - ((P.Y + FAddAndRemovePopup.Height + 2) - R.Bottom);

  if (R.Right < P.X + FAddAndRemovePopup.Width) then
    P.X := ClientToScreen(Point(FAddAndRemoveBtn.BRect.Left, FAddAndRemoveBtn.BRect.Top)).X - FAddAndRemovePopup.Width;

  FAddAndRemovePopup.Left := P.X;
  FAddAndRemovePopup.Top := P.Y;
  FAddAndRemovePopup.Visible := True;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.HideAddAndRemovePopup;
begin
  if Assigned(FAddAndRemovePopup) and FAddAndRemovePopup.Visible then
  begin
    FAddAndRemovePopup.PopupPanel.BeforeHide;
    FAddAndRemovePopup.Hide;
  end;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.OnAddAndRemoveWindowHide(Sender: TObject);
begin
  if Assigned(Parent) and (Parent is TOptionSelectorWindow) then
    TOptionSelectorWindow(Parent).HideOnDeActivate := True;

  FAddAndRemoveBtnDown := False;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.OnAARWindowDeActivateHide(Sender: TObject);
begin
  TOptionSelectorWindow(Parent).Hide;
  FAddAndRemoveBtnDown := False;
  FAddAndRemoveBtnHot := False;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetShowAddAndRemoveBtn(
  const Value: Boolean);
begin
  if FShowAddAndRemoveBtn <> Value then
  begin
    FShowAddAndRemoveBtn := Value;
  end;
end;

//------------------------------------------------------------------------------

function TControlSelectorPanel.IsEmpty: Boolean;
begin
  Result := (FControlList.Count <= 0) and not FShowAddAndRemoveBtn and not ShowOptionsBtn;
end;

//------------------------------------------------------------------------------

function TControlSelectorPanel.GetShowOptionsBtn: Boolean;
begin
  Result := Assigned(FOptionsMenu) or Assigned(FCustomizer);
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetOptionsMenu(const Value: TPopupMenu);
begin
  FOptionsMenu := Value;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.OnCustomizeOptionWindowHide(Sender: TObject);
begin
  if not FInternalHiding then
    TOptionSelectorWindow(Parent).Hide;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.ShowOptionsBtnPopup;
var
  APoint, cp: TPoint;
  MenuWidth, J, K: Integer;
  MeasureItemStruct: TMeasureItemStruct;
  R: TRect;
begin
  if not Assigned(AdvToolBar) then
    Exit;
    
  if Assigned(FOptionsMenu) or Assigned(FCustomizer) then
  begin
    if ShowAddAndRemoveBtn then
    begin
      HideAddAndRemovePopup;
      FTimer.Enabled := True;
    end;

    MenuWidth := 0;
    if Assigned(FOptionsMenu) then
    begin
      // correct popup point coordinates
      j := 0;
      for k := 0 to FOptionsMenu.Items.Count - 1 do
      begin
        if MenuWidth < Canvas.TextWidth(FOptionsMenu.Items[k].Caption) then
        begin
          MenuWidth := Canvas.TextWidth(FOptionsMenu.Items[k].Caption);
          j := k;
        end;
      end;

      if FOptionsMenu.Items.Count > 0 then
      begin
        with MeasureItemStruct do
        begin
          CtlType := ODT_MENU;
          itemID := FOptionsMenu.Items[j].Command;
          itemWidth := 10;
          itemHeight := 10;
        end;
        SendMessage(PopupList.Window, WM_MEASUREITEM, 0, lParam(@MeasureItemStruct));
        MenuWidth := MeasureItemStruct.itemWidth; //+ TriangleSize;
      end;
    end
    else if Assigned(FCustomizer) then
    begin
      if not Assigned(FCustomizeOptionWindow) then
      begin
        FCustomizeOptionWindow := TOptionSelectorWindow.CreateNew(self);
        FCustomizeOptionWindow.Parent := AdvToolBar;  // FF: D2005
        FCustomizeOptionWindow.BorderIcons := [];
        FCustomizeOptionWindow.BorderStyle := bsNone;
        FCustomizeOptionWindow.Ctl3D := false;
        FCustomizeOptionWindow.FormStyle := fsStayOnTop;
        FCustomizeOptionWindow.Visible := False;
        FCustomizeOptionWindow.Width := 100;
        FCustomizeOptionWindow.Height := 40;
        FCustomizeOptionWindow.AutoScroll := False;
        FCustomizeOptionWindow.BorderWidth := 0;
        FCustomizeOptionWindow.OnHide := OnCustomizeOptionWindowHide;
        //FCustomizeOptionWindow.AdvToolBar := AdvToolBar;
      end;

      if not Assigned(FCustomizeOptionPanel) then
      begin
        FCustomizeOptionPanel := TCustomizeOption.Create(FCustomizeOptionWindow);
        FCustomizeOptionPanel.Parent := FCustomizeOptionWindow;
      end;
      FCustomizeOptionPanel.AdvToolBar := AdvToolBar;
      if Assigned(Customizer) then
        FCustomizeOptionPanel.FCustomizeText := Customizer.FDialogSettings.Customize + ' '+AdvToolBar.Caption
      else
        FCustomizeOptionPanel.FCustomizeText := {'Customize '+ }AdvToolBar.Caption;
      FCustomizeOptionPanel.UpDateSize;
      FCustomizeOptionWindow.OptionsPanel := FCustomizeOptionPanel;
      FCustomizeOptionWindow.SetWindowSize;

      MenuWidth := FCustomizeOptionWindow.Width;      
    end;

    APoint := Point(FOptionsBtn.BRect.Right, FOptionsBtn.BRect.Top);
    {$IFNDEF TMSDOTNET}
      SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
    {$ENDIF}
    {$IFDEF TMSDOTNET}
      SystemParametersInfo(SPI_GETWORKAREA, 0, R, 0);
    {$ENDIF}

    APoint := ClientToScreen(APoint);
    if (APoint.X + MenuWidth > R.Right) then
      APoint := ClientToScreen(Point(FOptionsBtn.BRect.Left - MenuWidth, FOptionsBtn.BRect.top));
      
   (* if (GetSystemMetrics(SM_CYMENU) * FOptionsMenu.Items.Count) + APoint.Y + 10 >
    {$IFDEF DELPHI6_LVL}
      Screen.MonitorFromPoint(APoint).Height then
    {$ELSE}
      Screen.Height then
    {$ENDIF}
      //Dec(APoint.Y, Button.Height);
      Dec(APoint.Y, (GetSystemMetrics(SM_CYMENU) * FOptionsMenu.Items.Count) + FOptionsBtn.Height + 4);
    *)

    TOptionSelectorWindow(Parent).HideOnDeActivate := False;
    if Assigned(FOptionsMenu) then
    begin
      FOptionsMenu.Popup(APoint.X, APoint.Y);
      FOptionsBtnHot := False;
      FOptionsBtnDown := False;
      FTimer.Enabled := False;
      if ShowAddAndRemoveBtn then
      begin
        GetCursorPos(CP);
        CP := ScreenToClient(CP);
        if not PtInRect(FAddAndRemoveBtn.BRect, CP) then
          TOptionSelectorWindow(Parent).Hide;
      end
      else
      begin
        GetCursorPos(CP);
        CP := ScreenToClient(CP);
        //if not PtInRect(ClientRect, CP) then
          TOptionSelectorWindow(Parent).Hide;
      end;
    end
    else if Assigned(FCustomizer) then
    begin
      FCustomizeOptionWindow.Left := APoint.X;
      FCustomizeOptionWindow.Top := APoint.Y;
      FCustomizeOptionWindow.Show;
    end;

    TOptionSelectorWindow(Parent).HideOnDeActivate := True;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.HideOptionsBtnPopup;
begin

end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.TimerOnTime(Sender: TObject);
var
 cp: TPoint;
begin
  GetCursorPos(CP);
  CP := ScreenToClient(CP);
  if PtInRect(FAddAndRemoveBtn.BRect, CP) then
  begin
    FTimer.Enabled := False;
    PostMessage(Handle, WM_LBUTTONDOWN, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(Cp))));
    PostMessage(Handle, WM_LBUTTONUP, MK_LBUTTON, Longint(PointToSmallPoint(ScreenToClient(Cp))));
    //mouse_event( MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 );
    //mouse_event( MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 );
  end;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetTextAutoOptionMenu(const Value: String);
begin
  //if FAddAndRemoveBtn.Caption <> Value then
  begin
    FAddAndRemoveBtn.Caption := Value;
    ReSetButtonSize;
  end;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.SetTextOptionMenu(const Value: String);
begin
  if FOptionsBtn.Caption <> Value then
  begin
    FOptionsBtn.Caption := Value;
    ReSetButtonSize;
  end;
end;

//------------------------------------------------------------------------------

procedure TControlSelectorPanel.ReSetButtonSize;
var
  W: Integer;
  R: TRect;
begin
  W := 130;

  Canvas.Font.Name := 'Tahoma';
  Canvas.Font.Size := 8;

  if ShowAddAndRemoveBtn then
  begin
    R := Rect(0,0,1000,100);
    DrawText(Canvas.Handle,PChar(FAddAndRemoveBtn.Caption),Length(FAddAndRemoveBtn.Caption), R, DT_CALCRECT or DT_LEFT or DT_SINGlELINE);
    W := Max(W, R.Right + 15);
  end;

  if ShowOptionsBtn then
  begin
    R := Rect(0,0,1000,100);
    DrawText(Canvas.Handle,PChar(FOptionsBtn.Caption),Length(FOptionsBtn.Caption), R, DT_CALCRECT or DT_LEFT or DT_SINGlELINE);
    W := Max(W, R.Right + 15);
  end;

  FAddAndRemoveBtn.Width := W;
  FOptionsBtn.Width := W;
end;

//------------------------------------------------------------------------------

function TControlSelectorPanel.GetTextAutoOptionMenu: String;
begin
  Result := FAddAndRemoveBtn.Caption;
end;

//------------------------------------------------------------------------------

function TControlSelectorPanel.GetTextOptionMenu: String;
begin
  Result := FOptionsBtn.Caption;
end;

//------------------------------------------------------------------------------

{ TSelectorItem }

constructor TSelectorItem.Create;
begin
  inherited;
  FHeight := DEFAULT_ITEMHEIGHT;
  FWidth := 30;
  FCaption := '';
end;

//------------------------------------------------------------------------------

destructor TSelectorItem.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TSelectorItem.SetCaption(const Value: TCaption);
begin
  FCaption := Value;
end;

//------------------------------------------------------------------------------

procedure TSelectorItem.SetHeight(const Value: Integer);
begin
  FHeight := Value;
end;

//------------------------------------------------------------------------------

procedure TSelectorItem.SetWidth(const Value: Integer);
begin
  FWidth := Value;
end;

//------------------------------------------------------------------------------

{ TATBPopupWindow }

constructor TATBPopupWindow.Create(AOwner: TComponent);
begin
  inherited;
  FHideOnDeActivate := true;
  FHideTimer := TTimer.Create(self);
  FHideTimer.Interval := 1;
  FHideTimer.Enabled := false;
  FHideTimer.OnTimer := HideTimerOnTime;
end;

//------------------------------------------------------------------------------

constructor TATBPopupWindow.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
  inherited;
  FOwner := AOwner;
  FHideOnDeActivate := true;
  FHideTimer := TTimer.Create(self);
  FHideTimer.Interval := 1;
  FHideTimer.Enabled := false;
  FHideTimer.OnTimer := HideTimerOnTime;

  CreatePopupPanel;
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.CreatePopupPanel;
begin
  FPopupPanel := TATBPopupPanel.Create(self);
  FPopupPanel.Parent := Self;
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.CreateItems;
begin
  FItems := TATBMenuItem.Create;
  FPopupPanel.Items := FItems;
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.CreateParams(var Params: TCreateParams);
const
  CS_DROPSHADOW = $00020000;
begin
  inherited CreateParams(Params);
  //Params.Style := Params.Style - WS_BORDER;
  {
  if (Win32Platform = VER_PLATFORM_WIN32_NT) and
     ((Win32MajorVersion > 5) or
      ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1))) then
    Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;

  Params.ExStyle := Params.ExStyle or WS_EX_TOPMOST; }
end;

//------------------------------------------------------------------------------

destructor TATBPopupWindow.Destroy;
begin
  FHideTimer.Free;
  if Assigned(FItems) then
    FItems.Free;
  inherited;
end;

//------------------------------------------------------------------------------

function TATBPopupWindow.GetParentWnd: HWnd;
var
  Last, P: HWnd;
begin
  P := GetParent((Owner as TWinControl).Handle);
  if Assigned(AdvToolBar) then
    P := GetParent(AdvToolBar.Handle);   // Set to avoid DeActivate of Form

  Last := P;
  while P <> 0 do
  begin
    Last := P;
    P := GetParent(P);
  end;
  Result := Last;
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.HideTimerOnTime(Sender: TObject);
begin
 { if Assigned(FPopupPanel) then
    FPopupPanel.BeforeHide;
  }
  Hide;
  FHideTimer.Enabled := false;
  if Assigned(OnDeActivateHide) then
    FOnDeActivateHide(Self);
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.Paint;
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.SetPopupPanel(const Value: TATBPopupPanel);
begin
  //FPopupPanel := Value;
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.SetWindowSize;
begin
  if Assigned(FPopupPanel) then
  begin
    Height := FPopupPanel.GetVisibleHeight;
    Width := FPopupPanel.Width;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.WMActivate(var Message: TWMActivate);
begin
  if Message.Active = integer(False) then
  begin
    if HideOnDeActivate and Visible then
    begin
      FHideTimer.Enabled := true;
    end;
  end
  else if Assigned(FPopupPanel) then
  begin
    FPopupPanel.SetFocus;
    SendMessage(getParentWnd, WM_NCACTIVATE, 1, 0);
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.WMNCHitTest(var Message: TWMNCHitTest);
var
  pt: TPoint;
begin
  // Make the hint sizable
  pt := ScreenToClient(Point(Message.XPos, Message.YPos));

  if (pt.X > Width - 10) and (pt.Y > Height - 10) then
    message.Result := HTBOTTOMRIGHT
end;

//------------------------------------------------------------------------------

procedure TATBPopupWindow.Hide;
begin
  if Assigned(FPopupPanel) then
    FPopupPanel.BeforeHide;

  inherited Hide;
end;

//------------------------------------------------------------------------------

{ TATBCustomPopupPanel }

constructor TATBCustomPopupPanel.Create(AOwner: TComponent);
begin
  inherited;
  FOwner := AOwner;
  BevelOuter := bvNone;
  BevelWidth := 1;
  Color := $00F7F8F9;
  FColorTo := clNone;
  FWindowBorderColor := clGray;
  FGradientDirection := gdHorizontal;
  FMarginX := 2;
  FMarginY := 2;
end;

//------------------------------------------------------------------------------

function TATBCustomPopupPanel.GetVisibleHeight: integer;
begin
  Result := Height;
end;

//------------------------------------------------------------------------------

procedure TATBCustomPopupPanel.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TATBCustomPopupPanel.Paint;
var
  R: TRect;
begin
  inherited;
  R := Rect(0, 0, Width, Height);

  if ColorTo <> clNone then
    DrawGradient(Canvas, Color, ColorTo, 40, R, FGradientDirection = gdHorizontal);

  Canvas.Brush.Style := bsClear;
  Canvas.Pen.Color := FWindowBorderColor;

  Canvas.MoveTo(0, 0);
  Canvas.LineTo(0, Height);

  //if TSelectorDropDownWindow(FOwner).ShowFullBorder then
  //begin
  Canvas.MoveTo(0, 0);
  Canvas.LineTo(Width - 1, 0);
  Canvas.MoveTo(0, Height - 1);
  Canvas.LineTo(Width - 1, Height - 1);
{  end
  else
  begin

  end;
  }
  Canvas.MoveTo(Width - 1, Height);
  Canvas.LineTo(Width - 1, {0} -1);
end;

//------------------------------------------------------------------------------

procedure TATBCustomPopupPanel.SetColorTo(const Value: TColor);
begin
  FColorTo := Value;
end;

//------------------------------------------------------------------------------

procedure TATBCustomPopupPanel.SetGradientDirection(
  const Value: TGradientDirection);
begin
  FGradientDirection := Value;
end;

//------------------------------------------------------------------------------

procedure TATBCustomPopupPanel.SetMarginX(const Value: Integer);
begin
  FMarginX := Value;
end;

//------------------------------------------------------------------------------

procedure TATBCustomPopupPanel.SetMarginY(const Value: Integer);
begin
  FMarginY := Value;
end;

//------------------------------------------------------------------------------

procedure TATBCustomPopupPanel.SetWindowBorderColor(const Value: TColor);
begin
  FWindowBorderColor := Value;
end;

//------------------------------------------------------------------------------

{ TATBMenuItem }

constructor TATBMenuItem.Create;
begin
  inherited;
  FItems := TDbgList.Create;
  FObjects := nil;
  FEnabled := True;
  FVisible := True;
end;

//------------------------------------------------------------------------------

destructor TATBMenuItem.Destroy;
  procedure FreeAllItems(AItem: TATBMenuItem);
  var
    I: Integer;
  begin
    for I:= 0 to AItem.Count-1 do
    begin
      FreeAllItems(AItem.Items[I]);
    end;
    AItem.Free;
  end;

var
  I: Integer;
begin
  for I:= 0 to FItems.Count-1 do
    TATBMenuItem(FItems.Items[I]).Free;
    //FreeAllItems(FItems.Items[I]);

  FItems.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.Clear;
{  procedure FreeAllItems(AItem: TATBMenuItem);
  var
    I: Integer;
  begin
    for I:= 0 to AItem.Count-1 do
    begin
      FreeAllItems(AItem.Items[I]);
    end;
    AItem.Free;
  end;
}
var
  I: Integer;
begin
  for I:= 0 to FItems.Count-1 do
    TATBMenuItem(FItems.Items[I]).Free;
    //FreeAllItems(FItems.Items[I]);
  FItems.Clear;
end;

//------------------------------------------------------------------------------

function TATBMenuItem.GetCount: integer;
begin
  Result := FItems.Count;
end;

//------------------------------------------------------------------------------

function TATBMenuItem.GetItem(Index: Integer): TATBMenuItem;
begin
  Result := FItems.Items[Index];
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.SetCaption(const Value: TCaption);
begin
  FCaption := Value;
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.SetChecked(const Value: Boolean);
begin
  FChecked := Value;
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.SetEnabled(const Value: Boolean);
begin
  FEnabled := Value;
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.SetFParentItem(const Value: TATBMenuItem);
begin
  FParentItem := Value;
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.SetHeight(const Value: Integer);
begin
  FHeight := Value;
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.SetVisible(const Value: Boolean);
begin
  FVisible := Value;
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.SetWidth(const Value: Integer);
begin
  FWidth := Value;
end;

//------------------------------------------------------------------------------

function TATBMenuItem.HasChildren: Boolean;
begin
  Result := FItems.Count > 0;
end;

//------------------------------------------------------------------------------

function TATBMenuItem.Add: TATBMenuItem;
begin
  Result := TATBMenuItem.Create;
  Result.ParentItem := Self;
  FItems.Add(Result);
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.SetAutoCheck(const Value: Boolean);
begin
  FAutoCheck := Value;
end;

//------------------------------------------------------------------------------

procedure TATBMenuItem.RemoveItem(ItemIndex: Integer);
begin

end;

//------------------------------------------------------------------------------

{ TATBPopupPanel }

constructor TATBPopupPanel.Create(AOwner: TComponent);
begin
  inherited;
  FItemHeight := 24;
  ImageBarSize := 20;
  FImageBarColor := clGray;
  FImageBarColorTo := clNone;
  FHotItem := -1;
  FPopupItem := -1;
end;

//------------------------------------------------------------------------------

destructor TATBPopupPanel.Destroy;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.ArrangeItems;
var
  i, L, T, W: integer;
begin
  L := MarginX;
  T := MarginY;

  w := 0;
  for i:= 0 to FItems.Count-1 do
  begin
    w := max(w, Canvas.TextWidth(FItems.Items[i].Caption)+ {4}7);
    if FItems.Items[i].HasChildren then
      inc(w, 30);

    if not ShowImageBar and (FItems.Items[i].Objects <> nil) then
    begin
      if (TControl(FItems.Items[i].Objects) is TAdvCustomToolBarButton) then
      begin
        if (TAdvCustomToolBarButton(FItems.Items[i].Objects).ImageIndex >= 0) or not (TAdvCustomToolBarButton(FItems.Items[i].Objects).Glyph.Empty) then
          ShowImageBar := True;
      end
      else if (TControl(FItems.Items[i].Objects) is TAdvCustomGlowButton) then
      begin
        if (TAdvCustomGlowButton(FItems.Items[i].Objects).ImageIndex >= 0) or not (TAdvCustomGlowButton(FItems.Items[i].Objects).Picture.Empty) or
           ((TAdvCustomGlowButton(FItems.Items[i].Objects).Action is TCustomAction) and Assigned(TCustomAction(TAdvCustomGlowButton(FItems.Items[i].Objects).Action).ActionList) and (TCustomAction(TAdvCustomGlowButton(FItems.Items[i].Objects).Action).ImageIndex >= 0)) then
          ShowImageBar := True;
      end;
    end;
  end;

  if Assigned(AdvMenuStyler) then
    if ShowIconBar then
      W := w + AdvMenuStyler.IconBar.Size;

  if ShowImageBar then
    w := w + ImageBarSize;

  w := Max(w, MIN_POPUPWINDOWSIZE);
  
  for i:= 0 to FItems.Count-1 do
  begin
    FItems.Items[i].BoundRect := Rect(L, T, L + W, T + ItemHeight);
    inc(T, ItemHeight + MarginY);
  end;

  Width := w + MarginX * 2;
  Height := T;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.CMMouseLeave(var Message: TMessage);
begin
  inherited;
  if FPopupItem < 0 then
    HotItem := -1;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.MouseMove(Shift: TShiftState; X, Y: Integer);
var
  i: Integer;
begin
  inherited;
  i := IndexOfItemAt(X, Y);
  if (i >= 0) then
  begin
    if (i <> HotItem) and not (ssLeft in Shift) then
    begin
      HotItem := i;
      ShowItemPopup;
    end
    else
    begin
      //ShowItemPopup;
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.MouseUp(Button: TMouseButton; Shift: TShiftState;
  X, Y: Integer);
var
  i: Integer;
begin
  inherited;
  i := IndexOfItemAt(X, Y);
  if (i >= 0) then
  begin
    ItemClick(i);
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.Paint;
var
  R, R2: TRect;
begin
  inherited;

  R := ClientRect;
  R := Rect(R.Left + MarginX, R.Top + MarginY, R.Right - MarginX, R.Bottom - MarginY);
  R2 := R;
  R2.Right := R.Left;

  if Assigned(AdvMenuStyler) and ShowIconBar then
  begin
    R2.Right := R2.Right + AdvMenuStyler.IconBar.Size;
    
    if ShowImageBar then
      R2.Right := R2.Right + ImageBarSize;
      
    with AdvMenuStyler.IconBar do
    begin
      if (AdvMenuStyler.IconBar.Color <> clNone) and (AdvMenuStyler.IconBar.ColorTo <> clNone) then
        DrawGradient(Canvas, AdvMenuStyler.IconBar.Color, AdvMenuStyler.IconBar.ColorTo, 40, R2, True)
      else
      begin
        Canvas.Brush.Color := AdvMenuStyler.IconBar.Color;
        Canvas.Pen.Color := AdvMenuStyler.IconBar.Color;
        Canvas.Rectangle(R2);
      end;
      // ToDO:
      ImageBarColor := AdvMenuStyler.IconBar.ColorTo;
    end;
  end;

  if ShowImageBar and not ShowIconBar then
  begin
    ImageBarColor := AdvMenuStyler.IconBar.Color;
    ImageBarColorTo := AdvMenuStyler.IconBar.ColorTo;

    R2.Right := R2.Right + ImageBarSize;

    if (ImageBarColor <> clNone) and (ImageBarColorTo <> clNone) then
      DrawGradient(Canvas, ImageBarColor, ImageBarColorTo, 40, R2, True)
    else
    begin
      Canvas.Brush.Color := ImageBarColor;
      Canvas.Pen.Color := ImageBarColor;
      Canvas.Rectangle(R2);
    end;
  end;

  DrawAllItems;  
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.SetAdvMenuStyler(
  const Value: TCustomAdvMenuStyler);
begin
  FAdvMenuStyler := Value;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.SetItems(const Value: TATBMenuItem);
begin
  FItems := Value;
  ArrangeItems;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.SetItemHeight(const Value: Integer);
begin
  FItemHeight := Value;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.SetHotItem(const Value: Integer);
var
  I: Integer;
begin
  if FHotItem <> Value then
  begin
    if (FHotItem >= 0) then
    begin
      I := FHotItem;
      HideItemPopup;
      FHotItem := -1;
      InvalidateItem(I);
    end;
    FHotItem := Value;
    if FHotItem >= 0 then
      InvalidateItem(FHotItem);
  end;
end;

//------------------------------------------------------------------------------

function TATBPopupPanel.IndexOfItemAt(X, Y: Integer): Integer;
var
  i: Integer;
begin
  Result := -1;

  for i:= 0 to FItems.Count-1 do
  begin
    if PtInRect(FItems.Items[i].BoundRect, Point(X, Y)) then
    begin
      Result := i;
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.ToggleCheck(ItemIndex: Integer);
begin
  if (ItemIndex >= 0) and (ItemIndex < FItems.Count) then
  begin
    if FItems.Items[ItemIndex].Objects <> nil then
    begin
      TControl(FItems.Items[ItemIndex].Objects).Visible := not TControl(FItems.Items[ItemIndex].Objects).Visible;
      FItems.Items[ItemIndex].Checked := TControl(FItems.Items[ItemIndex].Objects).Visible;
      InvalidateItem(ItemIndex);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.SetShowImageBar(const Value: Boolean);
begin
  FShowImageBar := Value;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.DrawAllItems;
var
  i: Integer;
begin
  for I:= 0 to FItems.Count-1 do
    DrawItem(I);
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.DrawItem(ItemIndex: Integer);
var
  CapR, R, R2: TRect;

  procedure DrawCheck(R: TRect);
  var
    Glyph: TBitMap;
  begin
    if FItems.Items[ItemIndex].Checked then
    begin
      if FItems.Items[ItemIndex].Enabled then
      begin
        Glyph := TBitmap.Create;
        try
          begin
            if (HotItem = ItemIndex) then
              with AdvMenuStyler.SelectedItem do
              begin
                if (CheckColorTo <> clNone) then
                  DrawGradient(Canvas, CheckColor, CheckColorTo, 16, R, True)
                else if CheckColor <> clNone then
                begin
                  Canvas.Brush.Color := CheckColor;
                  Canvas.Pen.Color := CheckColor;
                  Canvas.Rectangle(R);
                end;
                if BorderColor <> clNone then
                begin
                  Canvas.Brush.Color := BorderColor;
                  Canvas.FrameRect(R);
                end;
              end
            else
              with AdvMenuStyler.IconBar do
              begin
                if (CheckColorTo <> clNone) then
                  DrawGradient(Canvas, CheckColor, CheckColorTo, 16, R, True)
                else if CheckColor <> clNone then
                begin
                  Canvas.Brush.Color := CheckColor;
                  Canvas.Pen.Color := CheckColor;
                  Canvas.Rectangle(R);
                end;
                if CheckBorder <> clNone then
                begin
                  Canvas.Brush.Color := CheckBorder;
                  Canvas.FrameRect(R);
                end;
              end;
            Glyph.Assign(AdvMenuStyler.Glyphs.Check);
          end;

          // restore selection rectangle
          if (HotItem = ItemIndex) then
          begin
            Canvas.Brush.Color := AdvMenuStyler.SelectedItem.BorderColor;
            Canvas.FrameRect(R);
          end;

          //OldFontColor := Canvas.Font.Color;
          //Canvas.Font.Color := clBtnText;
          Canvas.Draw(R.Left + ((R.Right-R.Left) - Glyph.Width) div 2, R.Top + ((R.Bottom - R.Top) - Glyph.Height) div 2, Glyph);
          //Canvas.Font.Color := OldFontColor;
        finally
          FreeAndNil(Glyph);
        end;

      end
      else
      begin

      end;
    end;
  end;

  procedure DrawImage(R: TRect);
  var
    tbmp: TBitMap;
    imgidx, PicW, PicH: Integer;
    images: TCustomImageList;
  begin
    if TControl(FItems.Items[ItemIndex].Objects) is TAdvCustomToolBarButton then
    begin
      images := nil;
      if (Parent is TATBPopupWindow) and Assigned(TATBPopupWindow(Parent).AdvToolBar) and Assigned(TATBPopupWindow(Parent).AdvToolBar.Images) then
        images := TATBPopupWindow(Parent).AdvToolBar.Images;

      imgidx := TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).ImageIndex;

      if (TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).Action is TCustomAction) then
      begin
        if Assigned((TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).Action as TCustomAction).ActionList) then
        begin
          if Assigned((TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).Action as TCustomAction).ActionList.Images) then
            images := (TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).Action as TCustomAction).ActionList.Images;

          imgidx := (TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).Action as TCustomAction).ImageIndex;
        end;
      end;

      if (imgidx >= 0) and (images <> nil) then
      begin
        tbmp := TBitmap.Create;
        tbmp.Width := images.Width;
        tbmp.Height := images.Height;
        tbmp.PixelFormat := pf32bit;

        if (tbmp.Width <= R.Right - R.Left) and (tbmp.Height <= R.Bottom - R.Top) then
        begin
          //Images.Draw(tbmp.Canvas, 0, 0, ImgIdx);
          //tbmp.TransparentMode := tmAuto;
          //tbmp.Transparent := true;
          //Canvas.Draw(R.left+(R.Right-R.Left-tbmp.width) div 2 , R.Top+(R.Bottom-R.Top-tbmp.height) div 2, tbmp);
          Images.Draw(Canvas, R.left+(R.Right-R.Left-tbmp.width) div 2, R.Top+(R.Bottom-R.Top-tbmp.height) div 2, ImgIdx);
        end
        else
        begin
          Images.Draw(tbmp.Canvas, 0, 0, ImgIdx);
          tbmp.TransparentMode := tmAuto;
          tbmp.Transparent := true;
          Canvas.StretchDraw(R, tbmp);
        end;
        tbmp.Free;
      end
      else if not TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).Glyph.Empty then
      begin
        tbmp := TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).Glyph;
        if (tbmp.Width <= R.Right - R.Left) and (tbmp.Height <= R.Bottom - R.Top) then
        begin
          Canvas.Draw(R.left+(R.Right-R.Left-tbmp.width) div 2 , R.Top+(R.Bottom-R.Top-tbmp.height) div 2, tbmp);
        end
        else
          Canvas.StretchDraw(R, TAdvCustomToolBarButton(FItems.Items[ItemIndex].Objects).Glyph);
      end;
    end
    else if TControl(FItems.Items[ItemIndex].Objects) is TAdvCustomGlowButton then
    begin
      images := nil;
      if (Parent is TATBPopupWindow) and Assigned(TATBPopupWindow(Parent).AdvToolBar) and Assigned(TATBPopupWindow(Parent).AdvToolBar.Images) then
        images := TATBPopupWindow(Parent).AdvToolBar.Images;

      imgidx := TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).ImageIndex;

      if (TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).Action is TCustomAction) then
      begin
        if Assigned((TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).Action as TCustomAction).ActionList) then
        begin
          if Assigned((TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).Action as TCustomAction).ActionList.Images) then
            images := (TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).Action as TCustomAction).ActionList.Images;

          imgidx := (TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).Action as TCustomAction).ImageIndex;
        end;
      end;

      if (imgidx >= 0) and (images <> nil) then
      begin
        tbmp := TBitmap.Create;
        tbmp.Width := images.Width;
        tbmp.Height := images.Height;
        tbmp.Transparent := true;
        if (tbmp.Width <= R.Right - R.Left) and (tbmp.Height <= R.Bottom - R.Top) then
        begin
          Images.Draw(tbmp.Canvas, 0, 0, ImgIdx);
          Canvas.Draw(R.left+(R.Right-R.Left-tbmp.width) div 2 , R.Top+(R.Bottom-R.Top-tbmp.height) div 2, tbmp);
        end
        else
        begin
          Images.Draw(tbmp.Canvas, 0, 0, ImgIdx);
          Canvas.StretchDraw(R, tbmp);
        end;
        tbmp.Free;
      end
      else if not TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).Picture.Empty then
      begin
        TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).picture.GetImageSizes;
        PicW := TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).picture.Width;
        PicH := TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).picture.Height;
        if (PicW <= R.Right - R.Left) and (PicH <= R.Bottom - R.Top) then
        begin
          Canvas.Draw(R.left+(R.Right-R.Left-PicW) div 2 , R.Top+(R.Bottom-R.Top-PicH) div 2, TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).picture);
        end
        else
          Canvas.StretchDraw(R, TAdvCustomGlowButton(FItems.Items[ItemIndex].Objects).Picture);
      end;
    end;
  end;

  procedure DrawSubmenuTriangle(ARect: TRect);
  var
    R: TRect;
    DY: Integer;
  begin
    DY:= (ARect.Top + ARect.Bottom - 5) div 2;
    // Default submenu triangle has 4x7 size
    //if Alignment <> paRight then
      R := Rect(ARect.Right - 8, DY, ARect.Right - 5, DY + 6);
    //else
      //R := Rect(ARect.Left + 5, DY, ARect.Left + 8, DY + 6);

    with AdvMenuStyler.Glyphs do
    begin
      CenterRect(R, SubMenu.Width, SubMenu.Height);
      //OldFontColor := ACanvas.Font.Color;
      //ACanvas.Font.Color := TriangleColor;
      Canvas.Draw(R.Left, R.Top, AdvMenuStyler.Glyphs.SubMenu);
      //Canvas.Font.Color := OldFontColor;
     end;
  end;

begin
  R := FItems.Items[ItemIndex].BoundRect;
  CapR := R;
  if HotItem = ItemIndex then
  begin
    with AdvMenuStyler.SelectedItem do
    begin
      if (Color <> clNone) and (ColorTo <> clNone) then
        DrawGradient(Canvas, Color, ColorTo, 40, R, AdvMenuStyler.SelectedItem.GradientDirection = AdvMenus.gdHorizontal)
      else
      begin
        Canvas.Brush.Color := Color;
        Canvas.Pen.Color := Color;
        Canvas.Rectangle(R);
      end;
      if AdvMenuStyler.SelectedItem.BorderColor <> clNone then
      begin
        Canvas.Brush.Style := bsClear;
        Canvas.Pen.Color := AdvMenuStyler.SelectedItem.BorderColor;
        Canvas.Rectangle(R);
      end;
    end;
  end;

  if ShowIconBar then
  begin
    R.Right := R.Left + AdvMenuStyler.IconBar.Size;
    CapR.Left := R.Right;
    R2 := Rect(R.Left+1, R.Top+1, R.Right-2, R.Bottom-1);
    if FItems.Items[ItemIndex].AutoCheck then
    begin
      DrawCheck(R2);
    end
    else if not ShowImageBar then
    begin
      DrawImage(R);
    end;
  end;

  if ShowImageBar then
  begin
    R.Left := R.Right;
    R.Right := R.Left + ImageBarSize;
    CapR.Left := R.Right;
    DrawImage(R);
  end;

  // Draw Caption
  CapR.Left := CapR.Left + 4{Text Margin};
  //R.Right := FItems.Items[ItemIndex].BoundRect.Right;
  Canvas.Brush.Style := bsClear;
  DrawText(Canvas.Handle, PChar(FItems.Items[ItemIndex].Caption), -1, CapR, DT_SINGLELINE or DT_VCENTER or DT_LEFT);

  if FItems.Items[ItemIndex].HasChildren then
    DrawSubmenuTriangle(FItems.Items[ItemIndex].BoundRect);
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.InvalidateItem(ItemIndex: Integer);
var
  R: TRect;
begin
  if (ItemIndex >= 0) and (ItemIndex < FItems.Count) then
  begin
    R := FItems.Items[ItemIndex].BoundRect;
    InvalidateRect(Handle, @R, True);
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.SetShowIconBar(const Value: Boolean);
begin
  FShowIconBar := Value;
end;

//------------------------------------------------------------------------------

function TATBPopupPanel.IsAnyAutoCheckItem: Boolean;
begin
  Result := True;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.SetImageBarSize(const Value: Integer);
begin
  FImageBarSize := Value;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.ShowItemPopup;
var
  P : TPoint;
  R: TRect;
begin
  if (FPopupItem <> HotItem) and (HotItem >= 0) then
  begin
    HideItemPopup;
    if (HotItem >= 0) and FItems.Items[HotItem].HasChildren then
    begin
      if not Assigned(FItemPopup) then
      begin
        FItemPopup:= TATBPopupWindow.CreateNew(self{TOptionSelectorWindow(Parent).AdvToolBar});
        FItemPopup.BorderIcons := [];
        FItemPopup.BorderStyle := bsNone;
        FItemPopup.Ctl3D := false;
        FItemPopup.FormStyle := fsStayOnTop;
        FItemPopup.Visible := False;
        FItemPopup.Width := 10;
        FItemPopup.Height := 10;
        FItemPopup.AutoScroll := False;
        FItemPopup.BorderWidth := 0;
        FItemPopup.AdvToolBar := TATBPopupWindow(Parent).AdvToolBar;
        FItemPopup.OnHide := OnItemPopupHide;
        FItemPopup.OnDeActivateHide := OnItemPopupDeActivateHide;
      end;

      //FItemPopup.PopupPanel.Items.Clear;
      FItemPopup.PopupPanel.Items := FItems.Items[HotItem];
      FItemPopup.PopupPanel.ShowIconBar := True;
      FItemPopup.PopupPanel.AdvMenuStyler := AdvMenuStyler;

      FPopupItem := FHotItem;

      FItemPopup.PopupPanel.ArrangeItems;
      FItemPopup.SetWindowSize;

      TOptionSelectorWindow(Parent).HideOnDeActivate := False;

      // Positioning Window

      //P := ClientToScreen(Point(Left, Top));

    {$IFNDEF TMSDOTNET}
      SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
    {$ENDIF}
    {$IFDEF TMSDOTNET}
      SystemParametersInfo(SPI_GETWORKAREA, 0, R, 0);
    {$ENDIF}

      P := ClientToScreen(Point(FItems.Items[HotItem].BoundRect.Right+2, FItems.Items[HotItem].BoundRect.Top));

      if R.Bottom < (P.Y + FItemPopup.Height + 2) then
        P.Y := P.Y - ((P.Y + FItemPopup.Height + 2) - R.Bottom);

      if (R.Right < P.X + FItemPopup.Width) then
        P.X := ClientToScreen(Point(FItems.Items[HotItem].BoundRect.Left, FItems.Items[HotItem].BoundRect.Top)).X - FItemPopup.Width;

      FItemPopup.Left := P.X;
      FItemPopup.Top := P.Y;
      FItemPopup.Visible := True;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.HideItemPopup;
begin
  if Assigned(FItemPopup) and FItemPopup.Visible then
  begin
    FItemPopup.Hide;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.OnItemPopupDeActivateHide(Sender: TObject);
begin
  TATBPopupWindow(Parent).Hide;
    if Assigned(TATBPopupWindow(Parent).OnDeActivateHide) then
      TATBPopupWindow(Parent).FOnDeActivateHide(TATBPopupWindow(Parent));
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.OnItemPopupHide(Sender: TObject);
begin
  if Assigned(Parent) and (Parent is TATBPopupWindow) then
    TATBPopupWindow(Parent).HideOnDeActivate := True;
  FPopupItem := -1;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.ItemClick(ItemIndex: Integer);
begin
  if (ItemIndex >= 0) and (ItemIndex < FItems.Count) then
  begin
    if FItems.Items[ItemIndex].AutoCheck then
    begin
      ToggleCheck(ItemIndex);
    end
    else
    begin

    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBPopupPanel.BeforeHide;
begin
  HideItemPopup;
  FHotItem := -1;
  FPopupItem := -1;
end;

//------------------------------------------------------------------------------

{ TAdvToolBarButtonDrawPosition }

procedure TAdvToolBarButtonDrawPosition.Assign(Source: TPersistent);
begin
  if (Source is TAdvToolBarButtonDrawPosition) then
  begin
    FTextX := (Source as TAdvToolBarButtonDrawPosition).TextX;
    FTextY := (Source as TAdvToolBarButtonDrawPosition).TextY;
    FImageX := (Source as TAdvToolBarButtonDrawPosition).ImageX;
    FImageY := (Source as TAdvToolBarButtonDrawPosition).ImageY;
    FEnabled := (Source as TAdvToolBarButtonDrawPosition).Enabled;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarButtonDrawPosition.Changed;
begin
  if Assigned(OnChange) then
    OnChange(Self);
end;

//------------------------------------------------------------------------------

constructor TAdvToolBarButtonDrawPosition.Create;
begin
  inherited;
  FTextX := 0;
  FTextY := 0;
  FEnabled := False;
  FImageX := 0;
  FImageY := 0;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarButtonDrawPosition.SetEnabled(const Value: Boolean);
begin
  if FEnabled <> Value then
  begin
    FEnabled := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarButtonDrawPosition.SetImageX(const Value: integer);
begin
  if FImageX <> Value then
  begin
    FImageX := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarButtonDrawPosition.SetImageY(const Value: Integer);
begin
  if FImageY <> Value then
  begin
    FImageY := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarButtonDrawPosition.SetTextX(const Value: integer);
begin
  if FTextX <> Value then
  begin
    FTextX := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarButtonDrawPosition.SetTextY(const Value: integer);
begin
  if FTextY <> Value then
  begin
    FTextY := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

{ TDbgList }


procedure TDbgList.AssignList(ListA: TList);
var
  I: Integer;
begin
  Clear;
  //Capacity := ListA.Capacity;
  for I := 0 to ListA.Count - 1 do
    Add(ListA[I]);
end;

//------------------------------------------------------------------------------

function TDbgList.GetItemsEx(Index: Integer): Pointer;
begin
  if (Index >= Count) then
  begin
    raise Exception.Create('Index out of bounds in list read access');
  end;

  if Index < Count then
    Result := inherited Items[Index]
  else
    Result := nil;
end;

//------------------------------------------------------------------------------

procedure TDbgList.SetItemsEx(Index: Integer; const Value: Pointer);
begin
  if (Index >= Count) then
  begin
    raise Exception.Create('Index out of bounds in list write access');
  end;
  if Index < Count then
    inherited Items[Index] := value;
end;

//------------------------------------------------------------------------------

{$IFNDEF TMS_STD}

{ TDBATBButtonDataLink }

constructor TDBATBButtonDataLink.Create;
begin
  inherited Create;
  FOnEditingChanged := nil;
  FOnDataSetChanged := nil;
  FOnActiveChanged := nil;
end;

//------------------------------------------------------------------------------

procedure TDBATBButtonDataLink.ActiveChanged;
begin
  if Assigned(FOnActiveChanged) then FOnActiveChanged(Self);
end;

//------------------------------------------------------------------------------

procedure TDBATBButtonDataLink.DataSetChanged;
begin
  if Assigned(FOnDataSetChanged) then FOnDataSetChanged(Self);
end;

//------------------------------------------------------------------------------

procedure TDBATBButtonDataLink.EditingChanged;
begin
  if Assigned(FOnEditingChanged) then FOnEditingChanged(Self);
end;

//------------------------------------------------------------------------------

{ TDBAdvToolBarButton }

constructor TDBAdvToolBarButton.Create(AOwner: TComponent);
begin
  inherited;
  FAutoDisable := True;
  FDBButtonType := dbtCustom;
  FDisableControls := [];
  FDataLink := TDBATBButtonDataLink.Create;
  with FDataLink do
  begin
    OnEditingChanged := OnDataSetEvents;
    OnDataSetChanged := OnDataSetEvents;
    OnActiveChanged := OnDataSetEvents;
  end;
  FConfirmActionString := '';  
end;

//------------------------------------------------------------------------------

destructor TDBAdvToolBarButton.Destroy;
begin
  FDataLink.Free;
  FDataLink := nil;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.CalcDisableReasons;
begin
  case FDBButtonType of
    dbtPrior:    FDisableControls := [drBOF, drEditing, drEmpty];
    dbtNext:     FDisableControls := [drEOF, drEditing, drEmpty];
    dbtFirst:    FDisableControls := [drBOF, drEditing, drEmpty];
    dbtLast:     FDisableControls := [drEOF, drEditing, drEmpty];
    dbtInsert,
    dbtAppend:   FDisableControls := [drReadonly, drEditing];
    dbtEdit:     FDisableControls := [drReadonly, drEditing, drEmpty];
    dbtCancel:   FDisableControls := [drNotEditing];
    dbtPost:     FDisableControls := [drNotEditing];
    dbtRefresh:  FDisableControls := [drEditing];
    dbtDelete:   FDisableControls := [drReadonly, drEditing, drEmpty];
  end;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.Click;
begin
  inherited;
  DoAction;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.CMEnabledChanged(var Message: TMessage);
begin
  inherited;
  if (not FInProcUpdateEnabled) and
     (not (csLoading in ComponentState)) and
     (not (csDestroying in ComponentState)) then
  begin
    UpdateEnabled;
  end;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.DoAction;
var
  DoAction: Boolean;
  ShowException: Boolean;
begin
  if not DoConfirmAction then
    Exit;

  DoAction := (FDBButtonType <> dbtCustom);
  try
    DoBeforeAction(DoAction);
    if DoAction and (DataSource <> nil) and (DataSource.State <> dsInactive) then
    begin
      with DataSource.DataSet do
      begin
        case FDBButtonType of
          dbtPrior: Prior;
          dbtNext: Next;
          dbtFirst: First;
          dbtLast: Last;
          dbtInsert: Insert;
          dbtAppend: Append;
          dbtEdit: Edit;
          dbtCancel: Cancel;
          dbtPost: Post;
          dbtRefresh:Refresh;
          dbtDelete: Delete;
        end;
      end;
    end;
    ShowException := false;
  except
    ShowException := true;
    if Assigned(FOnAfterAction) then
      FOnAfterAction(self, ShowException);
    if ShowException then
      raise;
    ShowException := true;
  end;
  if not ShowException and DoAction and Assigned(FOnAfterAction) then
    FOnAfterAction(self, ShowException);
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.DoBeforeAction(var DoAction: Boolean);
begin
  if (not (csDesigning in ComponentState)) and Assigned(FOnBeforeAction) then
    FOnBeforeAction(self, DoAction);
end;

//------------------------------------------------------------------------------

function TDBAdvToolBarButton.DoConfirmAction: Boolean;
var
  Question: string;
  QuestionButtons: TMsgDlgButtons;
  QuestionHelpCtx: Longint;
  QuestionResult: Longint;
begin
  DoGetQuestion(Question, QuestionButtons, QuestionHelpCtx);
  if (Question <> '') then
  begin
    QuestionResult := MessageDlg(Question, mtConfirmation, QuestionButtons, QuestionHelpCtx);
    Result := (QuestionResult = idOk) or (QuestionResult = idYes);
  end
  else
    Result := true;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.DoGetQuestion(var Question: string;
  var Buttons: TMsgDlgButtons; var HelpCtx: Integer);
begin
  Question := '';
  if FConfirmAction then
  begin
    Question := FConfirmActionString;
    Buttons := mbOKCancel;
    HelpCtx := 0;
    if Assigned(FOnGetConfirm) then
      FOnGetConfirm(self, Question, Buttons, HelpCtx);
  end;
end;

//------------------------------------------------------------------------------

function TDBAdvToolBarButton.GetDataSource: TDataSource;
begin
  Result := FDataLink.DataSource;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.Notification(AComponent: TComponent;
  AOperation: TOperation);
begin
  inherited;
  if (AOperation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then
    DataSource := nil;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.SetDataSource(const Value: TDataSource);
begin
  FDataLink.DataSource := Value;
  if not (csLoading in ComponentState) then
    UpdateEnabled;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.SetDBButtonType(const Value: TDBButtonType);
begin
  if (Value = FDBButtonType) then
    Exit;

  if (Value = dbtDelete) and (FConfirmActionString = ''){and ConfirmAction} then
    FConfirmActionString := SDeleteRecordQuestion; //'Delete Record?';

  if (csReading in ComponentState) or (csLoading in ComponentState) then
  begin
    FDBButtonType := Value;
    CalcDisableReasons;
    exit;
  end;

  FDBButtonType := Value;
  LoadGlyph;
  CalcDisableReasons;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.UpdateEnabled;
var
  PossibleDisableReasons: TDBBDisableControls;
  GetEnable: Boolean;
  WasEnabled: Boolean;
begin
  if (csDesigning in ComponentState) or (csDestroying in ComponentState) or not FAutoDisable then
    Exit;

  FInProcUpdateEnabled := true;
  try
   WasEnabled := Enabled;
   if FDataLink.Active then
   begin
     PossibleDisableReasons := [];
     if FDataLink.DataSet.BOF then
       Include(PossibleDisableReasons, drBOF);
     if FDataLink.DataSet.EOF then
       Include(PossibleDisableReasons, drEOF);
     if not FDataLink.DataSet.CanModify then
       Include(PossibleDisableReasons, drReadonly);
     if FDataLink.DataSet.BOF and FDataLink.DataSet.EOF then
       Include(PossibleDisableReasons, drEmpty);
     if FDataLink.Editing then
       Include(PossibleDisableReasons, drEditing)
     else
       Include(PossibleDisableReasons, drNotEditing);

     GetEnable := ((FDisableControls - [drEvent])* PossibleDisableReasons = []);
     if (drEvent in FDisableControls) and (Assigned(FOnGetEnabled)) then
       FOnGetEnabled(Self, GetEnable);
     Enabled := GetEnable;
   end
   else
     Enabled := false;

   if (WasEnabled <> Enabled) and Assigned(FOnEnabledChanged) then
     FOnEnabledChanged(self);
  finally
    FInProcUpdateEnabled := false;
  end;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.Loaded;
begin
  inherited;
  if Glyph.Empty then
    LoadGlyph;
    
  UpdateEnabled;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.OnDataSetEvents(Sender: TObject);
begin
  UpdateEnabled;
end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.LoadGlyph;
begin
  if (csLoading in ComponentState) then
    Exit;

  case FDBButtonType of
    dbtPrior:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNPRIOR');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNPRIORD');
    end;
    dbtNext:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNNEXT');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNNEXTD');
    end;
    dbtFirst:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNFIRST');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNFIRSTD');
    end;
    dbtLast:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNLAST');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNLASTD');
    end;
    dbtInsert:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNINSERT');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNINSERTD');
    end;
    dbtAppend:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNINSERT');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNINSERTD');
    end;
    dbtEdit:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNEDIT');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNEDITD');
    end;
    dbtCancel:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNCANCEL');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNCANCELD');
    end;
    dbtPost:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNPOST');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNPOSTD');
    end;
    dbtRefresh:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNREFRESH');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNREFRESHD');
    end;
    dbtDelete:
    begin
      Glyph.LoadFromResourceName(HInstance, 'DBBTNDELETE');
      GlyphDisabled.LoadFromResourceName(HInstance, 'DBBTNDELETED');
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TDBAdvToolBarButton.SetConfirmActionString(const Value: String);
begin
  if FConfirmActionString <> Value then
  begin
    FConfirmActionString := Value;
  end;
end;


{$ENDIF}

//------------------------------------------------------------------------------

{ TATBCommand }

procedure TATBCommand.Assign(Source: TPersistent);
begin
  if Source is TATBCommand then
  begin
    Caption := (Source as TATBCommand).Caption;
    OnExecute := (Source as TATBCommand).OnExecute;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

constructor TATBCommand.Create(Collection: TCollection);
begin
  inherited;
  FOnExecute := nil;
  FCaption := '';
  ItemIndex := -1;
end;

//------------------------------------------------------------------------------

destructor TATBCommand.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TATBCommand.SetCaption(const Value: TCaption);
var
  S: String;
begin
  S := Value;
  while Pos(' ', S) > 0 do
    S[Pos(' ', S)] := '_';
  FCaption := S;
end;

//------------------------------------------------------------------------------

{ TATBCommands }

function TATBCommands.Add: TATBCommand;
begin
  Result := TATBCommand(inherited Add);
end;

//------------------------------------------------------------------------------

constructor TATBCommands.Create(AOwner: TAdvToolBarCustomizer);
begin
  inherited Create(TATBCommand);
  FOwner := AOwner;
end;

//------------------------------------------------------------------------------

function TATBCommands.GetItem(Index: Integer): TATBCommand;
begin
  Result := TATBCommand(inherited Items[Index]);
end;

//------------------------------------------------------------------------------

function TATBCommands.GetOwner: TPersistent;
begin
  Result := FOwner;
end;

//------------------------------------------------------------------------------

function TATBCommands.Insert(Index: Integer): TATBCommand;
begin
  Result := TATBCommand(inherited Insert(Index));
end;

//------------------------------------------------------------------------------

procedure TATBCommands.SetItem(Index: Integer; const Value: TATBCommand);
begin
  inherited Items[Index] := Value;
end;

//------------------------------------------------------------------------------

{ TButtonProperties }

procedure TButtonProperties.Assign(Source: TPersistent);
begin
  if (Source is TButtonProperties) then
  begin
    FCaption := (Source as TButtonProperties).Caption;
    FShowCaption := (Source as TButtonProperties).ShowCaption;
    FVisible := (Source as TButtonProperties).Visible;
    //FShaded := (Source as TButtonProperties).Shaded;
    FHint := (Source as TButtonProperties).Hint;
    FGlyph := (Source as TButtonProperties).Glyph;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TButtonProperties.Change;
begin
  if Assigned(FOnChange) then
    FOnChange(self);
end;

//------------------------------------------------------------------------------

constructor TButtonProperties.Create;
begin
  inherited Create;
  FCaption := True;
  FShowCaption := True;
  FVisible := False;
  FHint := True;
  FGlyph := True;
  //FFormCaption := 'Customize Button';
end;

//------------------------------------------------------------------------------

destructor TButtonProperties.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TButtonProperties.SetCaption(const Value: Boolean);
begin
  if FCaption <> Value then
  begin
    FCaption := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonProperties.SetGlyph(const Value: Boolean);
begin
  if FGlyph <> Value then
  begin
    FGlyph := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonProperties.SetHint(const Value: Boolean);
begin
  if FHint <> Value then
  begin
    FHint := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonProperties.SetShowCaption(const Value: Boolean);
begin
  if FShowCaption <> Value then
  begin
    FShowCaption := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TButtonProperties.SetVisible(const Value: Boolean);
begin
  if FVisible <> Value then
  begin
    FVisible := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

{ TCustomizedOptions }

procedure TCustomizedOptions.Assign(Source: TPersistent);
begin
  if (Source is TCustomizedOptions) then
  begin
    FAddButton := (Source as TCustomizedOptions).AddButton;
    FReOrder := (Source as TCustomizedOptions).ReOrder;
    FDelete := (Source as TCustomizedOptions).Delete;
    FDeleteAll := (Source as TCustomizedOptions).DeleteAll;
    FAddSeparator := (Source as TCustomizedOptions).AddSeparator;
    FAddGlowButton := (Source as TCustomizedOptions).AddGlowButton;
    EditButton := (Source as TCustomizedOptions).EditButton;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TCustomizedOptions.Change;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

constructor TCustomizedOptions.Create;
begin
  inherited Create;
  FAddButton := True;
  FReOrder := True;
  FDelete := True;
  FDeleteAll := False;
  FAddSeparator := True;
  FAddGlowButton := True;
  FEditButton := True;
end;

//------------------------------------------------------------------------------

destructor TCustomizedOptions.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TCustomizedOptions.SetAddButton(const Value: Boolean);
begin
  if FAddButton <> Value then
  begin
    FAddButton := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizedOptions.SetAddGlowButton(const Value: Boolean);
begin
  if (FAddGlowButton <> Value) then
  begin
    FAddGlowButton := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizedOptions.SetAddSeparator(const Value: Boolean);
begin
  if FAddSeparator <> Value then
  begin
    FAddSeparator := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizedOptions.SetDelete(const Value: Boolean);
begin
  if FDelete <> Value then
  begin
    FDelete := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizedOptions.SetDeleteAll(const Value: Boolean);
begin
  if FDeleteAll <> Value then
  begin
    FDeleteAll := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizedOptions.SetEditButton(const Value: Boolean);
begin
  if (FEditButton <> Value) then
  begin
    FEditButton := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizedOptions.SetReOrder(const Value: Boolean);
begin
  if FReOrder <> Value then
  begin
    FReOrder := Value;
    Change;
  end;
end;

//------------------------------------------------------------------------------

{ TAdvToolbarCustomizer }

procedure TAdvToolbarCustomizer.Assign(Source: TPersistent);
begin
  inherited;

end;

//------------------------------------------------------------------------------

constructor TAdvToolbarCustomizer.Create(AOwner: TComponent);
begin
  inherited;
  //FCaption := False;
  FEnablePersistence := True;
  //FLargeIcon := False;
  //FGlyphPosition := False;
  FFileName := '.\untitled.ini';
  FAdvToolBar := nil;
  FCommands := TATBCommands.Create(Self);
  FCommands.OnChange := OnCommandsChange;
  FButtonProperties := TButtonProperties.Create;
  FButtonProperties.OnChange := OnButtonPropChange;
  FLargeImages := nil;
  FDialogSettings := TDialogSettings.Create;
  FOptions := TCustomizedOptions.Create;
  FOptions.OnChange := OnOptionsChange;
  FDeleteItems := TDbgList.Create;
  //FFormCaption := 'Customizer';
end;

//------------------------------------------------------------------------------

destructor TAdvToolbarCustomizer.Destroy;
{var
  i: Integer; }
begin
  {for i:= 0 to FDeleteItems.Count-1 do
    TControl(FDeleteItems[i]).Free; }
  FCommands.Free;
  FButtonProperties.Free;
  FOptions.Free;
  FDialogSettings.Free;
  FDeleteItems.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.Loaded;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  inherited;
  
  if not (csDestroying in ComponentState) and (Operation = opRemove) then
  begin
    if (AComponent = FAdvToolBar) then
      AdvToolBar := nil;
    if (AComponent = FLargeImages) then
      LargeImages := nil;
    if (AComponent = FSmallImages) then
      SmallImages := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.OnButtonPropChange(Sender: TObject);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.OnCommandsChange(Sender: TObject);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.OnOptionsChange(Sender: TObject);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.SetAdvToolBar(
  const Value: TAdvToolBar);
begin
  if (FAdvToolBar <> Value) then
  begin
    if (FAdvToolBar <> nil) and (FAdvToolBar.Customizer = Self) then
      FAdvToolBar.Customizer := nil;
    FAdvToolBar := Value;

    if (FAdvToolBar <> nil) then
      FAdvToolBar.Customizer := Self;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.SetButtonProperties(
  const Value: TButtonProperties);
begin
  FButtonProperties.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.SetCommands(const Value: TATBCommands);
begin
  FCommands.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.SetEnablePersistence(const Value: Boolean);
begin
  FEnablePersistence := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.SetFileName(const Value: String);
begin
  FFileName := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.SetLargeImages(
  const Value: TCustomImageList);
begin
  FLargeImages := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.SetOptions(
  const Value: TCustomizedOptions);
begin
  FOptions.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.InitializeWindow;
begin
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.ShowCustomizer;
var
  R: TRect;
  pt, spt: TPoint;
  i, y: Integer;
  CanShow: Boolean;
begin
  if not Assigned(FAdvToolBar) then
    Exit;

  //--- Initialize Window
  if (CustomizerForm = nil) then
  begin
    CustomizerForm := TCustomizerForm.Create(Self);
  end;

  CustomizerForm.FToolBarCustomizer := Self;
  //--- Set Label and Hint
  CustomizerForm.UpButton.Hint := FDialogSettings.UpHint;
  CustomizerForm.TopButton.Hint := FDialogSettings.TopHint;
  CustomizerForm.LblToolBarItems.Caption := FDialogSettings.ToolBarLabel;
  CustomizerForm.DeleteButton.Hint := FDialogSettings.DeleteHint;
  CustomizerForm.BtnEdit.Hint := FDialogSettings.EditHint;
  CustomizerForm.LblCaption.Caption := FDialogSettings.CaptionLabel;
  CustomizerForm.LblGlphPos.Caption := FDialogSettings.GlyphPosLabel;
  CustomizerForm.LblCommands.Caption := FDialogSettings.CommandLabel;
  CustomizerForm.AddButton.Hint := FDialogSettings.AddHint;
  CustomizerForm.SeparatorButton.Hint := FDialogSettings.AddSeparatorHint;
  CustomizerForm.ClearButton.Hint := FDialogSettings.DeleteAllHint;
  CustomizerForm.BottomButton.Hint := FDialogSettings.BottomHint;
  CustomizerForm.DownButton.Hint := FDialogSettings.DownHint;
  CustomizerForm.AddGlowButton.Hint := FDialogSettings.AddGlowButtonHint;
  CustomizerForm.ChkLargeIcon.Caption := FDialogSettings.LargeIconCheck;
  CustomizerForm.Caption := FDialogSettings.Caption;

  //--- Set Ok, Cancel, Reset Button's Captions
  CustomizerForm.BtnOk.Caption := FDialogSettings.OkButtonCaption;
  CustomizerForm.BtnOk.Hint := FDialogSettings.OkButtonHint;
  CustomizerForm.BtnCancel.Caption := FDialogSettings.CancelButtonCaption;
  CustomizerForm.BtnCancel.Hint := FDialogSettings.CancelButtonHint;
  CustomizerForm.BtnReset.Caption := FDialogSettings.ResetButtonCaption;
  CustomizerForm.BtnReset.Hint := FDialogSettings.ResetButtonHint;

  //--- Set Glyph Position text
  CustomizerForm.CmBxGlphPos.Items[0]:=FDialogSettings.GlyphPositionLeftCaption;
  CustomizerForm.CmBxGlphPos.Items[1]:=FDialogSettings.GlyphPositionTopCaption;
  CustomizerForm.CmBxGlphPos.Items[2]:=FDialogSettings.GlyphPositionRightCaption;
  CustomizerForm.CmBxGlphPos.Items[3]:=FDialogSettings.GlyphPositionBottomCaption;

  //--- Set Components
  CustomizerForm.SetCaption(FDialogSettings.EditCaption);
  CustomizerForm.SetGlyphPosition(FDialogSettings.EditGlyphPosition);
  CustomizerForm.ChkLargeIcon.Visible := FDialogSettings.LargeIcon and Assigned(LargeImages);
  CustomizerForm.LoadComponents;

  CustomizerForm.CmBxIcon.Enabled := FDialogSettings.EditGlyph;

  CustomizerForm.TopButton.Visible := self.Options.ReOrder;
  CustomizerForm.BottomButton.Visible := self.Options.ReOrder;
  CustomizerForm.UpButton.Visible := self.Options.ReOrder;
  CustomizerForm.DownButton.Visible := self.Options.ReOrder;
  CustomizerForm.DeleteButton.Visible := self.Options.Delete;
  CustomizerForm.ClearButton.Visible := self.Options.DeleteAll;
  CustomizerForm.AddButton.Visible := Options.AddButton and (CustomizerForm.LstBxCommand.Items.Count > 0);
  CustomizerForm.SeparatorButton.Visible := Options.AddSeparator;
  CustomizerForm.AddGlowButton.Visible := Options.AddGlowButton;
  CustomizerForm.BtnEdit.Visible := Options.EditButton;

  if not CustomizerForm.TopButton.Visible then
    y := CustomizerForm.TopButton.Top
  else
    y := CustomizerForm.BottomButton.Top + CustomizerForm.BottomButton.Height;

  if CustomizerForm.AddButton.Visible then
  begin
    CustomizerForm.AddButton.Top := y;
    y := y + CustomizerForm.AddButton.Height;
  end;

  if CustomizerForm.AddGlowButton.Visible then
  begin
    CustomizerForm.AddGlowButton.Top := y;
    y := y + CustomizerForm.AddGlowButton.Height;
  end;

  if CustomizerForm.SeparatorButton.Visible then
  begin
    CustomizerForm.SeparatorButton.Top := y;
    y := y + CustomizerForm.SeparatorButton.Height;
  end;

  if CustomizerForm.DeleteButton.Visible then
  begin
    CustomizerForm.DeleteButton.Top := y;
    y := y + CustomizerForm.DeleteButton.Height;
  end;

  if CustomizerForm.ClearButton.Visible then
  begin
    CustomizerForm.ClearButton.Top := y;
    y := y + CustomizerForm.ClearButton.Height;
  end;

  if CustomizerForm.BtnEdit.Visible then
    CustomizerForm.BtnEdit.Top := y;

  if self.Options.ReOrder then
    CustomizerForm.LstBxToolBarItems.DragMode := dmAutomatic
  else
    CustomizerForm.LstBxToolBarItems.DragMode := dmManual;

  //CustomizerForm.Caption := self.FormCaption;

  //--- set display points
  pt := Point(FAdvToolBar.Left + FAdvToolBar.Width - 12, FAdvToolBar.Top + FAdvToolBar.Height + 1);
  spt := FAdvToolBar.Parent.ClientToScreen(pt);

{$IFNDEF TMSDOTNET}
  SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
{$ENDIF}
{$IFDEF TMSDOTNET}
  SystemParametersInfo(SPI_GETWORKAREA, 0, R, 0);
{$ENDIF}

  if R.Bottom < (spt.Y + CustomizerForm.Height + 2) then
    spt.Y := spt.Y - ((spt.Y + CustomizerForm.Height + 2) - R.Bottom);

  if (R.Right < spt.X + CustomizerForm.Width) then
  begin
    if FAdvToolBar.Position = daRight then
      spt.X := FAdvToolBar.ClientToScreen(Point(FAdvToolBar.Left - CustomizerForm.Width, FAdvToolBar.Top + FAdvToolBar.Height + 1)).X
    else
      spt.X := spt.X - ((spt.X + CustomizerForm.Width) - R.Right);
  end;

  CanShow := True;
  if Assigned(FOnCanShow) then
  begin
    FOnCanShow(Self, spt.x, spt.y, CanShow);
  end;

  if CanShow then
  begin
    CustomizerForm.Left := spt.X;
    CustomizerForm.Top := spt.Y;
    if Assigned(OnBeforeDisplay) then
      FOnBeforeDisplay(Self);

    i := CustomizerForm.ShowModal;
    if (i = mrOk) then
    begin
      // Apply Changes
      if CustomizerForm.Modified then
      begin
        UpdateAdvToolBar;
        if Assigned(OnAfterPost) then
          FOnAfterPost(Self);
      end;
    end
    else if (i = mrNoToAll) then
    begin
      ResetToolBar;
    end;
  end;  

  CustomizerForm.Free;
  CustomizerForm := nil;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.ResetToolBar;
var
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
  Section: String;
  N, CN: String;
  ATBItemCount, i, gp, LargeImg, j, k: Integer;
  ACtrl: TControl;
  AllItems: TDbgList;
  SL: TStrings;

begin
  if (EnablePersistence) and (FileName <>'') and not (csDesigning in ComponentState) then
  begin
    Section := Name + 'Org';
    IniFile := TIniFile(TIniFile.Create(FileName));
    with IniFile do
    begin
      AdvToolBar.Caption := ReadString(Section, 'ATBCaption', AdvToolBar.Caption);
      gp := ReadInteger(Section, 'GlyphPosition', 0);
      LargeImg := ReadInteger(Section, 'LargeIcon', 0);

      ATBItemCount:= ReadInteger(Section,'ToolBarItemCount', 0);

      if (ATBItemCount > 0) then
      begin
        for i:= 0 to FDeleteItems.Count -1 do
          TControl(FDeleteItems[i]).Parent := AdvToolBar;
        FDeleteItems.Clear;

        AllItems := TDbgList.Create;
        for i:= 0 to ATBItemCount-1 do
        begin
          N := ReadString(Section, 'Name'+inttostr(i), '');
          CN := ReadString(Section, 'Name'+inttostr(i)+'.ClassName', '');
          if (CN <> '') then
          begin
            ACtrl := GetCtrl(N);
            if (ACtrl <> nil) and (ACtrl is TAdvToolBarButton) then
            begin
              TAdvToolBarButton(ACtrl).ImageIndex := ReadInteger(Section, 'Name'+inttostr(i)+'.ImageIndex', TAdvToolBarButton(ACtrl).ImageIndex);
              TAdvToolBarButton(ACtrl).Visible := Bool(ReadInteger(Section, 'Name'+inttostr(i)+'.Visible', Integer(TAdvToolBarButton(ACtrl).Visible)));
              TAdvToolBarButton(ACtrl).ShowCaption := ReadInteger(Section, 'Name'+inttostr(i)+'.ShowCaption', Integer(TAdvToolBarButton(ACtrl).ShowCaption)) = 1;
              TAdvToolBarButton(ACtrl).Caption := ReadString(Section, 'Name'+inttostr(i)+'.Caption', TAdvToolBarButton(ACtrl).Caption);
              TAdvToolBarButton(ACtrl).Hint := ReadString(Section, 'Name'+inttostr(i)+'.Hint', TAdvToolBarButton(ACtrl).Hint);
            end;

            if (ACtrl <> nil) then
              AllItems.Add(ACtrl);

          end;
        end;

        for i:= 0 to AllItems.Count -1 do
        begin
          if (i < AdvToolBar.ToolBarControlCount) then
          begin
            if FDialogSettings.EditGlyphPosition and (TControl(AllItems[i]) is TAdvToolBarButton) then
              (TControl(AllItems[i]) as TAdvToolBarButton).GlyphPosition := TGlyphPosition(gp);
            j := AdvToolBar.IndexOfToolBarControl(AllItems[i]);
            if (j >= 0) and (j <> i) then
              AdvToolBar.MoveToolBarControl(j, i);
          end;
        end;

        i:= AllItems.Count;
        k := i;
        j := AdvToolBar.ToolBarControlCount;
        while (i < j) do
        begin
          if (k < AdvToolBar.ToolBarControlCount) then
          begin
            ACtrl := TControl(AdvToolBar.ToolBarControls[k]);
            ACtrl.Parent := nil;
            ACtrl.Free;
          end;
          Inc(i);
        end;
        AllItems.Free;
      end;

      if (LargeImg = 1) and Assigned(LargeImages) then
        AdvToolBar.Images := LargeImages
      else if Assigned(SmallImages) then
        AdvToolBar.Images := SmallImages;

      //--- Delete here
      SL := TStringList.Create;
      IniFile.ReadSectionValues(Name, SL);
      for i:= 0 to SL.Count-1 do
        IniFile.DeleteKey(Name, SL.Names[i]);
      SL.Free;
    end;
    IniFile.Free;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.SaveInitialState;
var
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
  i, j: Integer;
  Section: String;
begin
  if (EnablePersistence) and (FileName <>'') and not (csDesigning in ComponentState) then
  begin
    Section := Name + 'Org';
    IniFile := TIniFile(TIniFile.Create(FileName));
    with IniFile do
    begin
      WriteString(Section, 'ATBCaption', AdvToolBar.Caption);
      j := 0;
      for I := 0 to AdvToolBar.ToolBarControlCount-1 do
      begin
        if TControl(AdvToolBar.ToolBarControls[i]) is TAdvToolBarButton then
        begin
          j := integer(TAdvToolBarButton(AdvToolBar.ToolBarControls[i]).GlyphPosition);
          Break;
        end
      end;
      WriteInteger(Section, 'GlyphPosition', j);
      WriteInteger(Section, 'LargeIcon', integer(AdvToolBar.Images = LargeImages));

      WriteInteger(Section, 'ToolBarItemCount', AdvToolBar.ToolBarControlCount);

      for I := 0 to AdvToolBar.ToolBarControlCount-1 do
      begin
        if TControl(AdvToolBar.ToolBarControls[i]) is TAdvToolBarButton then
        begin
          WriteString(Section, 'Name'+ inttostr(i), TAdvToolBarButton(AdvToolBar.ToolBarControls[i]).Name);
          WriteString(Section, 'Name'+ inttostr(i)+'.ClassName', 'ADVTOOLBARBUTTON');
          WriteInteger(Section, 'Name'+ inttostr(i)+'.ImageIndex', TAdvToolBarButton(AdvToolBar.ToolBarControls[i]).ImageIndex);
          WriteInteger(Section, 'Name'+ inttostr(i)+'.Visible', Integer(TAdvToolBarButton(AdvToolBar.ToolBarControls[i]).Visible));
          WriteInteger(Section, 'Name'+ inttostr(i)+'.ShowCaption', Integer(TAdvToolBarButton(AdvToolBar.ToolBarControls[i]).ShowCaption));
          WriteString(Section, 'Name'+ inttostr(i)+'.Caption', TAdvToolBarButton(AdvToolBar.ToolBarControls[i]).Caption);
          WriteString(Section, 'Name'+ inttostr(i)+'.Hint', TAdvToolBarButton(AdvToolBar.ToolBarControls[i]).Hint);
        end
        else if TControl(AdvToolBar.ToolBarControls[i]) is TAdvToolBarSeparator then
        begin
          WriteString(Section, 'Name'+ inttostr(i), TAdvToolBarSeparator(AdvToolBar.ToolBarControls[i]).Name);
          WriteString(Section, 'Name'+ inttostr(i)+'.ClassName', 'ADVTOOLBARSEPARATOR');
        end
        else if TControl(AdvToolBar.ToolBarControls[i]) is TAdvCustomGlowButton then
        begin
          WriteString(Section, 'Name'+ inttostr(i), TAdvCustomGlowButton(AdvToolBar.ToolBarControls[i]).Name);
          WriteString(Section, 'Name'+ inttostr(i)+'.ClassName', 'ADVCUSTOMGLOWBUTTON');
          WriteInteger(Section, 'Name'+ inttostr(i)+'.ImageIndex', TAdvCustomGlowButton(AdvToolBar.ToolBarControls[i]).ImageIndex);
          WriteInteger(Section, 'Name'+ inttostr(i)+'.Visible', Integer(TAdvCustomGlowButton(AdvToolBar.ToolBarControls[i]).Visible));
          WriteInteger(Section, 'Name'+ inttostr(i)+'.ShowCaption', Integer(TAdvCustomGlowButton(AdvToolBar.ToolBarControls[i]).ShowCaption));
          WriteString(Section, 'Name'+ inttostr(i)+'.Caption', TAdvCustomGlowButton(AdvToolBar.ToolBarControls[i]).Caption);
          WriteString(Section, 'Name'+ inttostr(i)+'.Hint', TAdvCustomGlowButton(AdvToolBar.ToolBarControls[i]).Hint);
        end
        else
        begin
          WriteString(Section, 'Name'+ inttostr(i), TControl(AdvToolBar.ToolBarControls[i]).Name);
          WriteString(Section, 'Name'+ inttostr(i)+'.ClassName', '-1');
        end;
      end;
    end;
    IniFile.Free;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolbarCustomizer.GetCtrl(CtrlName: String): TControl;
var
  i: Integer;
begin
  Result := nil;
  if (CtrlName = '') then
    Exit;
  for i:= 0 to AdvToolBar.ToolBarControlCount-1 do
  begin
    if UpperCase(CtrlName) = UpperCase(AdvToolBar.ToolBarControls[i].Name) then
    begin
      Result := AdvToolBar.ToolBarControls[i];
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolbarCustomizer.UpdateAdvToolBar;
var
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
  N, CN: String;
  ATBItemCount, i, gp, LargeImg, j, CID, k: Integer;
  ACtrl: TControl;
  ATBButton: TAdvToolBarButton;
  ATBSeparator: TAdvToolBarSeparator;
  GlowButton: TAdvGlowButton;
  AllItems: TDbgList;
  //AItem: TATBItemProp;

begin

  if (EnablePersistence) and (FileName <>'') and not (csDesigning in ComponentState) then
  begin
    IniFile := TIniFile(TIniFile.Create(FileName));

    with IniFile do
    begin
      if FDialogSettings.EditCaption then
        AdvToolBar.Caption := ReadString(Name {Section}, 'ATBCaption', AdvToolBar.Caption);
      gp := 0;
      if FDialogSettings.EditGlyphPosition then
        gp := ReadInteger(Name {Section}, 'GlyphPosition', 0);

      LargeImg := 0;
      if FDialogSettings.LargeIcon and Assigned(LargeImages) then
        LargeImg := ReadInteger(Name {Section}, 'LargeIcon', 0);

      ATBItemCount:= ReadInteger(Name,'ToolBarItemCount', -1{0});

      if (ATBItemCount > 0) then
      begin
        AllItems := TDbgList.Create;
        for i:= 0 to ATBItemCount-1 do
        begin
          N := ReadString(Name, 'Name'+inttostr(i), '');
          CN := ReadString(Name, 'Name'+inttostr(i)+'.ClassName', '');
          if {(N <> '') and }(CN <> '') then
          begin
            ACtrl := GetCtrl(N);
            if (ACtrl = nil) then
            begin
              if (UpperCase(CN) = 'ADVTOOLBARBUTTON') then
              begin
                ATBButton := TAdvToolBarButton.Create(AdvToolBar);
                ATBButton.Parent := AdvToolBar;
                ATBButton.Name := N;
                ATBButton.FCustomizerCreated := True;
                CID := ReadInteger(Name, 'Name'+inttostr(i)+'.CommandID', -1);
                if (CID >= 0) and (CID < Commands.Count) then
                begin
                  ATBButton.OnClick := Commands.Items[CID].OnExecute;
                  ATBButton.Action := Commands.Items[CID].Action;
                  ATBButton.FCommandID := CID;
                end;
                //AdvToolBar.MoveToolBarControl(AdvToolBar.IndexOfToolBarControl(ATBButton), i);
                ACtrl := ATBButton;
              end
              else if (UpperCase(CN) = 'ADVTOOLBARSEPARATOR') then
              begin
                ATBSeparator := TAdvToolBarSeparator.Create(AdvToolBar);
                ATBSeparator.Parent := AdvToolBar;
                ATBSeparator.Name := N;
                //AdvToolBar.MoveToolBarControl(AdvToolBar.IndexOfToolBarControl(ATBSeparator), i);
                ACtrl := ATBSeparator;
              end
              else if (UpperCase(CN) = 'ADVCUSTOMGLOWBUTTON') then
              begin
                GlowButton := TAdvGlowButton.Create(AdvToolBar);
                GlowButton.Parent := AdvToolBar;
                GlowButton.Name := N;
                TProCustomGlowButton(GlowButton).FCustomizerCreated := True;
                if (AdvToolBar.Images is TImageList) then
                  GlowButton.Images := TImageList(AdvToolBar.Images);
                GlowButton.Width := 23;
                GlowButton.Height := 22;
                GlowButton.AutoSize := True;
                CID := ReadInteger(Name, 'Name'+inttostr(i)+'.CommandID', -1);
                if (CID >= 0) and (CID < Commands.Count) then
                begin
                  GlowButton.OnClick := Commands.Items[CID].OnExecute;
                  GlowButton.Action := Commands.Items[CID].Action;
                  TProCustomGlowButton(GlowButton).FCommandID := CID;
                end;
                ACtrl := GlowButton;
              end;
            end;

            if (ACtrl <> nil) and (ACtrl is TAdvToolBarButton) then
            begin
              if ButtonProperties.Glyph then
              begin
                TAdvToolBarButton(ACtrl).ImageIndex := ReadInteger(Name, 'Name'+inttostr(i)+'.ImageIndex', TAdvToolBarButton(ACtrl).ImageIndex);
                TAdvToolBarButton(ACtrl).ForceImageIndex := Bool(ReadInteger(Name, 'Name'+inttostr(i)+'.ForceImageIndex', Integer(TAdvToolBarButton(ACtrl).ForceImageIndex)));
              end;
              if ButtonProperties.Visible then
                TAdvToolBarButton(ACtrl).Visible := Bool(ReadInteger(Name, 'Name'+inttostr(i)+'.Visible', Integer(TAdvToolBarButton(ACtrl).Visible)));
              if ButtonProperties.ShowCaption then
                TAdvToolBarButton(ACtrl).ShowCaption := ReadInteger(Name, 'Name'+inttostr(i)+'.ShowCaption', Integer(TAdvToolBarButton(ACtrl).ShowCaption)) = 1;
              if ButtonProperties.Caption then
                TAdvToolBarButton(ACtrl).Caption := ReadString(Name, 'Name'+inttostr(i)+'.Caption', TAdvToolBarButton(ACtrl).Caption);
              if ButtonProperties.Hint then
                TAdvToolBarButton(ACtrl).Hint := ReadString(Name, 'Name'+inttostr(i)+'.Hint', TAdvToolBarButton(ACtrl).Hint);
            end;

            if (ACtrl <> nil) and (ACtrl is TAdvCustomGlowButton) then
            begin
              if ButtonProperties.Glyph and TProCustomGlowButton(ACtrl).FCustomizerCreated then
              begin
                TAdvCustomGlowButton(ACtrl).ImageIndex := ReadInteger(Name, 'Name'+inttostr(i)+'.ImageIndex', TAdvCustomGlowButton(ACtrl).ImageIndex);                
                //TAdvToolBarButton(ACtrl).ForceImageIndex := Bool(ReadInteger(Name, 'Name'+inttostr(i)+'.ForceImageIndex', Integer(TAdvToolBarButton(ACtrl).ForceImageIndex)));
              end;
              if ButtonProperties.Visible then
                TAdvCustomGlowButton(ACtrl).Visible := Bool(ReadInteger(Name, 'Name'+inttostr(i)+'.Visible', Integer(TAdvCustomGlowButton(ACtrl).Visible)));
              if ButtonProperties.ShowCaption then
                TAdvCustomGlowButton(ACtrl).ShowCaption := ReadInteger(Name, 'Name'+inttostr(i)+'.ShowCaption', Integer(TAdvCustomGlowButton(ACtrl).ShowCaption)) = 1;
              if ButtonProperties.Caption then
                TAdvCustomGlowButton(ACtrl).Caption := ReadString(Name, 'Name'+inttostr(i)+'.Caption', TAdvCustomGlowButton(ACtrl).Caption);
              if ButtonProperties.Hint then
                TAdvCustomGlowButton(ACtrl).Hint := ReadString(Name, 'Name'+inttostr(i)+'.Hint', TAdvCustomGlowButton(ACtrl).Hint);
            end;

            if (ACtrl <> nil) then
              AllItems.Add(ACtrl);

          end;
        end;

        for i:= 0 to AllItems.Count -1 do
        begin
          if (i < AdvToolBar.ToolBarControlCount) then
          begin
            if FDialogSettings.EditGlyphPosition then
            begin
              if (TControl(AllItems[i]) is TAdvToolBarButton) then
              begin
                (TControl(AllItems[i]) as TAdvToolBarButton).GlyphPosition := TGlyphPosition(gp);
              end
              else if (TControl(AllItems[i]) is TAdvCustomGlowButton) then
              begin
                case TGlyphPosition(gp) of
                  gpLeft: (TControl(AllItems[i]) as TAdvGlowButton).Layout := blGlyphLeft;
                  gpTop: (TControl(AllItems[i]) as TAdvGlowButton).Layout := blGlyphTop;
                  gpRight: (TControl(AllItems[i]) as TAdvGlowButton).Layout := blGlyphRight;
                  gpBottom: (TControl(AllItems[i]) as TAdvGlowButton).Layout := blGlyphBottom;
                end;
              end;
            end;
            j := AdvToolBar.IndexOfToolBarControl(AllItems[i]);
            if (j >= 0) and (j <> i) then
              AdvToolBar.MoveToolBarControl(j, i);
          end;
        end;

       { i:= AllItems.Count;
        while i < AdvToolBar.ToolBarControlCount do
        begin
          FDeleteItems.Add(AdvToolBar.ToolBarControls[i]);
          TControl(AdvToolBar.ToolBarControls[i]).Parent := nil;
          Inc(i);
        end; }
        i:= AllItems.Count;
        k := i;
        j := AdvToolBar.ToolBarControlCount;
        while (i < j) do
        begin
          if (k < AdvToolBar.ToolBarControlCount) then
          begin
            FDeleteItems.Add(AdvToolBar.ToolBarControls[k]);
            TControl(AdvToolBar.ToolBarControls[k]).Parent := nil;
          end;
          Inc(i);
        end;
        AllItems.Free;
      end
      else if (ATBItemCount = 0) then
      begin
        for i := 0 to AdvToolBar.ToolBarControlCount -1 do
        begin
          FDeleteItems.Add(AdvToolBar.ToolBarControls[0]);
          TControl(AdvToolBar.ToolBarControls[0]).Parent := nil;
        end;
      end;

      if (LargeImg = 1) and Assigned(LargeImages) then
        AdvToolBar.Images := LargeImages
      else if Assigned(SmallImages) then
        AdvToolBar.Images := SmallImages;
    end;
    IniFile.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarCustomizer.SetSmallImages(
  const Value: TCustomImageList);
begin
  FSmallImages := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarCustomizer.SetDialogSettings(
  const Value: TDialogSettings);
begin
  FDialogSettings.Assign(Value);
end;

//------------------------------------------------------------------------------

{ TAdvToolBarWindow }

constructor TAdvToolBarWindow.Create(AOwner: TComponent);
begin
  inherited;
  FOwner := AOwner;
  FBorderWidth := 2;
  FBorderColor := clGray;
  Color := clSilver;
  FColorTo := clWhite;
  FGradientDirection := gdVertical;
  FCaptionColorTo := clNone;
  FCaptionColor := clBlue;
end;

//------------------------------------------------------------------------------

constructor TAdvToolBarWindow.CreateNew(AOwner: TComponent;
  Dummy: Integer);
begin
  inherited;
  FOwner := AOwner;
  FBorderWidth := 2;
  FBorderColor := clGray;
  Color := clSilver;
  FColorTo := clWhite;
  FGradientDirection := gdVertical;
  FCaptionColorTo := clNone;
  FCaptionColor := clBlue;
end;

//------------------------------------------------------------------------------

destructor TAdvToolBarWindow.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarWindow.Paint;
var
  R, CapR: TRect;
begin
  inherited;
  R := ClientRect;
  if (ColorTo <> clNone) then
    DrawGradient(Canvas, Color, ColorTo, 80, R, GradientDirection = gdHorizontal);

  CapR := Rect(R.Left, R.Top, R.Right, R.Top + DEFAULT_CAPTIONHEIGHT);
  if (FCaptionColor <> clNone) and (FCaptionColorTo <> clNone) then
    DrawGradient(Canvas, FCaptionColor, FCaptionColorTo, 80, CapR, true)
  else
  begin
    Canvas.Brush.Color := FCaptionColor;
    Canvas.FillRect(CapR);
  end;

end;

//------------------------------------------------------------------------------

{ TCustomizeOption }

procedure TCustomizeOption.UpDateSize;
begin
  Height := Default_ItemHeight + 5;
  Width := Canvas.TextWidth(FCustomizeText) + FMarginX*2 + 6*2;
end;

//------------------------------------------------------------------------------

constructor TCustomizeOption.Create(AOwner: TComponent);
begin
  inherited;
  FOwner := AOwner;
  FCustomizeText := 'Customize';
end;

//------------------------------------------------------------------------------

function TCustomizeOption.GetCustomizeBtnRect: TRect;
begin
  Result := Rect(MarginX, MarginY, Width - MarginX, Height - MarginY);
end;

//------------------------------------------------------------------------------

procedure TCustomizeOption.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  if PtInRect(GetCustomizeBtnRect, Point(X, Y)) then
  begin
    if not FCustomizeBtnHot and not (ssLeft in Shift) then
    begin
      FCustomizeBtnHot := True;
      FCustomizeBtnDown := True;
      Invalidate;
    end;
  end
  else if FCustomizeBtnHot then
  begin
    FCustomizeBtnHot := False;
    FCustomizeBtnDown := False;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizeOption.MouseUp(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  if FCustomizeBtnDown and PtInRect(GetCustomizeBtnRect, Point(X, Y)) then
  begin
    FCustomizeBtnHot := False;
    FCustomizeBtnDown := False;
    Invalidate;
    if (FOwner is TOptionSelectorWindow) then
      TOptionSelectorWindow(FOwner).Hide;
    if Assigned(AdvToolBar) then
      AdvToolBar.ShowCustomizer;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizeOption.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  if PtInRect(GetCustomizeBtnRect, Point(X, Y)) then
  begin
    if not FCustomizeBtnDown then
    begin
      FCustomizeBtnHot := True;
      FCustomizeBtnDown := True;
      Invalidate;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizeOption.CMMouseLeave(var Message: TMessage);
begin
  inherited;

  if FCustomizeBtnHot or FCustomizeBtnDown then
  begin
    FCustomizeBtnHot := False;
    FCustomizeBtnDown := False;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomizeOption.Paint;
var
  TextR: TRect;
  Clr, ClrTo, BrClr: TColor;
begin
  inherited;

  if Assigned(AdvToolBar) then
  begin
    with Canvas do
    begin
      if FCustomizeBtnDown then
      begin
        if Assigned(AdvToolBar.FMenu) and Assigned(AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler) then
        begin
          Clr := AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.SelectedColor;
          ClrTo := AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.SelectedColorTo;
          Font.Color := AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.SelectedTextColor;
        end
        else
        begin
          Clr := AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.ColorDown;
          ClrTo := AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.ColorDownTo;
          Font.Color := AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.CaptionTextColorDown;
        end;
        brClr := clBlack;
      end
      else if FCustomizeBtnHot then
      begin
        if Assigned(AdvToolBar.FMenu) and Assigned(AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler) then
        begin
          Clr := AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.HoverColor;
          ClrTo := AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.HoverColorTo;
          Font.Color := AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.HoverTextColor;
        end
        else
        begin
          Clr := AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.ColorHot;
          ClrTo := AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.ColorHotTo;
          Font.Color := AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.CaptionTextColorHot;
        end;
        brClr := clBlack;
      end
      else
      begin
        if Assigned(AdvToolBar.FMenu) and Assigned(AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler) then
        begin
          Clr := clNone; //AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.Color;
          ClrTo := clNone; //AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.ColorTo;
          Font.Color := AdvToolBar.FCurrentToolBarStyler.AdvMenuStyler.RootItem.SelectedTextColor;
        end
        else
        begin
          Clr := clNone; //AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.Color;
          ClrTo := clNone; //AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.ColorTo;
          Font.Color := AdvToolBar.FCurrentToolBarStyler.ButtonAppearance.CaptionTextColor;
        end;
        brClr := clBlack;
      end;

      if (Clr <> clNone) and (ClrTo <> clNone) then
      begin
        DrawGradient(Self.Canvas, Clr, ClrTo, 40, GetCustomizeBtnRect, False);
        Brush.Style := bsClear;
        Pen.Color := BrClr;
        Rectangle(GetCustomizeBtnRect);
      end
      else if (Clr <> clNone) then
      begin
        Brush.Color := Clr;
        Rectangle(GetCustomizeBtnRect);
      end;

      TextR := GetCustomizeBtnRect;
      TextR.Left := TextR.Left +4;
      TextR.Right := TextR.Right - 4;
      Canvas.Brush.Style := bsClear;
      DrawText(Self.Canvas.Handle, PChar(FCustomizeText), -1, TextR, DT_SINGLELINE or DT_VCENTER or DT_CENTER);
    end;
  end;
end;

//------------------------------------------------------------------------------

{ TATBButtonProp }

constructor TATBItemProp.Create;
begin
  inherited;
  FImageIndex := -1;
  FCaption := '';
  FHint := '';
  FVisible := True;
  FID := '';
  FCommandID := -1;
  FForceImageIndex := False;
  FIsGlowButton := False;
end;

//------------------------------------------------------------------------------

destructor TATBItemProp.Destroy;
begin

  inherited;
end;

//------------------------------------------------------------------------------

procedure TATBItemProp.SetIsATBButton(const Value: Boolean);
begin
  FIsATBButton := Value;
end;

//------------------------------------------------------------------------------

procedure TATBItemProp.SetIsSeparator(const Value: Boolean);
begin
  FIsSeparator := Value;
end;

//------------------------------------------------------------------------------

{ TDialogSettings }

procedure TDialogSettings.Assign(Source: TPersistent);
begin
  if (Source is TDialogSettings) then
  begin
    FEditCaption := (Source as TDialogSettings).EditCaption;
    FLargeIcon := (Source as TDialogSettings).LargeIcon;
    FEditGlyphPosition := (Source as TDialogSettings).EditGlyphPosition;
    FUpHint := (Source as TDialogSettings).UpHint;
    FButtonEditCaptionLabel := (Source as TDialogSettings).ButtonEditCaptionLabel;
    FTopHint := (Source as TDialogSettings).TopHint;
    FButtonEditIconLabel := (Source as TDialogSettings).ButtonEditIconLabel;
    FToolBarLabel := (Source as TDialogSettings).ToolBarLabel;
    FDeleteHint := (Source as TDialogSettings).DeleteHint;
    FEditHint := (Source as TDialogSettings).EditHint;
    FCaptionLabel := (Source as TDialogSettings).CaptionLabel;
    FGlyphPosLabel := (Source as TDialogSettings).GlyphPosLabel;
    FCommandLabel := (Source as TDialogSettings).CommandLabel;
    FButtonEditVisibleCheck := (Source as TDialogSettings).ButtonEditVisibleCheck;
    FButtonEditCaptionCheck := (Source as TDialogSettings).ButtonEditCaptionCheck;
    FButtonEditHintLabel := (Source as TDialogSettings).ButtonEditHintLabel;
    FAddHint := (Source as TDialogSettings).AddHint;
    FAddSeparatorHint := (Source as TDialogSettings).AddSeparatorHint;
    FDeleteAllHint := (Source as TDialogSettings).DeleteAllHint;
    FBottomHint := (Source as TDialogSettings).BottomHint;
    FDownHint := (Source as TDialogSettings).DownHint;
    FCaption := (Source as TDialogSettings).Caption;
    FLargeIconCheck := (Source as TDialogSettings).LargeIconCheck;
    FButtonEditCaption := (Source as TDialogSettings).ButtonEditCaption;
    FResetButtonCaption := (Source as TDialogSettings).FResetButtonCaption;
    FOKButtonCaption := (Source as TDialogSettings).FOKButtonCaption;
    FCancelButtonCaption := (Source as TDialogSettings).FCancelButtonCaption;
    FEditGlyph := (Source as TDialogSettings).EditGlyph;
    FEditGlyphVisible := (Source as TDialogSettings).EditGlyphVisible;

    FOKButtonHint := (Source as TDialogSettings).OKButtonHint;
    FCancelButtonHint := (Source as TDialogSettings).CancelButtonHint;
    FResetButtonHint := (Source as TDialogSettings).ResetButtonHint;
    FAddGlowButtonHint := (Source as TDialogSettings).AddGlowButtonHint;
    FGlyphPositionLeftCaption:= (Source as TDialogSettings).GlyphPositionLeftCaption;
    FGlyphPositionTopCaption:= (Source as TDialogSettings).GlyphPositionTopCaption;
    FGlyphPositionRightCaption:= (Source as TDialogSettings).GlyphPositionRightCaption;
    FGlyphPositionBottomCaption:= (Source as TDialogSettings).GlyphPositionBottomCaption;
    GlyphEditNoneIconCaption := (Source as TDialogSettings).GlyphEditNoneIconCaption;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TDialogSettings.Change;
begin

end;

//------------------------------------------------------------------------------

constructor TDialogSettings.Create;
begin
  inherited Create;
  FEditGlyph := True;
  FEditGlyphVisible := True;
  FEditCaption := True;
  FLargeIcon := False;
  FEditGlyphPosition := True;
  FUpHint := 'Move Up';
  FButtonEditCaptionLabel := 'Caption';
  FTopHint := 'Move to Top';
  FButtonEditIconLabel := 'Icon';
  FToolBarLabel := 'ToolBar Items:';
  FDeleteHint := 'Delete Item';
  FEditHint := 'Edit Item';
  FCaptionLabel := 'Caption';
  FGlyphPosLabel := 'Glyph Position';
  FCommandLabel := 'Commands';
  FButtonEditVisibleCheck := 'Visible';
  FButtonEditCaptionCheck := 'Show Caption';
  FButtonEditHintLabel := 'Hint';
  FAddHint := 'Add Item';
  FAddSeparatorHint := 'Add Separator';
  FDeleteAllHint := 'Delete All';
  FBottomHint := 'Move to Bottom';
  FDownHint := 'Move Down';
  FCaption := 'Customizer';
  FLargeIconCheck := 'Large Icon';
  FButtonEditCaption := 'Customize Button';
  FOnChange := nil;
  FCustomize := 'Customize';
  FResetButtonCaption := '&Reset';
  FOKButtonCaption := '&Ok';
  FCancelButtonCaption := '&Cancel';

  FOKButtonHint := '';
  FCancelButtonHint := '';
  FResetButtonHint := '';
  FAddGlowButtonHint := 'Insert GlowButton';
  FGlyphPositionLeftCaption := 'Left';
  FGlyphPositionTopCaption := 'Top';
  FGlyphPositionRightCaption := 'Right';
  FGlyphPositionBottomCaption := 'Bottom';
  FGlyphEditNoneIconCaption := 'None';
end;

//------------------------------------------------------------------------------

destructor TDialogSettings.Destroy;
begin
  inherited;
end;

//------------------------------------------------------------------------------

{TWinCtrl}

procedure TWinCtrl.PaintCtrls(DC: HDC; First: TControl);
begin
  PaintControls(DC, First);
end;

//------------------------------------------------------------------------------

{ TAdvToolBarContainer }

constructor TAdvToolBarContainer.Create(AOwner: TComponent);
begin
  inherited;
  ControlStyle := ControlStyle + [csAcceptsControls] - [csOpaque];
  DoubleBuffered := True;
  FParentStyler := True;
  FLine3D := True;
  FCaption := '';
  FLineColor := clBtnShadow;
  FColor := TGradientBackground.Create;
  FColor.OnChange := OnColorChange;
  FMargin := 2;
  FOfficeHint := TAdvHintInfo.Create;
end;

//------------------------------------------------------------------------------

destructor TAdvToolBarContainer.Destroy;
begin
  FColor.Free;
  FOfficeHint.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.UpdateAllGlowButtons;
var
  I: Integer;
  tmsif: ITMSStyle;
begin
  if Assigned(AdvToolBar) and Assigned(AdvToolBar.FCurrentToolBarStyler) then
  begin
    for i := 0 to ControlCount - 1 do
    begin
      if (TControl(Controls[i]) is TAdvGlowButton) then
          TAdvGlowButton(Controls[i]).Appearance.Assign(AdvToolBar.FCurrentToolBarStyler.GlowButtonAppearance);

      if (AdvToolBar.FCurrentToolBarStyler.GetInterface(ITMSStyle, tmsif)) and (AdvToolBar.FCurrentToolBarStyler.TMSStyle <> tsCustom) then
      begin
        if (TControl(Controls[i]).GetInterface(ITMSStyle, tmsif)) then
           tmsif.SetComponentStyle(AdvToolBar.FCurrentToolBarStyler.TMSStyle);
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.Loaded;
begin
  inherited;
  UpdateAllGlowButtons;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.OnColorChange(Sender: TObject);
begin
  inherited Color := Color.Color;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.Paint;
var
  {HorzGradient: boolean;
  GSteps: Integer;
  GColorFrom: TColor;
  GColorTo, }
  LnClr: TColor;
  ShowLn3D: Boolean;
  R, CapR: TRect;
  i: Integer;
  P: TPoint;
  bmp: TBitmap;

 { procedure SetGradientColors;
  var
    bmp: TBitMap;
    i: Integer;
    R: TRect;
  begin
    if Assigned(AdvToolBar) and Assigned(AdvToolBar.FCurrentToolBarStyler) and ParentStyler then
    begin
      bmp := TBitMap.Create;
      bmp.Width := Self.Left + Self.Width + 10;
      bmp.Height := Self.Top + Self.Height + 10;

      i := AdvToolBar.FCurrentToolBarStyler.Color.Steps;
      GColorFrom := AdvToolBar.FCurrentToolBarStyler.Color.Color;
      GColorTo := AdvToolBar.FCurrentToolBarStyler.Color.ColorTo;

      if AdvToolBar.FullSize then
      begin
        i := 256;
        GColorFrom := AdvToolBar.FCurrentToolBarStyler.DockColor.Color;
        GColorTo := AdvToolBar.FCurrentToolBarStyler.DockColor.ColorTo;

        if (AdvToolBar.ToolBarState = tsFloating) then
        begin
          GColorTo := AdvToolBar.FCurrentToolBarStyler.DockColor.Color;
          GColorFrom := AdvToolBar.FCurrentToolBarStyler.DockColor.Color;
        end;
      end;

      R := Rect(0, 0, bmp.Width, bmp.Height);
      DrawGradient(bmp.Canvas, GColorFrom, GColorTo, i, R, HorzGradient);
      GColorFrom := bmp.Canvas.Pixels[Left, Top];
      GColorTo := bmp.Canvas.Pixels[Left + Width, Top + Height];

      bmp.Free;
    end;
  end; }

begin
  inherited;
  
  // TRANSPARENCY CODE
  R := ClientRect;

  bmp := TBitmap.Create;
  bmp.Width := Left + (R.Right - R.Left);
  bmp.Height := Top + (R.Bottom - R.Top);

  i := SaveDC(bmp.Canvas.Handle);
  p := ClientOrigin;
  Windows.ScreenToClient(Parent.Handle, p);
  p.x := -p.x;
  p.y := -p.y;
  MoveWindowOrg(bmp.Canvas.Handle, p.x, p.y);

  SendMessage(Parent.Handle, WM_ERASEBKGND, bmp.Canvas.Handle, 0);
  // transparency ?
  SendMessage(Parent.Handle, WM_PAINT, bmp.Canvas.Handle, 0);

  if (Parent is TWinCtrl) then
    (Parent as TWinCtrl).PaintCtrls(bmp.Canvas.Handle, nil);

  RestoreDC(bmp.Canvas.Handle, i);

  Canvas.Draw(-Left, -Top, bmp);
  bmp.Free;
  R := ClientRect;
  {
  HorzGradient := Color.Direction = gdHorizontal;
  GSteps := Color.Steps;
  GColorFrom := Color.Color;
  GColorTo := Color.ColorTo;

  if Assigned(AdvToolBar) and ParentStyler then
  begin
    HorzGradient := AdvToolBar.FCurrentToolBarStyler.Color.Direction = gdHorizontal;
    if (AdvToolBar.Position in [daLeft, daRight]) then
      HorzGradient := not HorzGradient;

    if AdvToolBar.FullSize then
      HorzGradient := not HorzGradient;

    GColorFrom := clNone;//AdvToolBar.Canvas.Pixels[Left - 1, Top - 1];
    GColorTo := clNone; //AdvToolBar.Canvas.Pixels[Left + Width + 1, Top + Height];

    if (GColorFrom = clNone) or (GColorTo = clNone) then
      SetGradientColors;
  end;

  if (GColorTo <> clNone) and (GColorFrom <> clNone) then
    DrawGradient(Canvas, GColorFrom, GColorTo, GSteps, R, HorzGradient)
  else
  begin
    Canvas.Pen.Color := GColorFrom;
    Canvas.Brush.Color := GColorFrom;
    Canvas.Rectangle(R);
  end;  }

  ShowLn3D := Line3D;
  LnClr := LineColor;

  if Assigned(AdvToolBar) and ParentStyler and Assigned(AdvToolBar.FCurrentToolBarStyler) then
  begin
    ShowLn3D := AdvToolBar.FCurrentToolBarStyler.ContainerAppearance.Line3D;
    LnClr := AdvToolBar.FCurrentToolBarStyler.ContainerAppearance.LineColor;
  end;
  
  if (LnClr <> clNone) then
  begin
    if ShowLn3D then
    begin
      Canvas.Brush.Style := bsClear;
      if (Caption <> '') then
      begin
        CapR := R;
        CapR.Left := CapR.Left + 10;
        Canvas.Font.Color := clBlack;
        DrawText(Canvas.Handle, PChar(Caption), -1, CapR, DT_SINGLELINE or DT_Top);
        DrawText(Canvas.Handle, PChar(Caption), -1, CapR, DT_SINGLELINE or DT_Top or DT_CALCRECT);
        Canvas.Pen.Color := LnClr;
        Canvas.MoveTo(R.Left{ + FMargin}, R.Top + FMargin + 2);
        Canvas.LineTo(R.Left{ + FMargin} + 9, R.Top + FMargin + 2);
        Canvas.MoveTo(R.Left + CapR.Right + 1, R.Top + FMargin + 2);
        Canvas.LineTo(R.Right - FMargin, R.Top + FMargin + 2);
        Canvas.Pen.Color := clWhite;
        Canvas.MoveTo(R.Left{ + FMargin}, R.Top + FMargin + 3);
        Canvas.LineTo(R.Left{ + FMargin} + 9, R.Top + FMargin + 3);
        Canvas.MoveTo(R.Left + CapR.Right + 1, R.Top + FMargin + 3);
        Canvas.LineTo(R.Right - FMargin, R.Top + FMargin + 3);
      end
      else
      begin
        Canvas.Pen.Color := LnClr;
        Canvas.MoveTo(R.Left{ + FMargin}, R.Top + FMargin + 2);
        Canvas.LineTo(R.Right - FMargin, R.Top + FMargin + 2);
        Canvas.Pen.Color := clWhite;
        Canvas.MoveTo(R.Left{ + FMargin}, R.Top + FMargin + 3);
        Canvas.LineTo(R.Right - FMargin, R.Top + FMargin + 3);
      end;

      Canvas.Pen.Color := LnClr;
      Canvas.MoveTo(R.Left{ + FMargin}, R.Top + FMargin + 2);
      Canvas.LineTo(R.Left{ + FMargin}, R.Bottom - FMargin);
      Canvas.MoveTo(R.Left{ + FMargin}, R.Bottom - FMargin);
      Canvas.LineTo(R.Right - FMargin, R.Bottom - FMargin);
      Canvas.MoveTo(R.Right - FMargin, R.Bottom - FMargin);
      Canvas.LineTo(R.Right - FMargin, R.Top + FMargin + 2);
      Canvas.Pen.Color := clWhite;
      Canvas.MoveTo(R.Left{ + FMargin} + 1, R.Top + FMargin + 3);
      Canvas.LineTo(R.Left{ + FMargin} + 1, R.Bottom - FMargin);
      Canvas.MoveTo(R.Left{ + FMargin} + 1, R.Bottom - FMargin + 1);
      Canvas.LineTo(R.Right - FMargin + 1, R.Bottom - FMargin + 1);
      Canvas.MoveTo(R.Right - FMargin + 1, R.Bottom - FMargin + 1);
      Canvas.LineTo(R.Right - FMargin + 1, R.Top + FMargin + 2);
    end
    else
    begin
      Canvas.Brush.Style := bsClear;
      if (Caption <> '') then
      begin
        CapR := R;
        CapR.Left := CapR.Left + 10;
        Canvas.Font.Color := clBlack;
        DrawText(Canvas.Handle, PChar(Caption), -1, CapR, DT_SINGLELINE or DT_Top);
        DrawText(Canvas.Handle, PChar(Caption), -1, CapR, DT_SINGLELINE or DT_Top or DT_CALCRECT);
        Canvas.Pen.Color := LnClr;
        Canvas.MoveTo(R.Left{ + FMargin}, R.Top + FMargin + 2);
        Canvas.LineTo(R.Left{ + FMargin} + 9, R.Top + FMargin + 2);
        Canvas.MoveTo(R.Left + CapR.Right + 1, R.Top + FMargin + 2);
        Canvas.LineTo(R.Right - FMargin, R.Top + FMargin + 2);
      end
      else
      begin
        Canvas.Pen.Color := LnClr;
        Canvas.MoveTo(R.Left{ + FMargin}, R.Top + FMargin + 2);
        Canvas.LineTo(R.Right - FMargin, R.Top + FMargin + 2);
      end;

      Canvas.Pen.Color := LnClr;
      Canvas.MoveTo(R.Left{ + FMargin}, R.Top + FMargin + 2);
      Canvas.LineTo(R.Left{ + FMargin}, R.Bottom - FMargin);
      Canvas.MoveTo(R.Left{ + FMargin}, R.Bottom - FMargin);
      Canvas.LineTo(R.Right - FMargin, R.Bottom - FMargin);
      Canvas.MoveTo(R.Right - FMargin, R.Bottom - FMargin);
      Canvas.LineTo(R.Right - FMargin, R.Top + FMargin + 2);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.ReadState(Reader: TReader);
begin
  inherited ReadState(Reader);
  if Reader.Parent is TAdvToolBar then
    AdvToolBar := TAdvToolBar(Reader.Parent);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.SetAdvToolBar(
  const Value: TAdvCustomToolBar);
var
  I: Integer;
begin
  if (FAdvToolBar <> Value) then
  begin
    FAdvToolBar := Value;
    for I := 0 to ControlCount-1 do
    begin
      if (Controls[I] is TAdvCustomToolBarControl) then
        TAdvCustomToolBarControl(Controls[I]).FAdvToolBar := FAdvToolBar;

      if Assigned(AdvToolBar) and (Controls[I] is TAdvCustomGlowButton) then
      begin
        TProCustomGlowButton(Controls[I]).OnInternalKeyDown := AdvToolBar.OnGlowButtonKeyDown;
      end;
    end;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.SetCaption(const Value: TCaption);
begin
  FCaption := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.SetColor(const Value: TGradientBackground);
begin
  FColor.Assign(Value);
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.SetLineColor(const Value: TColor);
begin
  FLineColor := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.SetOfficeHint(const Value: TAdvHintInfo);
begin
  FOfficeHint.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.SetParentStyler(const Value: Boolean);
begin
  FParentStyler := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.SetLine3D(const Value: Boolean);
begin
  FLine3D := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.WMEraseBkGnd(var Message: TWMEraseBkGnd);
{
var
  DC: HDC;
  i: Integer;
  p: TPoint;
}
begin
  Message.Result := 1;
  inherited;
  

  (*
  if {FTransparent} True then
  begin
    if Assigned(Parent) then
    begin
      DC := Message.DC;
      i := SaveDC(DC);
      p := ClientOrigin;
      Windows.ScreenToClient(Parent.Handle, p);
      p.x := -p.x;
      p.y := -p.y;
      MoveWindowOrg(DC, p.x, p.y);
      SendMessage(Parent.Handle, WM_ERASEBKGND, DC, 0);
      SendMessage(Parent.Handle, WM_PAINT, DC, 0);
      if (Parent is TWinCtrl) then
        (Parent as TWinCtrl).PaintCtrls(DC, nil);
      RestoreDC(DC, i);
    end;
  end
  else
    inherited;
  *)  
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.CMMouseEnter(var Msg: TMessage);
begin
  inherited;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarContainer.CMControlChange(
  var Message: TCMControlChange);
var
  x, i: Integer;
begin
  inherited;

  with Message do
  begin
    if Inserting then
    begin
      if (Control is TAdvCustomGlowButton) and Assigned(AdvToolBar) then
      begin
        TProCustomGlowButton(Control).OnInternalKeyDown := AdvToolBar.OnGlowButtonKeyDown;
      end;

      if (csDesigning in ComponentState) then
      begin
        x := 0;
        for i := 0 to ControlCount - 1 do
        begin
          if (Controls[i] <> Control) and (X < (Controls[i].Left + Controls[i].Width)) then
          begin
            x := Controls[i].Left + Controls[i].Width;
          end;
        end;

        if (x > 0) and (x < Self.Width) then
        begin
          Control.Left := x;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

{ TContainerAppearance }

procedure TContainerAppearance.Assign(Source: TPersistent);
begin
  if (Source is TContainerAppearance) then
  begin
    LineColor := (Source as TContainerAppearance).LineColor;
    Line3D := (Source as TContainerAppearance).Line3D;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TContainerAppearance.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

constructor TContainerAppearance.Create;
begin
  inherited;
  FLine3D := True;
  FLineColor := clBtnShadow;
end;

//------------------------------------------------------------------------------

procedure TContainerAppearance.SetLine3D(const Value: Boolean);
begin
  if (FLine3D <> Value) then
  begin
    FLine3D := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TContainerAppearance.SetLineColor(const Value: TColor);
begin
  if (FLineColor <> Value) then
  begin
    FLineColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

{ AdvToolbarPager Key Hook }

var
  PagerKeyHook: HHOOK;
  MainPager: TAdvToolBarPager;
  {$IFDEF DELPHI9_LVL}
  OldWParam: Integer = -1;
  {$ENDIF}

procedure ReleasePagerKeyHooks; forward;

function PagerKeyMsgHook(Code: Integer; WParam: Longint; var Msg: TMsg): Longint; stdcall;
begin
  if (Code = HC_ACTION) then
  begin
    {if (Msg.Message = CM_DEACTIVATE) or (Msg.message = WM_COMMAND) then
      ReleasePagerKeyHooks
    else}
    if (Msg.Message = WM_KEYDOWN) then
    begin
      if Assigned(MainPager) then
      begin
        {$IFDEF DELPHI9_LVL}
        if (OldWParam <> Msg.WParam) then
          MainPager.HandleKey(Msg.WParam);
        OldWParam := Msg.WParam;
        {$ELSE}
        MainPager.HandleKey(Msg.WParam);
        {$ENDIF}
      end;

      //OutputDebugString(PChar(Inttostr(Msg.message) +' lParam'+ Inttostr(Msg.lParam) + 'hwnd' + inttostr(Msg.hwnd)));
    end
    else if (Msg.Message = WM_KEYUP) then
    begin
      {$IFDEF DELPHI9_LVL}
      OldWParam := -1;
      {$ENDIF}
    end;
  end;
  Result := CallNextHookEx(PagerKeyHook, Code, WParam, Longint(@Msg))
end;

//-------------------------------

procedure InitPagerKeyHooks(Pager: TAdvToolBarPager);
begin
  if PagerKeyHook = 0 then
  begin
    MainPager := Pager;
    PagerKeyHook := SetWindowsHookEx(WH_GETMESSAGE, @PagerKeyMsgHook, 0, GetCurrentThreadID);
  end;
end;

//-------------------------------

procedure ReleasePagerKeyHooks;
begin
  if PagerKeyHook <> 0 then
    UnhookWindowsHookEx(PagerKeyHook);
  PagerKeyHook := 0;
  MainPager := nil;
end;

//------------------------------------------------------------------------------

{ TAdvToolBarPager }

constructor TAdvToolBarPager.Create(AOwner: TComponent);
var
  ms: TMemoryStream;
  bmp: TBitmap;
begin
  inherited;

  ControlStyle := ControlStyle + [csAcceptsControls] - [csOpaque];

  inherited Align := alTop;
  FDockAlign := daTop;

  FInternalToolBarStyler := TCustomAdvToolBarStyler.Create(self);
  FInternalToolBarStyler.Name := 'InternalStyler';

  FToolBarStyler := nil;
  FCurrentToolBarStyler := FInternalToolBarStyler;
  FCurrentToolBarStyler.AddControl(self);
  {$IFDEF DELPHI6_LVL}
  FInternalToolBarStyler.SetSubComponent(True);
  {$ENDIF}

  FOffSetX := 0;
  FOffSetY := 0;
  FEnableWheel := true;
  FAntiAlias := aaClearType;

  FLeftScrollBtn := nil;
  FRightScrollBtn := nil;
  FStartTabIndex := 0;

  FAdvPages := TDbgList.Create;

  FQuickAccessToolBar := nil;

  FTabScroller := TATBTabScroller.Create;

  FMinimumSize := MINDOCKPANELHEIGHT;
  //FUseRunTimeHeight := False;

  FIOptionPicture := TGDIPPicture.Create;
  //FIOptionPicture.LoadFromResourceName(HInstance, 'OPTIONIND_PIC');  // does not work
  bmp := TBitmap.Create;
  bmp.LoadFromResourceName(HInstance, 'OPTIONIND_PIC');
  ms := TMemoryStream.Create;
  bmp.SaveToStream(ms);
  FIOptionPicture.LoadFromStream(ms);
  ms.Free;
  bmp.Free;
  FIOptionPicture.OnChange := OnOptionPictureChanged;

  FIOptionDisabledPicture := TGDIPPicture.Create;
  bmp := TBitmap.Create;
  bmp.LoadFromResourceName(HInstance, 'OPTIONIND_PICD');
  ms := TMemoryStream.Create;
  bmp.SaveToStream(ms);
  FIOptionDisabledPicture.LoadFromStream(ms);
  ms.Free;
  bmp.Free;
  FIOptionDisabledPicture.OnChange := OnOptionPictureChanged;
  
  FTabSettings := TATBTabSettings.Create;
  FTabSettings.OnChange := OnTabSettingsChanged;
  FCurrentTabSpacing := FTabSettings.Spacing;
  FCurrentTabLeftMargin := FTabSettings.LeftMargin;
  FCurrentTabRightMargin := FTabSettings.RightMargin;
  FCurrentGroupTabLeftMargin := FTabSettings.LeftMargin;
  FCurrentGroupTabRightMargin := FTabSettings.RightMargin;

  FCaption := TAdvPageCaption.Create;
  FCaption.OnChange := OnCaptionChanged;

  FActivePageIndex := -1;
  FHotPageIndex := -1;
  FOldHotPageIndex := -1;
  FDownPageIndex := -1;

  FShowTabHint := false;
  FHintPageIndex := -1;
  ShowHint := false;

  FExpanded := True;
  FExpandedHeight := Height;
  
  FTabGroups := TTabGroups.Create(self);
  FTabGroups.OnChange := OnTabGroupsChanged;

  FPersistence:= TPersistence.Create(self);
  FPersistence.OnChange:= OnPersistenceChanged;

  DoubleBuffered := true;
  Height := 149;
  FCanMove := False;
  FCaptionButtons := [];
  FCaptionCloseBtn := nil;
  FCaptionMinBtn := nil;
  FCaptionMaxBtn := nil;
  FCaptionBtnImages := nil;
  FOldCapRightIndent := 0;
  FHidePagesOnDblClick := true;

  FOfficeHint := TAdvHintInfo.Create;

  TabStop := False;

  FPageRightMargin := 0;
  FPageLeftMargin := 0;
  FShortCutHintWinList := TDbgList.Create;

  FAutoMDIButtons := False;
  FMDIButtonsVisible := False;
  FMDIButtonsWidth := 16;
  FMDIButtonsSpace := 2;
  FMDICloseBtn := nil;
  FMDIMinBtn := nil;
  FMDIMaxBtn := nil;
  FMDIChildForm := nil;
  FMDIBtnImages := nil;

  FShortCutTimer := TTimer.Create(Self);
  FShortCutTimer.Enabled := False;
  FShortCutTimer.Interval := 50; //SHORTCUT_DELAY;
  FShortCutTimer.OnTimer := OnShortCutTime;

  FShortCutDelay := 0;

  FFormWindowState := wsNormal;

  FDesignTime := (csDesigning in ComponentState) and not
      ((csReading in Owner.ComponentState) or (csLoading in Owner.ComponentState));

  FOfficeToolBarStyler := TAdvToolBarOfficeStyler.Create(self);
  FCurrentToolBarStyler := FOfficeToolBarStyler;
  TAdvToolBarOfficeStyler(FOfficeToolBarStyler).Style := bsOffice2007Luna;

  FOldHeight := 0;
  FHideState := False;
  FDblClickTimer := TTimer.Create(Self);
  FDblClickTimer.Enabled := False;
  FDblClickTimer.Interval := DBLCLICK_DELAY;
  FDblClickTimer.OnTimer := OnDblClickTimer;
  FClickCount := 0;

  FNonActiveMouseWheelOnFocus := False;
  (*
  for i:= 0 to AOwner.ComponentCount-1 do
  begin
    if (AOwner.Components[i] is TAdvToolBarPager) and (AOwner.Components[i] <> Self) then
      raise Exception.Create('Only one instance of AdvToolBarPager can be placed on a Form.');
  end;
  *)
//  ps.Free;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CreateParams(var Params: TCreateParams);
begin
  inherited;
  //if not (csDesigning in ComponentState) then
    //Params.WindowClass.Style:= Params.WindowClass.Style and not (CS_HREDRAW or CS_VREDRAW);
 { if (FAdvPages.Count = 0)  and (csDesigning in ComponentState) then
  begin
    FDefPage1 := TAdvPage.Create(FOwner);
    FDefPage1.Parent := Self;
    FDefPage1.AdvToolBarPager := Self;
    FDefPage1.Caption := 'AdvPage1';

    FDefPage2 := TAdvPage.Create(FOwner);
    FDefPage2.Parent := Self;
    FDefPage2.AdvToolBarPager := Self;
    FDefPage2.Caption := 'AdvPage2';

    FDefPage3 := TAdvPage.Create(FOwner);
    FDefPage3.Parent := Self;
    FDefPage3.AdvToolBarPager := Self;
    FDefPage3.Caption := 'AdvPage3';
    Self.ActivePage := FDefPage1;
  end;
  }
end;

//------------------------------------------------------------------------------

destructor TAdvToolBarPager.Destroy;
var
  i: Integer;
begin
  if (Self = MainPager) then
  ReleasePagerKeyHooks;
  
  if Assigned(FPersistence) and FPersistence.Enabled and not (csDesigning in ComponentState) then
    SaveState;

  {$IFDEF DELPHI2006_LVL}
  if not (csDesigning in ComponentState) and Assigned(FToolBarStyler) and (FToolBarStyler <> FInternalToolBarStyler) then
  begin
    FToolBarStyler.RemoveControl(self);
    FToolBarStyler := nil;
  end;
  {$ENDIF}
  FInternalToolBarStyler.Free;
  FOfficeToolBarStyler.Free;

  FDblClickTimer.Free;
  
  for I := 0 to FAdvPages.Count - 1 do
    TAdvPage(FAdvPages[I]).FAdvToolBarPager := nil;

  if (FCaptionBtnImages <> nil) then
    FCaptionBtnImages.Free;
  if (FCaptionCloseBtn <> nil) then
    FCaptionCloseBtn.Free;
  if (FCaptionMaxBtn <> nil) then
    FCaptionMaxBtn.Free;
  if (FCaptionMinBtn <> nil) then
    FCaptionMinBtn.Free;

  if (FMDICloseBtn <> nil) then
    FMDICloseBtn.Free;
  if (FMDIMinBtn <> nil) then
    FMDIMinBtn.Free;
  if (FMDIMaxBtn <> nil) then
    FMDIMaxBtn.Free;
  if (FMDIBtnImages <> nil) then
    FMDIBtnImages.Free;

  FAdvPages.Free;
  FTabSettings.Free;
  FCaption.Free;
  FTabScroller.Free;
  FTabGroups.Free;
  FOfficeHint.Free;
  FIOptionPicture.Free;
  FIOptionDisabledPicture.Free;

  for i := 0 to FShortCutHintWinList.Count-1 do
  begin
    if (FShortCutHintWinList.Items[i] <> nil) then
    begin
      TShortCutHintWindow(FShortCutHintWinList.Items[i]).Free;
      FShortCutHintWinList.Items[i] := nil;
    end;  
  end;
  FShortCutHintWinList.Free;
  FShortCutTimer.Free;
  FPersistence.Free;
  inherited;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.AddAdvPage(AdvPage: TAdvPage): integer;
begin
  Result := FAdvPages.IndexOf(AdvPage);
  if (FAdvPages.IndexOf(AdvPage) < 0) then
    Result := FAdvPages.Add(AdvPage);
  if (AdvPage.Parent <> Self) then
    AdvPage.Parent := Self;
  AdvPage.FAdvToolBarPager := Self;
  SetPagePosition(AdvPage);
  if (AdvPage <> ActivePage) then
    AdvPage.Visible := False;

  InvalidateTab(-1);
  if Assigned(ActivePage) then
    ActivePage.BringToFront;

  //UpdateTabScroller;
  InitializeTabsSize;
  UpdateTabPosition;
  InitializeScroller;
  //AdvPage.UpdateTabShowing;

  //PostMessage(Handle, WM_Size, 0, 0);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.AddAdvPage(PageCaption: TCaption): integer;
var
  aPage: TAdvPage;
begin
  aPage := TAdvPage.Create(Self);
  aPage.Caption := PageCaption;
  Result := AddAdvPage(aPage);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.AlignControls(AControl: TControl;
  var ARect: TRect);
begin
  inherited;
  if (AControl <> nil) and (AControl is TAdvPage) then
    SetPagePosition(TAdvPage(AControl))
  else if (AControl is TAdvPage) then
    SetAllPagesPosition;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetAlign: TDockAlign;
begin
  Result := FDockAlign;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.Loaded;
begin
  inherited;
  UpdateCaptionButtons(True);
  if AutoMDIButtons then
  begin
    FAutoMDIButtons := False;
    AutoMDIButtons := True;
  end;

  FPropertiesLoaded := True;
  
  InitializeTabsSize;
  UpdateTabSizes;
  InitializeScroller;

  if FPersistence.Enabled and not (csDesigning in ComponentState) then
    LoadState;

  if not (csDesigning in ComponentState) then
    InitPagerKeyHooks(Self);

  if not (csDesigning in ComponentState) and Assigned(Application) then
  begin
    //Application.HintPause := 900;
    //Application.HintHidePause := 20000;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  inherited;

  if not (csDestroying in ComponentState) and (Operation = opRemove) then
  begin
    if AComponent = ToolBarStyler then
      ToolBarStyler := nil;
    if (AComponent = PopupMenu) then
      PopupMenu := nil;
    if (AComponent = Images) then
      Images := nil;
    if (AComponent = DisabledImages) then
      DisabledImages := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetGlowSpeed(speed: integer);
begin
  GlowSpeed := speed;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.AdjustClientRect(var Rect: TRect);
begin
  { if Align in [daTop, daBottom] then
   begin
     if (FAdvPages.Count > 0) then
       Rect.Top := Rect.Top + TabSettings.Height;
     if (FCaption.Visible) then
       Rect.Top := Rect.Top + FCaption.Height;
   end; }
  inherited AdjustClientRect(Rect);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetFirstVisibleTabIndex: Integer;
var
  i: Integer;
begin
  Result := -1;
  for i:= 0 to AdvPageCount-1 do
  begin
    if AdvPages[i].TabVisible then
    begin
      Result := i;
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.ShouldDrawSeparator(PageIndex: Integer): Boolean;
begin
  Result := (FCurrentTabSpacing <= FTabSettings.MinSpacing) and (FCurrentTabLeftMargin <= FTabSettings.LeftMargin) and (FCurrentTabRightMargin <= FTabSettings.RightMargin)
            and (PageIndex >= 0) and (PageIndex < AdvPageCount);
  if Result then
  begin
    Result := (GetFirstVisibleTabIndex <> PageIndex);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DrawTab(PageIndex: Integer);
var
  GradColor: TColor;
  GradColorTo: TColor;
  GradColorMirror: TColor;
  GradColorMirrorTo: TColor;
  PenColor: TColor;
  GradB, GradU: TGDIPGradient;
  ImgList: TCustomImageList;
  //Pic: TGDIPPicture;
  ImgEnabled: Boolean;
  //Rgn1, Rgn2: HRGN;
  R, CapR, TR, R2, R3, TxtR: TRect;
  i, ImgX, ImgY, ImgTxtSp, j: Integer;
  //p: TPoint;
  DCaption: string;
  DWCaption: widestring;
  DoRepaint: Boolean;
  TxtClr, HighLightClr: TColor;
  TabAppearance: TCustomTabAppearance;
  SelectedHot: Boolean;
  bmp, bmp2: TBitmap;
  ACanvas: TCanvas;
  TabGroup: Integer;
begin
  if (PageIndex < 0) or (PageIndex >= FAdvPages.Count) or (TabSettings.Height <= 0) then
    Exit;

  ImgTxtSp := IMG_SPACE;
  GradColor := clNone;
  GradColorTo := clNone;
  GradColorMirror := clNone;
  GradColorMirrorTo := clNone;
  PenColor := clNone;
  TxtClr := clNone;
  GradB := ggRadial;
  GradU := ggRadial;

  ImgList := nil;
  DoRepaint := True;

  SelectedHot := False;

  R := GetTabRect(PageIndex);
  TR := GetTabsRect;


  if ((R.Left <= -1) and (R.Right <= -1)) or (((R.Left < TR.Left) and (R.Right < TR.Left)) or ((R.Left > TR.Right) and (R.Right > TR.Right))) then
  begin
    Exit;
  end;
 { if not Enabled then
  begin
    FState := absDisabled;
    FDragging := False;
  end
  else
  begin
    if (FState = absDisabled) then
      if FDownChecked and (GroupIndex <> 0) then
        FState := absExclusive
      else
        FState := absUp;
  end;
  if (Style = bsCheck) and (Down) then
    FState := absDown;
  }

  TabGroup := GroupOfTab(PageIndex);


  ACanvas := Canvas;

  bmp := nil;
  if (R.Left < TR.Left) or (R.Right > TR.Right) then
  begin
    bmp := TBitmap.Create;
    bmp.Height := Self.Height;
    bmp.Width := Self.Width;
    R3 := Rect(0, 0, bmp.Width, bmp.Height);
    //bmp.Canvas.Brush.Color := FCurrentToolBarStyler.TabAppearance.BackGround.Color;
    //bmp.Canvas.FillRect(R3);
    with FCurrentToolBarStyler.TabAppearance do
    begin
      if (BackGround.Color <> clNone) and (BackGround.ColorTo <> clNone) then
        DrawGradient(bmp.Canvas, BackGround.Color, BackGround.ColorTo, BackGround.Steps, R, BackGround.Direction = gdHorizontal)
      else if (BackGround.Color <> clNone) then
      begin
        bmp.Canvas.Brush.Color := BackGround.Color;
        bmp.Canvas.Pen.Color := BackGround.Color;
        bmp.Canvas.Rectangle(R.Left, R.Top, R.Right, R.Bottom);
      end;
    end;
    R3 := R;
    if (R3.Left < TR.Left) then
    begin
      R3.Left := TR.Left;
    end;

    if (R3.Right > TR.Right) then
    begin
      R3.Right := TR.Right;
    end;
    ACanvas := bmp.Canvas;
  end;

  TabAppearance := FCurrentToolBarStyler.TabAppearance;
  i := GroupOfTab(PageIndex);
  if (i >= 0) and (i < FTabGroups.Count) then
  begin
    if not FTabGroups.Items[i].DefaultAppearance then
      TabAppearance := FTabGroups.Items[i].GroupAppearance.TabAppearance
    else
      TabAppearance := FCurrentToolBarStyler.GroupAppearance.TabAppearance;
  end;

  HighLightClr := TabAppearance.HighLightColor;

  //-------- Tab separator
  if ShouldDrawSeparator(PageIndex) and (bmp = nil) then
  begin
    //i := 6;
    PenColor := BlendColor(FCurrentToolBarStyler.TabAppearance.BackGround.Color, FCurrentToolBarStyler.TabAppearance.BorderColorSelected, 60);
    DrawGradient(Canvas, PenColor, FCurrentToolBarStyler.TabAppearance.BorderColorSelected, 40, Rect(R.Left - 2, R.Top+1, R.Left - 1, R.Bottom), False);
    //Canvas.Pen.Color := FCurrentToolBarStyler.TabAppearance.BorderColorSelected;
    //Canvas.MoveTo(R.Left - 2, R.Top+8);
    //Canvas.LineTo(R.Left - 2, R.Bottom);
    PenColor := clNone;
  end;

  with TabAppearance do
  begin
    //DrawDwLn := False;
    if not(AdvPages[PageIndex].TabEnabled) and ShowNonSelectedTabs then
    begin
      if ShowNonSelectedTabs then
      begin
        GradColor := ColorDisabled;
        GradColorTo := ColorDisabledTo;
        GradColorMirror := ColorMirrorDisabled;
        GradColorMirrorTo := ColorMirrorDisabledTo;
        PenColor := BorderColorDisabled;
        GradU := GradientDisabled;
        GradB := GradientMirrorDisabled;
        TxtClr := TextColorDisabled;
      end
      else
      begin

      end;
    end
    else if (PageIndex = ActivePageIndex) and (Expanded or (not Expanded and IsFloatingRibbonShowing)) then
    begin
      GradColor := ColorSelected;
      GradColorTo := ColorSelectedTo;
      GradColorMirror := ColorMirrorSelected;
      GradColorMirrorTo := ColorMirrorSelectedTo;
      PenColor := BorderColorSelected;
      GradU := GradientSelected;
      GradB := GradientMirrorSelected;
      TxtClr := TextColorSelected;
      HighLightClr := TabAppearance.HighLightColor;

     { if (GroupOfTab(PageIndex) >= 0) then
      begin
        GradColor := ColorSelectedGroup;
        GradColorTo := ColorSelectedGroupTo;
        GradColorMirror := ColorMirrorSelectedGroup;
        GradColorMirrorTo := ColorMirrorSelectedGroupTo;
        //PenColor := BorderColorSelectedGroup;
        GradU := GradientSelectedGroup;
        GradB := GradientMirrorSelectedGroup;
        TxtClr := TextColorSelectedGroup;
      end;
      }
      if (PageIndex = FHotPageIndex) then
      begin
        PenColor := BorderColorSelectedHot;
        HighLightClr := TabAppearance.HighLightColorSelectedHot;
      end;

      if Assigned(AdvPages[PageIndex].FTimer) then
      begin
        if (AdvPages[PageIndex].FGlowState = gsPush) then
        begin
          GradColor := BlendColor(GradColor, FColorHot, AdvPages[PageIndex].FStepPush);
          GradColorTo := BlendColor(GradColorTo, FColorHotTo, AdvPages[PageIndex].FStepPush);
          GradColorMirror := BlendColor(GradColorMirror, FColorMirrorHot, AdvPages[PageIndex].FStepPush);
          GradColorMirrorTo := BlendColor(GradColorMirrorTo, FColorMirrorHotTo, AdvPages[PageIndex].FStepPush);
          PenColor := BlendColor(PenColor, BorderColorHot, AdvPages[PageIndex].FStepPush);
        end
        else if (AdvPages[PageIndex].FGlowState = gsHover) then
          PenColor := BlendColor(BorderColorSelectedHot, BorderColorSelected, AdvPages[PageIndex].FStepHover);
      end;

      if (FDownPageIndex = PageIndex) and not (csDesigning in ComponentState) then
      begin
        PenColor := BorderColorDown;
        HighLightClr := TabAppearance.HighLightColorDown;
      end;
    end
    else //if State = absUp then
    begin
      if (PageIndex = FHotPageIndex) then
      begin
        GradColor := ColorHot;
        GradColorTo := ColorHotTo;
        GradColorMirror := ColorMirrorHot;
        GradColorMirrorTo := ColorMirrorHotTo;
        PenColor := BorderColorHot;
        GradU := GradientHot;
        GradB := GradientMirrorHot;
        TxtClr := TextColorHot;
        HighLightClr := TabAppearance.HighLightColorHot;
        //DrawDwLn := True;
        if Assigned(AdvPages[PageIndex].FTimer) and (AdvPages[PageIndex].FGlowState = gsHover) then
        begin
          if ShowNonSelectedTabs then
          begin
            GradColor := BlendColor(FColorHot, FColor, AdvPages[PageIndex].FStepHover);
            GradColorTo := BlendColor(FColorHotTo, FColorTo, AdvPages[PageIndex].FStepHover);
            GradColorMirror := BlendColor(FColorMirrorHot, FColorMirror, AdvPages[PageIndex].FStepHover);
            GradColorMirrorTo := BlendColor(FColorMirrorHotTo, FColorMirrorTo, AdvPages[PageIndex].FStepHover);
            PenColor := BlendColor(BorderColorHot, BorderColor, AdvPages[PageIndex].FStepHover);
          end
          else
          begin
            GradColor := BlendColor(FColorHot, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            if (FCurrentToolBarStyler.TabAppearance.BackGround.ColorTo <> clNone) then
              GradColorTo := BlendColor(FColorHotTo, FCurrentToolBarStyler.TabAppearance.BackGround.ColorTo, AdvPages[PageIndex].FStepHover)
            else
              GradColorTo := BlendColor(FColorHotTo, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            GradColorMirror := BlendColor(FColorMirrorHot, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            GradColorMirrorTo := BlendColor(FColorMirrorHotTo, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            PenColor := BlendColor(BorderColorHot, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
          end;
        end;
      end
      else // Normal draw
      begin
        if ShowNonSelectedTabs then
        begin
          GradColor := Color;
          GradColorTo := ColorTo;
          GradColorMirror := ColorMirror;
          GradColorMirrorTo := ColorMirrorTo;
          PenColor := BorderColor;
          GradU := Gradient;
          GradB := GradientMirror;
          TxtClr := TextColor;
          if Assigned(AdvPages[PageIndex].FTimer) and (AdvPages[PageIndex].FGlowState = gsHover) {and (PageIndex = FOldHotPageIndex)} then
          begin
            GradColor := BlendColor(FColorHot, FColor, AdvPages[PageIndex].FStepHover);
            GradColorTo := BlendColor(FColorHotTo, FColorTo, AdvPages[PageIndex].FStepHover);
            GradColorMirror := BlendColor(FColorMirrorHot, FColorMirror, AdvPages[PageIndex].FStepHover);
            GradColorMirrorTo := BlendColor(FColorMirrorHotTo, FColorMirrorTo, AdvPages[PageIndex].FStepHover);
            PenColor := BlendColor(BorderColorHot, BorderColor, AdvPages[PageIndex].FStepHover);
          end;
        end
        else
        begin
          DoRepaint := False;
          TxtClr := TextColor;
          GradU := GradientHot;
          GradB := GradientMirrorHot;

          if not AdvPages[PageIndex].TabEnabled then
           TxtClr := TextColorDisabled;
          
          if Assigned(AdvPages[PageIndex].FTimer) and (AdvPages[PageIndex].FGlowState = gsHover){ and (PageIndex = FOldHotPageIndex)} then
          begin
            GradColor := BlendColor(FColorHot, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            if (FCurrentToolBarStyler.TabAppearance.BackGround.ColorTo <> clNone) then
              GradColorTo := BlendColor(FColorHotTo, FCurrentToolBarStyler.TabAppearance.BackGround.ColorTo, AdvPages[PageIndex].FStepHover)
            else
              GradColorTo := BlendColor(FColorHotTo, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            GradColorMirror := BlendColor(FColorMirrorHot, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            GradColorMirrorTo := BlendColor(FColorMirrorHotTo, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            PenColor := BlendColor(BorderColorHot, FCurrentToolBarStyler.TabAppearance.BackGround.Color, AdvPages[PageIndex].FStepHover);
            DoRepaint := True;
          end;
        end;
      end;
    end;

    if Focused and (PageIndex = ActivePageIndex) then
    begin
      GradColor := ColorHot;
      GradColorTo := ColorHotTo;
      GradColorMirror := ColorMirrorHot;
      GradColorMirrorTo := ColorMirrorHotTo;
      PenColor := BorderColorSelectedHot;
      GradU := GradientHot;
      GradB := GradientMirrorHot;
      TxtClr := TextColorHot;
      SelectedHot := True;
      HighLightClr := TabAppearance.HighLightColorSelected;
    end;

  {  if FHot then
    begin
      GradColor := FColorHot;
      GradColorTo := FColorHotTo;
      GradColorMirror := FColorMirrorHot;
      GradColorMirrorTo := FColorMirrorHotTo;
      PenColor := BorderColorHot;
      GradU := GradientHot;
      GradB := GradientMirrorHot;
    end
    else
    begin
      GradColor := FColor;
      GradColorTo := FColorTo;
      GradColorMirror := FColorMirror;
      GradColorMirrorTo := FColorMirrorTo;
      PenColor := BorderColor;
      GradU := Gradient;
      GradB := GradientMirror;
    end;

    if FDown then
    begin
      PenColor := BorderColorDown;
      GradU := GradientDown;
      GradB := GradientMirrorDown;
    end;
  }
  (*  if Assigned(FTimer) then
    begin
      if not FDown and not ((State = absExclusive) or ((Style = bsCheck) and (State = absDown))) then
      begin
        GradColor := BlendColor(FColorHot, FColor, FStepHover);
        GradColorTo := BlendColor(FColorHotTo, FColorTo, FStepHover);
        GradColorMirror := BlendColor(FColorMirrorHot, FColorMirror, FStepHover);
        GradColorMirrorTo := BlendColor(FColorMirrorHotTo, FColorMirrorTo, FStepHover);
        PenColor := BlendColor(BorderColorHot, BorderColor, FStepHover);
      end
      else
      begin
        if FDown and (State <> absExclusive) then
        begin
          GradColor := BlendColor(FColorDown, FColorHot, FStepPush);
          GradColorTo := BlendColor(FColorDownTo, FColorHotTo, FStepPush);
          GradColorMirror := BlendColor(FColorMirrorDown, FColorMirrorHot, FStepPush);
          GradColorMirrorTo := BlendColor(FColorMirrorDownTo, FColorMirrorHotTo, FStepPush);
          PenColor := BlendColor(BorderColorDown, BorderColorHot, FStepPush);
        end;
      end;
    end;   *)

  {  if Enabled or (DisabledImages = nil) then
    begin
      ImgList := Images;
      EnabledImg := Enabled;
    end
    else
    begin
      ImgList := DisabledImages;
      EnabledImg := True;
    end;

    if Enabled or DisabledPicture.Empty then
      Pic := Picture
    else
      Pic := DisabledPicture;


    if (ImgList = nil) then
    begin
      ImgList := FInternalImages;
      EnabledImg := True;
    end;

    if ShowCaption then
      DCaption := Caption
    else
      DCaption := '';
    }

    DCaption := AdvPages[PageIndex].Caption;
    DWCaption := AdvPages[PageIndex].WideCaption;

    {Canvas.Font.Name := 'Tahoma';
    Canvas.Font.Size := 8;
    Canvas.Font.Style := []; }

    ACanvas.Font.Assign(TabAppearance.Font);
    ACanvas.Font.Color := TxtClr;

    if DoRepaint then
    begin
      DrawVistaGradient(ACanvas, R,GradColor, GradColorTo, GradColorMirror, GradColorMirrorTo, PenColor,
        GradU, GradB, '', {Canvas.}Font, Enabled, False, FAntiAlias, True{FCurrentToolBarStyler.RoundEdges});
      //DrawVistaButton(Canvas, R,GradColor, GradColorTo, GradColorMirror, GradColorMirrorTo, PenColor,
       // GradU, GradB, DCaption, {Canvas.}Font, nil, -1, True, blGlyphLeft, False, False, Enabled, False, dpRight, aaAntiAlias, True);

      if True{FCurrentToolBarStyler.RoundEdges} then
      begin
        ACanvas.Pixels[R.Left, R.Top] := Canvas.Pixels[R.Left - 1, R.Top - 1];
        ACanvas.Pixels[R.Left + 1, R.Top] := Canvas.Pixels[R.Left + 1, R.Top - 1];
        ACanvas.Pixels[R.Left, R.Top + 1] := Canvas.Pixels[R.Left - 1, R.Top];

        ACanvas.Pixels[R.Right - 1, R.Top] := Canvas.Pixels[R.Right + 1, R.Top];
        ACanvas.Pixels[R.Right - 2, R.Top] := Canvas.Pixels[R.Right + 1, R.Top];
        ACanvas.Pixels[R.Right - 1, R.Top + 1] := Canvas.Pixels[R.Right + 1, R.Top];
      end;

      //--- Draw 3D effect
      if not Assigned(AdvPages[PageIndex].FTimer) then
      begin
        if SelectedHot then
          ACanvas.Pen.Color := BlendColor(clWhite, GradColor, 20)
        else
          ACanvas.Pen.Color := BlendColor(clWhite, GradColor, 50);
        ACanvas.MoveTo(R.Left+3, R.Top + 3);
        ACanvas.LineTo(R.Right-3, R.Top+3);
      end
      else
      begin
        if (AdvPages[PageIndex].FGlowState = gsHover) then
          ACanvas.Pen.Color := BlendColor(clWhite, GradColor, 20) //Min(20, AdvPages[PageIndex].FStepHover))
        else
        begin
          if SelectedHot then
            ACanvas.Pen.Color := BlendColor(clWhite, GradColor, 20)
          else
            ACanvas.Pen.Color := BlendColor(clWhite, GradColor, 50);
        end;
        ACanvas.MoveTo(R.Left+3, R.Top + 3);
        ACanvas.LineTo(R.Right-3, R.Top+3);
      end;

      //-- Draw Shadow
      if (FCurrentToolBarStyler.TabAppearance.ShadowColor <> clNone) then
      begin
        ACanvas.Pen.Color := FCurrentToolBarStyler.TabAppearance.ShadowColor;
        ACanvas.MoveTo(R.Right, R.Top + 3);
        ACanvas.LineTo(R.Right, R.Bottom-4);
        ACanvas.Pen.Color := BlendColor(FCurrentToolBarStyler.TabAppearance.ShadowColor, FCurrentToolBarStyler.TabAppearance.BackGround.Color, 40);
        ACanvas.MoveTo(R.Right + 1, R.Top + 4);
        ACanvas.LineTo(R.Right + 1, R.Bottom-4);
      end;

      //if not Assigned(AdvPages[PageIndex].FTimer) then
      if (HighLightClr <> clNone) then
      begin
        ACanvas.Pen.Color := BlendColor(GradColor, PenColor, 80);
        ACanvas.MoveTo(R.Left+3, R.Top+1);
        ACanvas.LineTo(R.Right-3, R.Top+1);
        ACanvas.Pen.Color := HighLightClr; //BlendColor(GradColor, PenColor, 50);
        ACanvas.MoveTo(R.Left+1, R.Top + 3);
        ACanvas.LineTo(R.Left+1, R.Bottom-5);
        ACanvas.MoveTo(R.Right-2, R.Top + 3);
        ACanvas.LineTo(R.Right-2, R.Bottom-5);
      end;
    end;

    if (TabGroup >= 0) then
      CapR := Rect(R.Left + FCurrentGroupTabLeftMargin, R.Top, R.Right, R.Bottom)
    else
      CapR := Rect(R.Left + FCurrentTabLeftMargin{FTabSettings.LeftMargin}, R.Top, R.Right, R.Bottom);
    if (Assigned(FImages) or Assigned(DisabledImages)) and (AdvPages[PageIndex].ImageIndex >= 0) then
    begin
      ImgEnabled := True;
      if AdvPages[PageIndex].Enabled then
      begin
        if Assigned(FImages) then
          ImgList := FImages;
      end
      else
      begin
        if Assigned(FDisabledImages) then
          ImgList := FDisabledImages
        else if Assigned(FImages) then
        begin
          ImgList := FImages;
          ImgEnabled := False;
        end;
      end;

      if (ImgList <> nil) then
      begin
        ImgX := CapR.Left;
        CapR.Left := CapR.Left + ImgList.Width + ImgTxtSp;
        ImgY := R.Top + ((R.Bottom - R.Top) - ImgList.Height) div 2;
        ImgList.Draw(ACanvas, ImgX, ImgY, AdvPages[PageIndex].ImageIndex, ImgEnabled);
      end;
    end;

    CapR.Right := CapR.Right - 2;
    bmp2 := TBitmap.Create;
    bmp2.Height := R.Bottom - R.Top;
    R2 := Rect(0, 0, GetRealTabWidth(PageIndex, j), R.Bottom - R.Top);
    if (TabGroup >= 0) then
      R2.Right := R2.Right - FCurrentGroupTabLeftMargin {- FCurrentGroupTabRightMargin}
    else
      R2.Right := R2.Right - FCurrentTabLeftMargin {- FCurrentTabRightMargin};
    bmp2.Width := R2.Right - R2.Left;
    bmp2.Canvas.CopyMode := cmSrcCopy;
    bmp2.Canvas.CopyRect(Rect(0, 0, CapR.Right - CapR.Left , CapR.Bottom - CapR.Top), ACanvas, CapR);
    R2 := Rect(0, 0, R2.Right, bmp2.Height);

    ACanvas.Font.Assign(FCurrentToolBarStyler.TabAppearance.Font);
    ACanvas.Font.Color := TxtClr;

    bmp2.Canvas.Font.Assign(ACanvas.Font);
    bmp2.Canvas.Font.Color := TxtClr;
                                              // CapR
    TxtR := DrawVistaText(bmp2.Canvas, taLeftJustify, R2, DCaption, DWCaption, ACanvas.Font, AdvPages[PageIndex].Enabled, True, AntiAlias);

    //DrawText(bmp2.Canvas.Handle, PChar(DCaption), Length(DCaption), R2, DT_SINGLELINE or DT_VCENTER);
    //bmp.Canvas.Draw(CapR.Left, CapR.Top, bmp2);
    ACanvas.CopyMode := cmSrcCopy;
    ACanvas.CopyRect(CapR, bmp2.Canvas, Rect(0, 0, CapR.Right - CapR.Left, CapR.Bottom - CapR.Top));
    bmp2.Free;

    if (R.Left < TR.Left)  then
    begin
      R.Left := TR.Left;
    end;
    if (R.Right > TR.Right) then
    begin
      R.Right := TR.Right;
    end;

    if (bmp <> nil) then
    begin
      Canvas.CopyMode := cmSrcCopy;
      Canvas.CopyRect(R3, ACanvas, R3);
      bmp.Free;
    end;

    if not Assigned(Parent) then
      Exit;
   {
    R := ClientRect;
    rgn1 := CreateRectRgn(0, 0, 1, 1);
    rgn2 := CreateRectRgn(R.Right-1, 0, R.Right, 1);
    CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
    DeleteObject(rgn2);
    rgn2 := CreateRectRgn(0, R.Bottom - 1, 1, R.Bottom);
    CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
    DeleteObject(rgn2);
    rgn2 := CreateRectRgn(R.Right - 1, R.Bottom - 1, R.Right, R.Bottom);
    CombineRgn(rgn1, rgn1, rgn2, RGN_OR);

    SelectClipRgn(Canvas.Handle, rgn1);

    i := SaveDC(Canvas.Handle);
    p := ClientOrigin;
    Windows.ScreenToClient(Parent.Handle, p);
    p.x := -p.x;
    p.y := -p.y;
    MoveWindowOrg(Canvas.Handle, p.x, p.y);
    //SendMessage(Parent.Handle, WM_ERASEBKGND, Canvas.Handle, 0);
    SendMessage(Parent.Handle, WM_PAINT, Canvas.Handle, 0);
    if (Parent is TWinCtrl) then
      (Parent as TWinCtrl).PaintCtrls(Canvas.Handle, nil);
    RestoreDC(Canvas.Handle, i);

    SelectClipRgn(Canvas.Handle, 0);
    DeleteObject(rgn1);
    DeleteObject(rgn2);  }
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DrawAllTabs;
var
  i: Integer;
  R: TRect;
begin
  // Draw TabBackGround
  R := GetTabsArea;

  R.Bottom := ClientRect.Bottom;

  with FCurrentToolBarStyler.TabAppearance do
  begin
    if (BackGround.Color <> clNone) and (BackGround.ColorTo <> clNone) then
      DrawGradient(Canvas, BackGround.Color, BackGround.ColorTo, BackGround.Steps, R, BackGround.Direction = gdHorizontal)
    else if (BackGround.Color <> clNone) then
    begin
      Canvas.Brush.Color := BackGround.Color;
      Canvas.Pen.Color := BackGround.Color;
      Canvas.Rectangle(R.Left, R.Top, R.Right, R.Bottom);
    end;

    if FCaption.Visible and (Align in [daTop, daBottom]) then
    begin
      Canvas.Pen.Color := BlendColor(clWhite, BackGround.Color, 70);//clWhite;
      Canvas.MoveTo(R.Left, R.Top+1);
      Canvas.LineTo(R.Right, R.Top+1);
    end;
  end;
  
  DrawTabGroups;

 {
  R := Rect(25, 32, 160, 53);
  DrawVistaGradient(Canvas, R,FCurrentToolBarStyler.TabAppearance.ColorChecked, FCurrentToolBarStyler.TabAppearance.ColorCheckedTo, FCurrentToolBarStyler.TabAppearance.ColorMirrorChecked, FCurrentToolBarStyler.TabAppearance.ColorMirrorCheckedTo, clBlue,
    FCurrentToolBarStyler.TabAppearance.GradientChecked, FCurrentToolBarStyler.TabAppearance.GradientMirrorChecked, '', Font,
    Enabled, FCurrentToolBarStyler.RoundEdges);

    Canvas.Font.Name := 'Tahoma';
    Canvas.Font.Size := 8;
    Canvas.Font.Color := clBlack;
    DrawVistaText(Canvas, R, 'AAA', Canvas.Font, True);
  }
 { DrawVistaTab(Canvas, R,clBlue, FCurrentToolBarStyler.TabAppearance.ColorCheckedTo, FCurrentToolBarStyler.TabAppearance.ColorMirrorChecked, FCurrentToolBarStyler.TabAppearance.ColorMirrorCheckedTo, clBlack,
    FCurrentToolBarStyler.TabAppearance.GradientChecked, FCurrentToolBarStyler.TabAppearance.GradientMirrorChecked, '', Font,
    nil, -1, True, blGlyphLeft, False, False, True, False, dpRight);
  }

  for i := 0 to FAdvPages.Count - 1 do
    DrawTab(i);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DrawCaption;
var
  R, TxtR, MaxR, TabGpR: TRect;
  i: Integer;
  bmp: TBitMap;
  DrawTabGpRL, DrawTabGpRR: Boolean;
  aln: TAlignment;
begin
  if FCaption.Visible then
  begin
    R := GetCaptionRect;
    bmp := TBitMap.Create;
    bmp.Width := R.Right - R.Left;
    bmp.Height := R.Bottom - R.Top;

    with FCurrentToolBarStyler.PagerCaption do
    begin
      R.Bottom := R.Bottom + 1;
      DrawVistaGradient(bmp.Canvas, R, Color, ColorTo, ColorMirror, ColorMirrorTo, BorderColor,
        Gradient, GradientMirror, '', Font, {ImgList, ImageIndex, EnabledImg, Layout, }
        Enabled, False, FAntiAlias, False);
      R.Bottom := R.Bottom - 1;
    end;

    // Draw Text
    TxtR := R;
    if HideState then
      TxtR.Left := TxtR.Left + 5
    else
      TxtR.Left := TxtR.Left + FCaption.Indent;
    if Assigned(FQuickAccessToolBar) and not ShowQATBelow and not HideState then
    begin
      TxtR.Left := MaxQATRect.Left + FQuickAccessToolBar.Width;
    end;

    if not HideState then
      TxtR.Right := TxtR.Right - FCaption.RightIndent;

    MaxR := Rect(-1, -1, -1, -1);
    if not HideState then
    begin
      for i:= 0 to FTabGroups.Count-1 do
      begin
        DrawTabGpRL := True;
        DrawTabGpRR := True;
        TabGpR := GetTabGroupRect(i, DrawTabGpRL, DrawTabGpRR);
        if (TabGpR.Left > -1) and (TabGpR.Right > -1) then
        begin
          if (MaxR.Left = -1) then
            MaxR.Left := TabGpR.Left
          else
            MaxR.left := Min(MaxR.left, TabGpR.Left);
          if (MaxR.Right = -1) then
            MaxR.Right := TabGpR.Right
          else
            MaxR.Right := Max(MaxR.Right, TabGpR.Right);
        end;
      end;
    end;

    if (MaxR.Left > -1) and (MaxR.Right > -1) then
      TxtR.Left := MaxR.Right;

   { MaxR := Rect(-1, -1, -1, -1);
    for i:= 0 to FTabGroups.Count-1 do
    begin
      if IsTabGroupVisible(i) then
      begin
        TabGpR := GetTabGroupRect(i);
        if (TabGpR.Left > -1) and (TabGpR.Right > -1) then
        begin
          if (MaxR.Left = -1) then
            MaxR.Left := TabGpR.Left
          else
            MaxR.left := Min(MaxR.left, TabGpR.Left);
          if (MaxR.Right = -1) then
            MaxR.Right := TabGpR.Right
          else
            MaxR.Right := Max(MaxR.Right, TabGpR.Right);
        end;
      end;
    end;

    if (MaxR.Left > -1) and (MaxR.Right > -1) then
    begin
      ls := MaxR.Left - FCaption.Indent;
      rs := R.Right - MaxR.Right - FCaption.RightIndent;
      if (ls >= rs) then
      begin
        TxtR.Left := FCaption.Indent;
        TxtR.Right := MaxR.Left;
      end
      else
      begin
        TxtR.Left := MaxR.Right;
        TxtR.Right := R.Right - FCaption.RightIndent;
      end;  
    end;
    }
    bmp.Canvas.Font.Assign(FCurrentToolBarStyler.PagerCaption.Font);
    //Canvas.Font.Size := 8;
    //Canvas.Font.Style := [];
    bmp.Canvas.Font.Color := FCurrentToolBarStyler.PagerCaption.TextColor;

    if HideState then
      aln := taLeftJustify
    else
      aln := taCenter;
    DrawVistaText(bmp.Canvas, aln, TxtR, Caption.Caption, Caption.WideCaption, bmp.Canvas.Font, Enabled, True, AntiAlias);

    Canvas.Draw(R.Left, R.Top, bmp);
    bmp.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.Paint;
var
  R: TRect;
  c, ro, th: integer;
  PrtForm: TCustomForm;
  col: TColor;
begin
  inherited;

  R := ClientRect;


  with FCurrentToolBarStyler, Canvas do
  begin
   { if DockColor.ColorTo <> clNone then
      DrawGradient(Canvas, DockColor.Color, DockColor.ColorTo, DockColor.Steps, R, DockColor.Direction = gdHorizontal)
    else
    begin
      Pen.Color := DockColor.Color;
      Brush.Color := DockColor.Color;
      Rectangle(R);
    end;
    }
    if not BackGround.Empty then
    begin
      case BackGroundDisplay of
        bdTile:
          begin
            c := 1;
            ro := 1;
            while ro < Height - 2 do
            begin
              while c < width - 2 do
              begin
                Draw(c, ro, BackGround);
                c := c + BackGround.Width;
              end;
              c := 1;
              ro := ro + BackGround.Height;
            end;
          end;
        bdCenter:
          begin
            Draw((Width - BackGround.Width) div 2, (Height - BackGround.Height) div 2, BackGround);
          end;
        bdStretch:
          begin
            StretchDraw(Rect(R.Left + 2, R.Top + 2, R.Right - 2, R.Bottom - 2), BackGround);
          end;
      end;
    end;
  end;

  DrawCaption;

  DrawAllTabs; // Also drawTabGroups

  //DrawTabGroups;
  DrawTabScrollButtons;

  UpdateMDIButtonsShowing;

  if (csDesigning in ComponentState) and (FAdvPages.Count = 0) then
  begin
    Canvas.Font.Assign(self.Font);
    Canvas.Brush.Style := bsClear;
    th := Canvas.TextHeight('gh');
    Canvas.TextOut(10, Height div 2, 'Right-click and choose "New Page"');
    Canvas.TextOut(10, (Height div 2) + th,'to insert a new tabsheet');
    Canvas.Font.Style := [fsItalic];
    Canvas.TextOut(10, Height div 2 + 3*th, 'If no such right-click menu option appears');
    Canvas.TextOut(10, Height div 2 + 4*th, 'please install designtime package!');
  end;

  if FCaption.Visible and (FCaptionButtons <> []) then
  begin
    PrtForm := GetParentForm(Self);
    if Assigned(PrtForm) then
    begin
      if (FFormWindowState <> PrtForm.WindowState) then
      begin
        FFormWindowState := PrtForm.WindowState;
        UpdateCaptionButtons(True);
      end;
    end;
  end;

  if (AdvPageCount > 0) and (ActivePageIndex >= 0) and (ActivePageIndex < AdvPageCount) then
  begin
    R := AdvPages[ActivePageIndex].ClientRect;

    OffsetRect(R,AdvPages[ActivePageIndex].Left, AdvPages[ActivePageIndex].Top);

    col := Canvas.Pixels[R.Left, R.Bottom + 1];
    Canvas.Pen.Color := DarkenColor(FCurrentToolBarStyler.PageAppearance.ShadowColor, -15); //DarkenColor(col,10);
    Canvas.MoveTo(R.Left + 4, R.Bottom);
    Canvas.LineTo(R.Right , R.Bottom);
    Canvas.Pen.Color := DarkenColor(col,10);
    Canvas.LineTo(R.Right , R.Top + 4);

    Canvas.Pen.Color := DarkenColor(FCurrentToolBarStyler.PageAppearance.ShadowColor, -20); //DarkenColor(col, 5);
    Canvas.MoveTo(R.Left + 5, R.Bottom + 1);
    Canvas.LineTo(R.Right + 1, R.Bottom + 1);
    Canvas.Pen.Color := DarkenColor(col,5);
    Canvas.LineTo(R.Right + 1, R.Top + 5);

  end;


  with FCurrentToolBarStyler do
  begin
    if (Parent is TAdvToolBarForm) and not IsVista then
    begin
      Canvas.Pen.Color := CaptionAppearance.CaptionTextColor;

      if Canvas.Pen.Color = clWhite then
        Canvas.Pen.Color := clBlack;

      Canvas.Pen.Width := 1;
      Canvas.MoveTo(0,0);
      Canvas.LineTo(7,0);
      Canvas.MoveTo(0,1);
      Canvas.LineTo(4,1);
      Canvas.MoveTo(1,1);
      Canvas.LineTo(1,4);
      Canvas.MoveTo(0,0);
      Canvas.LineTo(0,7);

      Canvas.MoveTo(Width - 7,0);
      Canvas.LineTo(Width,0);

      Canvas.MoveTo(Width - 4,1);
      Canvas.LineTo(Width,1);

      Canvas.MoveTo(Width-2,1);
      Canvas.LineTo(Width-2,4);
      Canvas.MoveTo(Width-1,0);
      Canvas.LineTo(Width-1,7);

    end;
  end;

  (*
  with FCurrentToolBarStyler.TabAppearance do
  begin
    R := GetAdvPageRect;
    DrawVistaGradient(Canvas, R, ColorChecked, ColorCheckedTo, ColorMirrorChecked, ColorMirrorCheckedTo, BorderColorChecked,
      GradientChecked, GradientMirrorChecked, '', Font, {ImgList, ImageIndex, EnabledImg, Layout, }
      Enabled{, GetFocus = self.Handle,Pic}, FCurrentToolBarStyler.RoundEdges);
  end; *)
  //Canvas.Draw(0, 0, FMyImage);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.RemoveAdvPage(AdvPage: TAdvPage);
var
  i, ni: Integer;
begin
  i := FAdvPages.IndexOf(AdvPage);
  if (i >= 0) then
  begin
    if i < ActivePageIndex then
      ni := ActivePageIndex - 1
    else
      ni := ActivePageIndex;

    if (ActivePage = AdvPage) then
      SelectNextPage(True);
    FAdvPages.Delete(i);
    AdvPage.FAdvToolBarPager := nil;  

    ActivePageIndex := ni;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetAlign(const Value: TDockAlign);
var
  i: integer;
begin
  if Value <> FDockAlign then
  begin
    FDockAlign := Value;
    case FDockAlign of
      daLeft: inherited Align := alLeft;
      daTop: inherited Align := alTop;
      daRight: inherited Align := alRight;
      daBottom: inherited Align := alBottom;
    end;

    for i := 0 to FAdvPages.Count - 1 do
    begin
      //TAdvCustomToolBar(FToolBars[i]).Position := FDockAlign;
    end;  
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetParent(AParent: TWinControl);
begin
  if (AParent is TAdvDockPanel) or (AParent is TAdvCustomToolBar) or (AParent is TAdvToolBarPager) or (AParent is TAdvPage) then
    raise Exception.Create('Invalid Parent');

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetToolBarStyler(
  const Value: TCustomAdvToolBarStyler);
var
  i, j: integer;
begin
  if (FToolBarStyler <> Value) or (Value = nil) then
  begin
    if Assigned(FToolBarStyler) and (FToolBarStyler <> FInternalToolBarStyler) then
      FToolBarStyler.RemoveControl(self);

    FToolBarStyler := Value;

    if FToolBarStyler = nil then
    begin
      FCurrentToolBarStyler := FInternalToolBarStyler;
    end
    else
    begin
      FCurrentToolBarStyler := FToolBarStyler;
      FToolBarStyler.AddControl(self);
    end;

    if not (csDestroying in ComponentState) and not (csLoading in ComponentState) then
    begin
      for i := 0 to FAdvPages.Count - 1 do
      begin
        for j:= 0 to AdvPages[i].ControlCount - 1 do
        begin
          if (AdvPages[i].Controls[j] is TAdvToolBar) then
            TAdvCustomToolBar(AdvPages[i].Controls[j]).ParentStyler := TAdvCustomToolBar(AdvPages[i].Controls[j]).ParentStyler;
        end;
        AdvPages[i].Invalidate;
      end;
    end;
    UpdateMe(0);
    PopupMenu := PopupMenu;   // Refresh Styler
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetAdvToolBarPageCount: integer;
begin
  Result := FAdvPages.Count;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetAdvPages(index: integer): TAdvPage;
begin
  Result := TAdvPage(FAdvPages[index]);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetAdvPageBounds(AdvPage: TAdvPage;
  var ALeft, ATop, AWidth, AHeight: Integer);
begin
end;

//------------------------------------------------------------------------------
procedure TAdvToolBarPager.WMPaint(var Message: TWMPaint);
var
  DC, MemDC: HDC;
  MemBitmap, OldBitmap: HBITMAP;
  PS: TPaintStruct;
begin
  if not FDoubleBuffered or (Message.DC <> 0) then
  begin
    if not (csCustomPaint in ControlState) and (ControlCount = 0) then
      inherited
    else
      PaintHandler(Message);
  end
  else
  begin
    DC := GetDC(0);
    MemBitmap := CreateCompatibleBitmap(DC, ClientRect.Right, ClientRect.Bottom);
    ReleaseDC(0, DC);
    MemDC := CreateCompatibleDC(0);
    OldBitmap := SelectObject(MemDC, MemBitmap);
    try
      DC := BeginPaint(Handle, PS);
      Perform(WM_ERASEBKGND, MemDC, MemDC);
      Message.DC := MemDC;
      WMPaint(Message);
      Message.DC := 0;
      BitBlt(DC, 0, 0, ClientRect.Right, ClientRect.Bottom, MemDC, 0, 0, SRCCOPY);
      EndPaint(Handle, PS);
    finally
      SelectObject(MemDC, OldBitmap);
      DeleteDC(MemDC);
      DeleteObject(MemBitmap);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.WMSize(var Message: TWMSize);
begin
  inherited;
  SetAllPagesPosition;
  UpdateTabSizes;
  InitializeScroller;
  UpdateCaptionButtons(False);
  UpdateMDIButtons(False);
  if Assigned(FQuickAccessToolBar) then
  begin
    FQuickAccessToolBar.UpdateSize;
    FQuickAccessToolBar.UpdateControlsVisiblity;
    FQuickAccessToolBar.UpdateControlsPos;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetPopupMenuEx(const Value: TPopupMenu);
begin
  Inherited PopupMenu := Value;
  if Assigned(PopupMenu) and (PopupMenu is TAdvPopupMenu) and Assigned(FCurrentToolBarStyler) then
    TAdvPopupMenu(PopupMenu).MenuStyler := FCurrentToolBarStyler.CurrentAdvMenuStyler;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMShowingChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMVisibleChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetPopupMenuEx: TPopupMenu;
begin
  Result := Inherited PopupMenu;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetShowNonSelectedTabs(const Value: Boolean);
begin
  FShowNonSelectedTabs := Value;
  InvalidateTab(-1);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMControlChange(var Message: TCMControlChange);
begin
  inherited;

  with Message do
  begin
    if (Control is TAdvPage) then
    begin
      if Inserting then
        //InsertControl(Control)
      else
        //RemoveControl(Control);
    end;

    if (Control is TAdvQuickAccessToolBar) then
    begin
      if Inserting then
      begin
        FQuickAccessToolBar := TAdvQuickAccessToolBar(Control);
      end
      else
      begin
        FQuickAccessToolBar := nil;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMControlListChange(
  var Message: TCMControlListChange);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMMouseEnter(var Msg: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMMouseLeave(var Message: TMessage);
var
  P: TPoint;
  R: TRect;
begin
  inherited;

  if FScrollerHoverLeftBtn or FScrollerHoverRightBtn then
  begin
    FScrollerHoverLeftBtn := false;
    FScrollerHoverRightBtn := false;
    DrawTabScrollButtons;
  end;

  FHintPageIndex := -1;

  if (csDesigning in ComponentState) then
    Exit;

  // work around to avoid false call  
  GetCursorPos(P);
  P := ScreenToClient(P);
  R := GetTabsRect;
  R.Bottom := R.Bottom - 4;
  if PtInRect(R, P) then
    Exit;

  if (FHotPageIndex >= AdvPageCount) then
    FHotPageIndex := -1;
    
  if (FHotPageIndex = FActivePageIndex) then
  begin
    FHotPageIndex := -1;
    Invalidate;
  end
  else if (FHotPageIndex >= 0) then
  begin
    if not Assigned(AdvPages[FHotPageIndex].FTimer) then
    begin
      AdvPages[FHotPageIndex].FTimer := TTimer.Create(self);
      AdvPages[FHotPageIndex].FTimer.OnTimer := AdvPages[FHotPageIndex].TimerProc;
      AdvPages[FHotPageIndex].FTimer.Interval := GlowSpeed;
      AdvPages[FHotPageIndex].FTimer.Enabled := true;
    end;

    AdvPages[FHotPageIndex].FTimeInc := -20;
    AdvPages[FHotPageIndex].FGlowState := gsHover;
    FHotPageIndex := -1;
    InvalidateTab(-1);
  end;
end;

//------------------------------------------------------------------------------
procedure TAdvToolBarPager.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);

var
  P: TPoint;
  Tab: Integer;
  hMenuHandle: hMENU;
  hMenuItem: dWord;
  i: Integer;
begin
  inherited;
  P := Point(X, Y);

  FDownPageIndex := -1;

  if (Button = mbRight) and (FCaption.Visible) and PtInRect(GetAvailableCaptionRect, p) then
  begin
     p.X := X;
     p.Y := Y;
     p := ClientToScreen(p);

     hMenuHandle := GetSystemMenu(Parent.Handle, False);
     hMenuItem := LongWord(Windows.TrackPopupMenu(hMenuHandle, TPM_LEFTBUTTON or
                                               TPM_RIGHTBUTTON or TPM_RETURNCMD,
                                               p.X, p.Y, 0, Parent.Handle, nil));
     if hMenuItem > 0 then
       SendMessage(Parent.Handle, WM_SYSCOMMAND, hMenuItem, 0);
     Exit;
  end;


  i := PtOntTabGroup(X, Y);
  if (FCaption.Visible) and PtInRect(GetAvailableCaptionRect, p) and FCanMove and (i < 0) then
  begin
    ReleaseCapture;
    SendMessage(GetParentForm(Self).Handle, WM_SYSCOMMAND, SC_MOVE+1, 0);
    Exit;
  end;

  if FTabShortCutHintShowing then
  begin
    HideShortCutHintOfAllPages(True);
  end;

  if PtInRect(GetTabsArea, p) then
  begin
    Tab := PTOnTab(X, Y);
    if (Tab >= 0) then
    begin
      if Assigned(FOnTabClick) then
        FOnTabClick(Self, Tab);

      {if (Tab = ActivePageIndex) then
      begin
        Inc(FClickCount);
        FDblClickTimer.Enabled := True;
      end;}

      if (Tab <> ActivePageIndex) and AdvPages[Tab].TabEnabled then
      begin
        // Select Tab
        ChangeActivePage(Tab);
        if not (csDesigning in ComponentState) and (Tab >= 0) and (Tab < AdvPageCount) then
        begin
          if not Assigned(AdvPages[Tab].FTimer) then
          begin
            AdvPages[Tab].FTimer := TTimer.Create(self);
            AdvPages[Tab].FTimer.OnTimer := AdvPages[Tab].TimerProc;
            AdvPages[Tab].FTimer.Interval := GlowSpeed;
            AdvPages[Tab].FTimer.Enabled := true;
          end;
          AdvPages[Tab].FTimeInc := +20;
          AdvPages[Tab].FGlowState := gsPush;
        end;
        Invalidate;

        FClickCount := -1;
      end
      else
      begin
        FDownPageIndex := Tab;
        InvalidateTab(-1);
      end;

      if not FExpanded then
      begin
        //Expand;
        if IsFloatingRibbonShowing then
        begin
          if (FClickCount < 2) then
            HideFloatingRibbon;
        end
        else
          ShowFloatingRibbon;
      end;
    end
    else
    begin
      if PtOnTabScrollLeftBtn(X, Y) then
      begin
        FScrollerDownLeftBtn := true;
        DrawTabScrollBtnLeft;
      end;
      if PtOnTabScrollRightBtn(X, Y) then
      begin
        FScrollerDownRightBtn := true;
        DrawTabScrollBtnRight;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.MouseMove(Shift: TShiftState; X, Y: Integer);
var
  P: TPoint;
  Tab: Integer;
begin
  inherited;

  if (csDesigning in ComponentState) then
    Exit;

  if (FHotPageIndex >= AdvPageCount) then
    FHotPageIndex := -1;
    
  P := Point(X, Y);

  if PtInRect(GetTabsArea, p) then
  begin
    Tab := PTOnTab(X, Y);
    if (Tab >= 0) and (Tab <> FHotPageIndex) then
    begin
      if (FDownPageIndex >= 0) then
      begin
        FDownPageIndex := -1;
        InvalidateTab(-1);
      end;

      if (FHotPageIndex >= 0) then
      begin
        OnExitTab(FHotPageIndex);
        begin
          if not Assigned(AdvPages[FHotPageIndex].FTimer) then
          begin
            AdvPages[FHotPageIndex].FTimer := TTimer.Create(self);
            AdvPages[FHotPageIndex].FTimer.OnTimer := AdvPages[FHotPageIndex].TimerProc;
            AdvPages[FHotPageIndex].FTimer.Interval := GlowSpeed;
            AdvPages[FHotPageIndex].FTimer.Enabled := true;
          end;
          AdvPages[FHotPageIndex].FTimeInc := -20;

          AdvPages[FHotPageIndex].FGlowState := gsHover;
          FHotPageIndex := -1;
          InvalidateTab(-1);
        end;
      end;

      // Hot Tab
      OnEnterTab(Tab);

      //InvalidateTab(-1);
      //if (Tab <> FActivePageIndex) then
      if AdvPages[Tab].TabEnabled then      
      begin
        FHotPageIndex := Tab;
        FOldHotPageIndex := FHotPageIndex;
        if not Assigned(AdvPages[FHotPageIndex].FTimer) then
        begin
          AdvPages[FHotPageIndex].FTimer := TTimer.Create(self);
          AdvPages[FHotPageIndex].FTimer.OnTimer := AdvPages[FHotPageIndex].TimerProc;
          AdvPages[FHotPageIndex].FTimer.Interval := GlowSpeed;
          AdvPages[FHotPageIndex].FTimer.Enabled := true;
        end;

        AdvPages[FHotPageIndex].FTimeInc := 20;
        Invalidate;
        AdvPages[FHotPageIndex].FGlowState := gsHover;

     { end
      else if (FHotPageIndex >= 0) then
      begin
        OnExitTab(FHotPageIndex);
        begin
          if not Assigned(AdvPages[FHotPageIndex].FTimer) then
          begin
            AdvPages[FHotPageIndex].FTimer := TTimer.Create(self);
            AdvPages[FHotPageIndex].FTimer.OnTimer := AdvPages[FHotPageIndex].TimerProc;
            AdvPages[FHotPageIndex].FTimer.Interval := GlowSpeed;
            AdvPages[FHotPageIndex].FTimer.Enabled := true;
          end;
          AdvPages[FHotPageIndex].FTimeInc := -20;

          AdvPages[FHotPageIndex].FGlowState := gsHover;
          FHotPageIndex := -1;
          InvalidateTab(-1);
        end; }
      end;

      if (FHintPageIndex <> Tab) then
      begin
        FHintPageIndex := Tab;
        Application.CancelHint;
      end;
    end
    else if (Tab < 0) and (FHotPageIndex >= 0) then
    begin
      if (FDownPageIndex >= 0) then
      begin
        FDownPageIndex := -1;
        InvalidateTab(-1);
      end;
      OnExitTab(FHotPageIndex);
      if (FHotPageIndex = FActivePageIndex) and false then
      begin
        FHotPageIndex := -1;
        Invalidate;
      end
      else
      begin
        if not Assigned(AdvPages[FHotPageIndex].FTimer) then
        begin
          AdvPages[FHotPageIndex].FTimer := TTimer.Create(self);
          AdvPages[FHotPageIndex].FTimer.OnTimer := AdvPages[FHotPageIndex].TimerProc;
          AdvPages[FHotPageIndex].FTimer.Interval := GlowSpeed;
          AdvPages[FHotPageIndex].FTimer.Enabled := true;
        end;
        AdvPages[FHotPageIndex].FTimeInc := -20;

        AdvPages[FHotPageIndex].FGlowState := gsHover;
        FHotPageIndex := -1;
        InvalidateTab(-1);
      end;
    end;

    if (Tab < 0) then
    begin
      FHintPageIndex := -1;
      Application.CancelHint;
    end;

    // Checking for TabScrollButtons
    if PtOnTabScrollLeftBtn(X, Y) then
    begin
      if not FScrollerHoverLeftBtn then
      begin
        FScrollerHoverLeftBtn := true;
        DrawTabScrollBtnLeft;
      end;
    end
    else if FScrollerHoverLeftBtn then
    begin
      FScrollerHoverLeftBtn := false;
      DrawTabScrollBtnLeft;
    end;

    if PtOnTabScrollRightBtn(X, Y) then
    begin
      if not FScrollerHoverRightBtn then
      begin
        FScrollerHoverRightBtn := true;
        DrawTabScrollBtnRight;
      end;
    end
    else if FScrollerHoverRightBtn then
    begin
      FScrollerHoverRightBtn := false;
      DrawTabScrollBtnRight;
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.MouseUp(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  P: TPoint;
  i, j: Integer;
begin
  inherited;
  P := Point(X, Y);

  if (FDownPageIndex >= 0) then
  begin
    FDownPageIndex := -1;
    InvalidateTab(-1);
  end;

  if PtInRect(GetTabsArea, p) then
  begin
    if PtOnTabScrollLeftBtn(X, Y) then
    begin
      FScrollerDownLeftBtn := false;
      DrawTabScrollBtnLeft;
      OnScrollLeftBtnClick(nil);
    end
    else if PtOnTabScrollRightBtn(X, Y) then
    begin
      FScrollerDownRightBtn := false;
      DrawTabScrollBtnRight;
      OnScrollRightBtnClick(nil);
    end;

    i := PTOnTab(X, Y);
    if (i >= 0) then
    begin
      if (i = ActivePageIndex) then
      begin
        Inc(FClickCount);
        FDblClickTimer.Enabled := True;
      end;
    end;

  end
  else
  begin
    i := PtOntTabGroup(X, Y);
    if (i >= 0) then
    begin
      for j := FTabGroups.Items[i].TabIndexStart to FTabGroups.Items[i].TabIndexEnd do
      begin
        if TAdvPage(FAdvPages[j]).Enabled and TAdvPage(FAdvPages[j]).TabVisible then
        begin
          if (ActivePageIndex <> j) then
            ActivePageIndex := j;
          break;
        end;
      end;

      if Assigned(FOnTabGroupClick) then
        FOnTabGroupClick(Self, i);
    end;
  end;


  if (FClickCount >= 2) and HidePagesOnDblClick then
  begin
    if FExpanded then
      Collaps
    else
      Expand;

    FDblClickTimer.Enabled := False;
    FClickCount := 0;
  end;
  
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.GetChildren(Proc: TGetChildProc;
  Root: TComponent);
var
  I: Integer;
  Control: TControl;
begin
  for I := 0 to FAdvPages.Count - 1 do Proc(TComponent(FAdvPages[I]));

  for I := 0 to ControlCount - 1 do
  begin
    Control := Controls[I];
    if (Control.Owner = Root) and (FAdvPages.IndexOf(Control) < 0) then Proc(Control);
  end;

end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.FindNextPage(CurPage: TAdvPage; GoForward,
  CheckTabVisible: Boolean): TAdvPage;
var
  i, j, CurIndex: Integer;
begin
  Result := nil;
  CurIndex := FAdvPages.IndexOf(CurPage);
  if (CurPage <> nil) and (CurIndex >= 0) then
    Exit;
    
  if GoForward then
  begin
    i := CurIndex;
    j := 1;
    while (j < FAdvPages.Count) do
    begin
      Inc(i);    
      if (i >= FAdvPages.Count) then
        i := 0;
      if (CheckTabVisible and AdvPages[i].TabVisible) or not CheckTabVisible then
      begin
        Result := AdvPages[i];
        Break;
      end;
      Inc(j);
    end;
  end
  else  // BackWard
  begin
    i := CurIndex;
    j := 1;
    while (j < FAdvPages.Count) do
    begin
      dec(i);
      if (i >= FAdvPages.Count) then
        i := 0;
      if (i < 0) then
        i := FAdvPages.Count-1;
      if (CheckTabVisible and AdvPages[i].TabVisible) or not CheckTabVisible then
      begin
        Result := AdvPages[i];
        Break;
      end;
      Inc(j);
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetActivePage: TAdvPage;
begin
  Result := nil;
  if (ActivePageIndex >= 0) and (ActivePageIndex < FAdvPages.Count) then
    Result := AdvPages[FActivePageIndex];
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetActivePageIndex: Integer;
begin
  Result := FActivePageIndex;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SelectNextPage(GoForward: Boolean);
var
  i, j: Integer;
begin
  if (ActivePageIndex < 0) then
    Exit;
    
  if GoForward then
  begin
    i := ActivePageIndex;
    j := 1;
    while (j < FAdvPages.Count) do
    begin
      Inc(i);    
      if (i >= FAdvPages.Count) then
        i := 0;
      if (ActivePage <> AdvPages[i]) and AdvPages[i].TabVisible and AdvPages[i].TabEnabled then
      begin
        ActivePageIndex := i;
        Break;
      end;
      Inc(j);
    end;
  end
  else  // BackWard
  begin
    i := ActivePageIndex;
    j := 1;
    while (j < FAdvPages.Count) do
    begin
      dec(i);
      if (i >= FAdvPages.Count) then
        i := 0;
      if (i < 0) then
        i := FAdvPages.Count-1;
      if (ActivePage <> AdvPages[i]) and AdvPages[i].TabVisible and AdvPages[i].TabEnabled then
      begin
        ActivePageIndex := i;
        Break;
      end;
      Inc(j);
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.IndexOfPage(AdvPage: TAdvPage): Integer;
begin
  Result := FAdvPages.IndexOf(AdvPage);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetActivePage(const Value: TAdvPage);
begin
  if (FAdvPages.IndexOf(Value) >= 0) then
    ActivePageIndex := FAdvPages.IndexOf(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.ChangeActivePage(PageIndex: Integer);
var
  aForm: TCustomForm;
  AllowChange: Boolean;
begin
  if (PageIndex >= 0) and (PageIndex < FAdvPages.Count) and (PageIndex <> ActivePageIndex) then
  begin
    AllowChange := True;
    if Assigned(FOnChanging) then
      FOnChanging(Self, ActivePageIndex, PageIndex, AllowChange);

    if not AllowChange then
      Exit;  

    if (ActivePageIndex >= 0) and (ActivePageIndex < FAdvPages.Count) then
    begin
      AdvPages[FActivePageIndex].Visible := False;
      if not Expanded then
        DestroyFloatingRibbon;
    end;

    FActivePageIndex := PageIndex;
    AdvPages[FActivePageIndex].Visible := True;
    AdvPages[FActivePageIndex].BringToFront;

    if Assigned(FOnChange) then
      FOnChange(Self);
      
    if (csDesigning in ComponentState) and not (csLoading in ComponentState) then
    begin
      aForm := GetParentForm(Self);
      if (aForm <> nil) and (aForm.Designer <> nil) then
        aForm.Designer.Modified;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetActivePageIndex(const Value: Integer);
var
  R: TRect;
begin
{  if (Value >= 0) and (Value < FAdvPages.Count) and (Value <> ActivePageIndex) then
  begin
    if (ActivePageIndex >= 0) and (ActivePageIndex < FAdvPages.Count) then
    begin
      AdvPages[FActivePageIndex].Visible := False;
    end;

    FActivePageIndex := Value;
    AdvPages[FActivePageIndex].Visible := True;
    AdvPages[FActivePageIndex].BringToFront;
 }
    ChangeActivePage(Value);
    R := GetTabsArea;
    InvalidateRect(Handle, @R, True);
 // end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetTabSettings(const Value: TATBTabSettings);
begin
  FTabSettings.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetCaption(const Value: TAdvPageCaption);
begin
  FCaption.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetAllPagesPosition;
var
  i: Integer;
begin
  for i:= 0 to FAdvPages.Count-1 do
  begin
    SetPagePosition(TAdvPage(FAdvPages[i]));
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetCaptionRect: TRect;
begin
  Result := Rect(-1, -1, -1, -1);
  if FCaption.Visible then
  begin
    Result := ClientRect;
    Result.Bottom := Result.Top + Caption.Height;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetAvailableCaptionRect: TRect;
begin
  Result := GetCaptionRect;
  if FCaption.Visible then
  begin
    Result.Left := Result.Left {+ FCaption.Indent};
    Result.Right := Result.Right {- FCaption.RightIndent};
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetAdvPageRect: TRect;
begin
  Result := ClientRect;
  if (Align in [daTop, daBottom]) then
  begin
    if (FCaption.Visible) then
      Result.Top := Result.Top + FCaption.Height;
    if ShowQATBelow then
      Result.Bottom := Result.Bottom - GetQATHeight;

    Result.Top := Result.Top + TabSettings.Height;
    Result.Left := Result.Left + ADVPAGE_OFFSET + FPageLeftMargin;
    Result.Right := Result.Right - ADVPAGE_OFFSET - FPageRightMargin;
    Result.Bottom := Result.Bottom - ADVPAGE_OFFSET-1;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetPagePosition(AdvPage: TAdvPage);
var
  R: TRect;
begin
  if (AdvPage <> nil) and (FAdvPages.IndexOf(AdvPage) >= 0) then
  begin
    if Align in [daTop, daBottom] then
    begin
      R := GetAdvPageRect;

      AdvPage.Left := R.Left;
      AdvPage.Top := R.Top;
      AdvPage.Width := R.Right - R.Left;
      AdvPage.Height := R.Bottom - R.Top;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.PTOnTab(X, Y: Integer): Integer;
var
  i: Integer;
  P: TPoint;
  TabR: TRect;
begin
  Result := -1;
  P := Point(X, Y);
  for i:= 0 to FAdvPages.Count-1 do
  begin
    TabR := GetTabRect(i);
    if PtInRect(TabR, P) then
    begin
      Result := i;
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

// Independent to Start/End Margins and Scroller
function TAdvToolBarPager.GetTabsArea: TRect;
begin
  Result := ClientRect;
  if Align in [daTop, daBottom] then
  begin
    if FCaption.Visible then
      Result.Top := Result.Top + FCaption.Height;

    Result.Bottom := Result.Top + FTabSettings.Height;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabsRect: TRect;
begin
  Result := ClientRect;
  if Align in [daTop, daBottom] then
  begin
    if FCaption.Visible then
      Result.Top := Result.Top + FCaption.Height;

    Result.Top := Result.Top + 4;
    Result.Bottom := Result.Top + FTabSettings.Height;
    Result.Left := Result.Left + FTabSettings.StartMargin + PageLeftMargin + ADVPAGE_OFFSET;
    Result.Right := Result.Right - FTabSettings.EndMargin - PageRightMargin - ADVPAGE_OFFSET;
    
    if FAutoMDIButtons and not (csDesigning in ComponentState) then
      Result.Right := Result.Right - ((FMDIButtonsWidth + FMDIButtonsSpace)*3) - 5;
    if FTabScroller.Visible then
      Result.Right := Result.Right - SCROLLER_SIZE;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabVisibleRect(Page: TAdvPage): TRect;
begin
  Result := GetTabVisibleRect(FAdvPages.IndexOf(Page));
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabVisibleRect(PageIndex: Integer): TRect;
var
  R, TR: TRect;
begin                                      
  Result := Rect(-1, -1, -1, -1);
  R := GetTabRect(PageIndex);
  TR := GetTabsRect;
  if ((R.Left <= -1) and (R.Right <= -1)) or (((R.Left < TR.Left) and (R.Right < TR.Left)) or ((R.Left > TR.Right) and (R.Right > TR.Right))) then
  begin
    Exit;
  end;

  if (R.Left < TR.Left) then
  begin
    R.Left := TR.Left;
  end;

  if (R.Right > TR.Right) then
  begin
    R.Right := TR.Right;
  end;
  Result := R;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabRect(PageIndex: Integer): TRect;
begin
  Result := GetTabRect(0, PageIndex, True);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabRect(StartIndex, PageIndex: Integer; ConsiderTabScroller: Boolean): TRect;
var
  {i, TbW, j, Sp, fdW, ImgTxtSp, k: Integer;}
  CR{, R, R2}: TRect;

begin
  Result := Rect(-1, -1, -1, -1);
  //Sp := FCurrentTabSpacing; // FTabSettings.Spacing;

  if (PageIndex >= 0) and (PageIndex < FAdvPages.Count) then
  begin
    if not AdvPages[PageIndex].TabVisible then
      Exit;

    CR := GetTabsRect;

    Result := Rect(AdvPages[PageIndex].TabLeft, CR.Top, AdvPages[PageIndex].TabLeft + AdvPages[PageIndex].TabWidth, CR.Bottom);
    Exit;

    (*
    if Align in [daTop, daBottom] then
    begin
      j := 0;
      for i := StartIndex to PageIndex do
      begin
        if not AdvPages[i].TabVisible then
          Continue;

        {TabAppearance := FCurrentToolBarStyler.TabAppearance;
        k := GroupOfTab(i);
        if (k >= 0) and (k < FTabGroups.Count) then
        begin
          if not FTabGroups.Items[k].DefaultAppearance then
            TabAppearance := FTabGroups.Items[k].GroupAppearance.TabAppearance
          else
            TabAppearance := FCurrentToolBarStyler.GroupAppearance.TabAppearance;
        end;

        Canvas.Font.Assign(TabAppearance.Font);

        if (AdvPages[i].Caption <> '') or (AdvPages[i].WideCaption <> '') then
        begin
          R2 := Rect(0,0, 1000, 100);
          if (AdvPages[i].Caption <> '') then
            DrawText(Canvas.Handle,PChar(AdvPages[i].Caption),Length(AdvPages[i].Caption), R2, DT_CALCRECT or DT_LEFT or DT_SINGlELINE)
          else
          begin
            DrawTextW(Canvas.Handle,PWideChar(AdvPages[i].WideCaption),Length(AdvPages[i].WideCaption), R2, DT_CALCRECT or DT_LEFT or DT_SINGLELINE);
          end;
        end
        else
          R2 := Rect(0, 0, 0, 0);

        //R2 := DrawVistaText(Canvas, R2, AdvPages[i].Caption, Canvas.Font, AdvPages[PageIndex].Enabled, False);
        TbW := TabSettings.LeftMargin + R2.Right+ fdW + TabSettings.RightMargin;

        if (Assigned(FImages) or Assigned(DisabledImages)) and (AdvPages[i].ImageIndex >= 0) then
        begin
          if AdvPages[i].Enabled then
          begin
            if Assigned(FImages) then
              TbW := TbW + FImages.Width + ImgTxtSp;
          end
          else
          begin
            if Assigned(FDisabledImages) then
              TbW := TbW + FDisabledImages.Width + ImgTxtSp
            else if Assigned(FImages) then
              TbW := TbW + FImages.Width + ImgTxtSp;
          end;
        end;}

        TbW := AdvPages[i].TabWidth;

        //if ((CR.Left + TbW) > (CR.Right - ADVPAGE_OFFSET)) then
          //Break;

        if FTabScroller.Visible and ConsiderTabScroller then
        begin
          if (j >= FTabScroller.Position) then
          begin
            R := Rect(CR.Left, CR.Top, CR.Left + TbW, CR.Bottom);
            if (i = PageIndex) then
              Result := R;
            CR.Left := CR.Left + TbW + Sp;
          end;
        end
        else
        begin
          R := Rect(CR.Left, CR.Top, CR.Left + TbW, CR.Bottom);
          if (i = PageIndex) then
            Result := R;
          CR.Left := CR.Left + TbW + Sp;
        end;
        Inc(j);
      end;
    end;
    *)
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabRect(Page: TAdvPage): TRect;
begin
  Result := GetTabRect(FAdvPages.IndexOf(Page));
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.TabInDisplayRange(PageIndex: Integer): Boolean;
begin
  Result := False;
  if (PageIndex >= 0) and (PageIndex < FAdvPages.Count) then
  begin
    if not AdvPages[PageIndex].TabVisible then
      Exit;
    if (PageIndex >= 0) then
      Result := True;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetLargestTabIndex(ConsiderGroupTabs: Boolean): Integer;
var
  i, w: Integer;
begin
  Result := -1;
  w := 0;
  for i := 0 to AdvPageCount-1 do
  begin
    if AdvPages[i].TabVisible and (w < AdvPages[i].TabWidth) and
    (ConsiderGroupTabs or (not ConsiderGroupTabs and (GroupOfTab(i) < 0))) then
    begin
      w := AdvPages[i].TabWidth;
      Result := i;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetSmallestExpandableTabIndex(PriorityGroupTabs: Boolean): Integer;
var
  i, w, gw, TabGroup: Integer;
  FoundGTab: Boolean;
begin
  Result := -1;
  w := 1500;
  gw := 1500;
  FoundGTab := False;
  for i := 0 to AdvPageCount-1 do
  begin
    if AdvPages[i].TabVisible and (AdvPages[i].TabClientWidth < AdvPages[i].TabRealClientWidth) then
    begin
      if not PriorityGroupTabs then
      begin
        if (w > AdvPages[i].TabClientWidth) then
        begin
          w := AdvPages[i].TabClientWidth;
          Result := i;
        end;
      end
      else
      begin
        TabGroup := GroupOfTab(i);

        if (w > AdvPages[i].TabClientWidth) and (TabGroup < 0) then
        begin
          w := AdvPages[i].TabClientWidth;
          if not FoundGTab then
            Result := i;
        end;

        if (gw > AdvPages[i].TabClientWidth) and (TabGroup >= 0) then
        begin
          gw := AdvPages[i].TabClientWidth;
          Result := i;
          FoundGTab := True;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetRealTabWidth(TabIndex: Integer; var TabClientWidth: Integer): Integer;
var
  TbW, fdW, ImgTxtSp, k: Integer;
  R2: TRect;
  TabAppearance: TCustomTabAppearance;
  AFont: TFont;
begin
  Result := 0;
  if (TabIndex < 0) or (TabIndex >= AdvPageCount) then
    Exit;

  fdW := 5;
  ImgTxtSp := IMG_SPACE;
  TabAppearance := FCurrentToolBarStyler.TabAppearance;
  k := GroupOfTab(TabIndex);
  if (k >= 0) and (k < FTabGroups.Count) then
  begin
    if not FTabGroups.Items[k].DefaultAppearance then
      TabAppearance := FTabGroups.Items[k].GroupAppearance.TabAppearance
    else
      TabAppearance := FCurrentToolBarStyler.GroupAppearance.TabAppearance;
  end;

  AFont := TFont.Create;
  AFont.Assign(Canvas.Font);
  Canvas.Font.Assign(TabAppearance.Font);

  if (AdvPages[TabIndex].Caption <> '') or (AdvPages[TabIndex].WideCaption <> '') then
  begin
    R2 := Rect(0,0, 1000, 100);
    if (AdvPages[TabIndex].Caption <> '') then
    begin
      DrawText(Canvas.Handle,PChar(AdvPages[TabIndex].Caption),Length(AdvPages[TabIndex].Caption), R2, DT_CALCRECT or DT_LEFT or DT_SINGlELINE);
      fdw := Max(fdw, Length(AdvPages[TabIndex].Caption));
    end
    else
    begin
      DrawTextW(Canvas.Handle,PWideChar(AdvPages[TabIndex].WideCaption),Length(AdvPages[TabIndex].WideCaption), R2, DT_CALCRECT or DT_LEFT or DT_SINGLELINE);
      fdw := Max(fdw, Length(AdvPages[TabIndex].WideCaption));
    end;
  end
  else
    R2 := Rect(0, 0, 0, 0);

  if (AntiAlias = aaNone) then
  begin
    fdw := 2;
  end
  else
  begin
    fdw := fdw + Max(0, (Canvas.Font.Size - 8));
  end;
  //TbW := TabSettings.LeftMargin + R2.Right+ fdW + TabSettings.RightMargin;
  TbW := R2.Right+ fdW;

  if (Assigned(FImages) or Assigned(DisabledImages)) and (AdvPages[TabIndex].ImageIndex >= 0) then
  begin
    if AdvPages[TabIndex].Enabled then
    begin
      if Assigned(FImages) then
        TbW := TbW + FImages.Width + ImgTxtSp;
    end
    else
    begin
      if Assigned(FDisabledImages) then
        TbW := TbW + FDisabledImages.Width + ImgTxtSp
      else if Assigned(FImages) then
        TbW := TbW + FImages.Width + ImgTxtSp;
    end;
  end;

  TabClientWidth := TbW;
  TbW := TabSettings.LeftMargin + TbW + TabSettings.RightMargin;

  Canvas.Font.Assign(AFont);
  Result := TbW;
  AFont.Free;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabsWidth(FromIndex, ToIndex: Integer): Integer;
var
  i: Integer;
begin
  Result := 0;
  if (FromIndex < 0) or (ToIndex >= AdvPageCount) then
    Exit;

  for i := FromIndex to ToIndex do
  begin
    if AdvPages[i].TabVisible then
    begin
      Result := Result + AdvPages[i].TabWidth;
      if (i < AdvPageCount-1) then
        Result := Result + FCurrentTabSpacing;
    end;  
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTotalTabsWidth: Integer;
begin
  Result := GetTabsWidth(0, AdvPageCount-1);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetMinTabWidth: Integer;
begin
  Result := 24;  // TODO: have to set it properly
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.AnyTabCanBeShrunk(ConsiderGroupTabs: Boolean): Boolean;
var
  i: Integer;
begin
  Result := False;
  for i:= 0 to AdvPageCount-1 do
  begin
    if AdvPages[i].TabVisible then
    begin
      if ConsiderGroupTabs or (not ConsiderGroupTabs and (GroupOfTab(i) < 0)) then
      begin
        if (AdvPages[i].TabWidth > GetMinTabWidth) then
        begin
          Result := True;
          Break;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.AnyTabCanBeExpanded: Boolean;
var
  i: Integer;
begin
  Result := False;
  for i:= 0 to AdvPageCount-1 do
  begin
    if AdvPages[i].TabVisible then
    begin
      if (AdvPages[i].TabClientWidth < AdvPages[i].TabRealClientWidth{GetRealTabWidth(i, j)}) then
      begin
        Result := True;
        Break;
      end;
    end;
  end;
end;


//------------------------------------------------------------------------------

function TAdvToolBarPager.TotalGroupTabsCanBeExpanded: Integer;
var
  i: Integer;
begin
  Result := 0;
  for i:= 0 to AdvPageCount-1 do
  begin
    if AdvPages[i].TabVisible and AdvPages[i].IsGroupTab then
    begin
      Result := Result + (AdvPages[i].TabRealClientWidth - AdvPages[i].TabClientWidth);
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.AnyGroupTabCanBeExpanded: Boolean;
var
  i: Integer;
begin
  Result := False;
  for i:= 0 to AdvPageCount-1 do
  begin
    if AdvPages[i].TabVisible and AdvPages[i].IsGroupTab then
    begin
      if (AdvPages[i].TabClientWidth < AdvPages[i].TabRealClientWidth) then
      begin
        Result := True;
        Break;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateTabSizes;
var
  aw, rw, d, MinSpacing, i, tc, j, k, l: Integer;
  R: TRect;
  OldV1, OldV2, ls: Integer;
begin
  if (AdvPageCount <= 0) or not FPropertiesLoaded then
    Exit;
    
  rw := GetTotalTabsWidth;
  R := GetTabsRect;
  aw := R.Right - R.Left;
  MinSpacing := FTabSettings.MinSpacing;
  tc := 5;  // truncate width
  ls := 5; // leave width to must have scroll (Group tabs essential)

  if (rw - aw = 0) then
  begin
    k := TotalGroupTabsCanBeExpanded;
    if (k > 0) then
    begin
      aw := aw + Min(ls, k);
    end;
  end;


  if (rw > aw) then   // Shrink tabs
  begin
    d := rw - aw;
    // reducing spacing
    while (FCurrentTabSpacing > MinSpacing) do
    begin
      FCurrentTabSpacing := FCurrentTabSpacing - 1;
      rw := GetTotalTabsWidth;
      d := rw - aw;
      if (d <= 0) then
      begin
        d := 0;
        Break;
      end;
    end;
    UpdateTabPosition;

    // reducing Margins
    if (d > 0) then
    begin
      while (FCurrentTabLeftMargin > FTabSettings.MinMargin) or (FCurrentTabRightMargin > FTabSettings.MinMargin) do
      begin
        if (FCurrentTabLeftMargin > FTabSettings.MinMargin) then
          FCurrentTabLeftMargin := FCurrentTabLeftMargin - 1;
        rw := GetTotalTabsWidth;
        d := rw - aw;
        if (d <= 0) then
        begin
          d := 0;
          Break;
        end;

        if (d > 0) then
        begin
          if (FCurrentTabRightMargin > FTabSettings.MinMargin) then
            FCurrentTabRightMargin := FCurrentTabRightMargin - 1;
          rw := GetTotalTabsWidth;
          d := rw - aw;
          if (d <= 0) then
          begin
            d := 0;
            Break;
          end;
        end;
      end;
      UpdateTabPosition;
    end;

    // reducing Group Tab Margins
    if (d > 0) then
    begin
      while (FCurrentGroupTabLeftMargin > FTabSettings.MinMargin) or (FCurrentGroupTabRightMargin > FTabSettings.MinMargin) do
      begin
        if (FCurrentGroupTabLeftMargin > FTabSettings.MinMargin) then
          FCurrentGroupTabLeftMargin := FCurrentGroupTabLeftMargin - 1;
        rw := GetTotalTabsWidth;
        d := rw - aw;
        if (d <= 0) then
        begin
          d := 0;
          Break;
        end;

        if (d > 0) then
        begin
          if (FCurrentGroupTabRightMargin > FTabSettings.MinMargin) then
            FCurrentGroupTabRightMargin := FCurrentGroupTabRightMargin - 1;
          rw := GetTotalTabsWidth;
          d := rw - aw;
          if (d <= 0) then
          begin
            d := 0;
            Break;
          end;
        end;
      end;
      UpdateTabPosition;
    end;

    if (d > 0) then
    begin
      if AnyTabCanBeShrunk(False) then
      begin
        k := 0;
        while (d > 0) do
        begin
          i := GetLargestTabIndex(False);
          if (i >= 0) and (AdvPages[i].TabWidth > GetMinTabWidth) then
          begin // truncating tab
            j := AdvPages[i].TabWidth - GetMinTabWidth;
            j := Min(j, Min(tc, d));
            AdvPages[i].TabClientWidth := AdvPages[i].TabClientWidth - j;
            for l := i+1 to AdvPageCount -1 do
            begin
              if AdvPages[l].TabVisible then
              begin
                AdvPages[l].TabLeft := AdvPages[l].TabLeft - j;
              end;
            end;
            d := d - j;
          end
          else
          begin
            Break;
          end;

          Inc(k);
          if (k >= rw) then  // make sure to avoid infinite loop
          begin
            Break;
          end;
        end;
      end
      else // consider Contextual tabs
      begin
        d := d - ls;
        if (d > 0) then
        begin
          k := 0;
          while (d > 0) do
          begin
            i := GetLargestTabIndex(True);
            if (i >= 0) and (AdvPages[i].TabWidth > GetMinTabWidth) and AdvPages[i].IsGroupTab then
            begin // truncating tab
              j := AdvPages[i].TabWidth - GetMinTabWidth;
              j := Min(j, Min(tc, d));
              AdvPages[i].TabClientWidth := AdvPages[i].TabClientWidth - j;
              for l := i+1 to AdvPageCount -1 do
              begin
                if AdvPages[l].TabVisible then
                begin
                  AdvPages[l].TabLeft := AdvPages[l].TabLeft - j;
                end;
              end;
              d := d - j;
            end
            else
            begin
              Break;
            end;

            Inc(k);
            if (k >= rw) then  // make sure to avoid infinite loop
            begin
              Break;
            end;
          end; // while
        end;
      end; // else
    end;
  end
  else if (rw < aw) then // Expand tabs
  begin
    d := aw - rw;
    if AnyTabCanBeExpanded then
    begin
      k := TotalGroupTabsCanBeExpanded;
      if (k > 0) and (k > d) then
      begin
        k := k - d;
        d := d + Min(ls, k);
      end;

      k := 0;
      while (d > 0) do
      begin
        i := GetSmallestExpandableTabIndex(True);
        if (i >= 0) then
        begin // expanding tab
          //j := GetRealTabWidth(i, m) - AdvPages[i].TabWidth;
          j := AdvPages[i].TabRealClientWidth - AdvPages[i].TabClientWidth;
          j := Min(j, Min(tc, d));
          AdvPages[i].TabClientWidth := AdvPages[i].TabClientWidth + j;
          for l := i+1 to AdvPageCount -1 do
          begin
            if AdvPages[l].TabVisible then
            begin
              AdvPages[l].TabLeft := AdvPages[l].TabLeft + j;
            end;
          end;
          d := d - j;
        end
        else
        begin
          Break;
        end;

        {if (d <= 0) and AnyGroupTabCanBeExpanded then
        begin
          d := ls;
        end;}

        Inc(k);
        if (k >= rw) then  // make sure to avoid infinite loop
        begin
          Break;
        end;
      end;
    end;

    if not AnyTabCanBeExpanded then
    begin
      // Increase Spacing
      if (d > 0) then
      begin
        while (FCurrentTabSpacing < FTabSettings.Spacing) do
        begin
          FCurrentTabSpacing := FCurrentTabSpacing + 1;
          rw := GetTotalTabsWidth;
          d := aw - rw;
          if (d <= 0) then
          begin
            if (d < 0) then
            begin
              FCurrentTabSpacing := FCurrentTabSpacing - 1;
            end;
            d := 0;
            Break;
          end;
        end;
        //OutputDebugString(PChar('FCurrentTabSpacing: ' + InttoStr(FCurrentTabSpacing)));
        UpdateTabPosition;
      end;

      // Increase Group Tab Margin
      if (d > 0) then
      begin
        while (FCurrentGroupTabLeftMargin < FTabSettings.LeftMargin) or (FCurrentGroupTabRightMargin < FTabSettings.RightMargin) do
        begin
          OldV1 := FCurrentGroupTabLeftMargin;
          OldV2 := FCurrentGroupTabRightMargin;

          if (FCurrentGroupTabLeftMargin < FTabSettings.LeftMargin) then
            FCurrentGroupTabLeftMargin := FCurrentGroupTabLeftMargin + 1;
          rw := GetTotalTabsWidth;
          d := aw - rw;
          if (d <= 0) then
          begin
            if (d < 0) then
            begin
              FCurrentGroupTabLeftMargin := OldV1;
            end;
            d := 0;
            Break;
          end;

          if (FCurrentGroupTabRightMargin < FTabSettings.RightMargin) then
            FCurrentGroupTabRightMargin := FCurrentGroupTabRightMargin + 1;
          rw := GetTotalTabsWidth;
          d := aw - rw;
          if (d <= 0) then
          begin
            if (d < 0) then
            begin
              FCurrentGroupTabRightMargin := OldV2;
            end;
            d := 0;
            Break;
          end;
        end;
        UpdateTabPosition;
      end;

      // Increase Margin
      if (d > 0) then
      begin
        while (FCurrentTabLeftMargin < FTabSettings.LeftMargin) or (FCurrentTabRightMargin < FTabSettings.RightMargin) do
        begin
          OldV1 := FCurrentTabLeftMargin;
          OldV2 := FCurrentTabRightMargin;

          if (FCurrentTabLeftMargin < FTabSettings.LeftMargin) then
            FCurrentTabLeftMargin := FCurrentTabLeftMargin + 1;
          rw := GetTotalTabsWidth;
          d := aw - rw;
          if (d <= 0) then
          begin
            if (d < 0) then
            begin
              FCurrentTabLeftMargin := OldV1;
            end;
            //d := 0;
            Break;
          end;

          if (FCurrentTabRightMargin < FTabSettings.RightMargin) then
            FCurrentTabRightMargin := FCurrentTabRightMargin + 1;
          rw := GetTotalTabsWidth;
          d := aw - rw;
          if (d <= 0) then
          begin
            if (d < 0) then
            begin
              FCurrentTabRightMargin := OldV2;
            end;
            //d := 0;
            Break;
          end;
        end;
        UpdateTabPosition;
      end;
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.ResetTabsPosition;
var
  i, X: Integer;
  R: TRect;
begin
  R := GetTabsRect;
  X := R.Left;
  for i:= 0 to AdvPageCount -1 do
  begin
    if AdvPages[i].TabVisible then
    begin
      AdvPages[i].TabLeft := X;
      X := X + AdvPages[i].TabWidth + FCurrentTabSpacing;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateTabPosition(FromIndex, ToIndex: Integer);
var
  i, X: Integer;
  firstfound: Boolean;
begin
  if (FromIndex < 0) or (ToIndex >= AdvPageCount) or (FromIndex > ToIndex) or (AdvPageCount = 0) then
    Exit;

  firstfound := False;
  X := 0;
  for i:= FromIndex to ToIndex do
  begin
    if AdvPages[i].TabVisible then
    begin
      if firstfound then
      begin
        AdvPages[i].TabLeft := X;
        X := X + AdvPages[i].TabWidth + FCurrentTabSpacing;
      end
      else
      begin
        X := AdvPages[i].TabLeft;
        X := X + AdvPages[i].TabWidth + FCurrentTabSpacing;
        firstfound := True;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateTabPosition;
begin
  UpdateTabPosition(0, AdvPageCount-1);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.InitializeTabsSize;
var
  i: Integer;
begin
  FCurrentTabSpacing := FTabSettings.Spacing;
  FCurrentTabLeftMargin := FTabSettings.LeftMargin;
  FCurrentTabRightMargin := FTabSettings.RightMargin;
  FCurrentGroupTabLeftMargin := FTabSettings.LeftMargin;
  FCurrentGroupTabRightMargin := FTabSettings.RightMargin;
  for i:= 0 to AdvPageCount -1 do
  begin
    InitializeTabWidth(i);
  end;
  //ResetTabsPosition;
  InitializeScroller;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.InitializeTabWidth(TabIndex: Integer);
var
  i: Integer;
begin
  if (TabIndex < 0) or (TabIndex >= AdvPageCount) then
    Exit;

  GetRealTabWidth(TabIndex, i);
  AdvPages[TabIndex].TabClientWidth := i;
  AdvPages[TabIndex].TabRealClientWidth := i;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMDesignHitTest(var Msg: TCMDesignHitTest);
var
  p: TPoint;
  Tab: Integer;
begin
  Tab := -1;
  if (csDesigning in ComponentState) then
  begin
    GetCursorPos(P);
    P := ScreenToClient(P);

    if PtInRect(GetTabsRect, p) and (GetAsyncKeyState(VK_LBUTTON) <> 0) then
    begin
      Tab := PTOnTab(P.X, P.Y);
      if (Tab >= 0) then
      begin
        // Select Tab
        //ActivePageIndex := Tab;
        Msg.Result := 1;
      end;
    end;

  end;

  if (Tab = -1) then
    inherited;;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetImages(const Value: TCustomImageList);
begin
  FImages := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.InvalidateActivePageAttachement;
var
  R: TRect;
begin
  if Assigned(ActivePage) then
  begin
    R := Rect(0, 0, ActivePage.Width, 3);
    InvalidateRect(ActivePage.Handle, @R, True);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.InvalidateTab(PageIndex: Integer);
var
  R: TRect;
begin
  if (PageIndex >= 0) and (PageIndex < FAdvPages.Count) then
    R := GetTabRect(PageIndex)
  else
    R := GetTabsArea;
  InvalidateRect(Handle, @R, True);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnEnterTab(PageIndex: Integer);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnExitTab(PageIndex: Integer);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetDisabledImages(
  const Value: TCustomImageList);
begin
  FDisabledImages := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

{procedure TAdvToolBarPager.UpdateTabScroller;
  function GetScrollMax: Integer;
  var
    i, LastVisTab: Integer;
    R: TRect;
  begin
    Result := 0;
    LastVisTab := 0;
    for i:= FAdvPages.Count -1 downto 0 do
    begin
      if AdvPages[i].TabVisible then
      begin
        LastVisTab := i;
        Break;
      end;
    end;

    if (LastVisTab <= 0) then
      Exit;

    i := 0;
    while (i < FAdvPages.Count) do
    begin
      R := GetTabRect(i, LastVisTab, False);
      if (R.Left > -1) and (R.Right > -1) then
      begin
        Result := i;
        Break;
      end;
      inc(i);
      FTabScroller.Visible := True;  // just to be counted in calculation
    end;
  end;

begin
  Exit;  // TODO: have to update scoll code

  FTabScroller.Visible := False;
  FTabScroller.Min := 0;
  FTabScroller.Max := GetScrollMax;
  FTabScroller.Visible := FTabScroller.Min < FTabScroller.Max;
  if (FTabScroller.Position > FTabScroller.Max) then
    FTabScroller.Position := FTabScroller.Max;
end;
}

//------------------------------------------------------------------------------

function TAdvToolBarPager.TabCountOnVisibleArea(TabIndex: Integer; GoForward: Boolean; var LastTabIndex: Integer): Integer;
var
  i, X: Integer;
  R: TRect;
begin
  Result := 0;
  if (TabIndex < 0) or (TabIndex >= AdvPageCount) then
    Exit;
    
  R := GetTabsRect;
  x :=  R.Left;
  if GoForward then
  begin
    for i := TabIndex to AdvPageCount -1 do
    begin
      if AdvPages[i].TabVisible then
      begin
        X := X + AdvPages[i].TabWidth + FCurrentTabSpacing;
        if (X - FCurrentTabSpacing < R.Right) then
        begin
          Result := Result + 1;
          LastTabIndex := i;
        end
        else
        begin
          Break;
        end;
      end;
    end;
  end
  else
  begin
    for i := TabIndex downto 0 do
    begin
      if AdvPages[i].TabVisible then
      begin
        X := X + AdvPages[i].TabWidth + FCurrentTabSpacing;
        if (X - FCurrentTabSpacing < R.Right) then
        begin
          Result := Result + 1;
          LastTabIndex := i;
        end
        else
        begin
          Break;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.InitializeScroller;
begin
  FStartTabIndex := 0;
  FTabScroller.Min := 0;
  FTabScroller.Max := 0;
  FTabScroller.Position := 0;
  ResetTabsPosition;
  UpdateTabScroller;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateTabScroller;
var
  aw, rw, vc, i, j, k, sw, t, tc: Integer;
  R: TRect;
begin
  if (AdvPageCount <= 0) or (csDesigning in ComponentState) or (csLoading in ComponentState) then
    Exit;

  rw := GetTotalTabsWidth;
  R := GetTabsRect;
  aw := R.Right - R.Left;
  sw := SCROLLBTN_WIDTH;
  tc := VisibleTabCount;

  if (rw > aw) then
  begin
    j := 0;
    vc := 0;
    t := 0;
    for i:= 0 to AdvPageCount-1 do
    begin
      k := 0;
      t := t + Max(1, TabCountOnVisibleArea(vc, True, k));
      if (t >= tc) then
        Break;
      vc := k + 1;
      j := j + 1;
    end;
    
    FTabScroller.Max := j;
  end
  else
  begin
    FTabScroller.Max := 0;
  end;
  FTabScroller.Position := Min(FTabScroller.Position, FTabScroller.Max);


  if FTabScroller.CanGoBack then
  begin
    if (FLeftScrollBtn = nil) then
    begin
      FLeftScrollBtn := TAdvPageScrollButton.Create(Self);
      FLeftScrollBtn.Parent := Self;
      //FLeftScrollBtn.Align := alLeft;
      FLeftScrollBtn.Width := sw;
      FLeftScrollBtn.Height := (R.Bottom - R.Top - 5);
      FLeftScrollBtn.Position := bpLeft;
      FLeftScrollBtn.ScrollArrow := saLeft;
      FLeftScrollBtn.OnClick := OnScrollLeftBtnClick;
    end;
    FLeftScrollBtn.Left := R.Left;
    FLeftScrollBtn.Top := R.Top;
    FLeftScrollBtn.Visible := True;
    FLeftScrollBtn.BringToFront;

    if Assigned(FCurrentToolBarStyler) then
      FLeftScrollBtn.Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
  end
  else
  begin
    if Assigned(FLeftScrollBtn) then
      FLeftScrollBtn.Visible := False;
  end;

  if FTabScroller.CanGoForward then
  begin
    if (FRightScrollBtn = nil) then
    begin
      FRightScrollBtn := TAdvPageScrollButton.Create(Self);
      FRightScrollBtn.Parent := Self;
      FRightScrollBtn.Width := sw;
      FRightScrollBtn.Height := (R.Bottom - R.Top - 5);
      FRightScrollBtn.Position := bpRight;
      FRightScrollBtn.ScrollArrow := saRight;
      FRightScrollBtn.OnClick := OnScrollRightBtnClick;
    end;
    FRightScrollBtn.Left := R.Right - FRightScrollBtn.Width;
    FRightScrollBtn.Top := R.Top;
    FRightScrollBtn.Visible := True;
    FRightScrollBtn.BringToFront;

    if Assigned(FCurrentToolBarStyler) then
      FRightScrollBtn.Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
  end
  else
  begin
    if Assigned(FRightScrollBtn) then
      FRightScrollBtn.Visible := False;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetLastVisibleTabIndex: Integer;
var
  i: Integer;
begin
  Result := -1;
  for i:= AdvPageCount-1 downto 0 do
  begin
    if AdvPages[i].TabVisible then
    begin
      Result := i;
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.ChangeLeftTabIndexTo(Value: Integer);
var
  i, j, vc, k, l, lv: Integer;
  done: Boolean;
  R: TRect;
begin
  if (Value < 0) or (Value >= AdvPageCount) then
    Exit;

  j := 5;

  if (Value > FStartTabIndex) then
  begin
    vc := TabCountOnVisibleArea(Value, True, l);
    for i := 0 to AdvPageCount -1 do
    begin
      k := TabCountOnVisibleArea(Value - 1, True, l);
      if (k > vc) then
      begin
        Value := Value - 1;
        vc := k;
      end
      else
      begin
        Break;
      end;
    end;

    if (Value > FStartTabIndex) then
    begin
      done := False;
      lv := GetLastVisibleTabIndex;
      R := GetTabsRect;
      while not done do
      begin
        if (lv >= 0) and (R.Right >= (AdvPages[lv].TabLeft + AdvPages[lv].TabWidth - j)) then
        begin
          j := ((AdvPages[lv].TabLeft + AdvPages[lv].TabWidth) - R.Right);
          done := True;
        end;

        if (R.Left >= AdvPages[Value].TabLeft - j) then
        begin
          j := AdvPages[Value].TabLeft - R.Left;
          done := True;
        end;

        for i := 0 to AdvPageCount -1 do
        begin
          AdvPages[i].TabLeft := AdvPages[i].TabLeft - j;
          InvalidateTab(-1);
        end;
      end;

      FStartTabIndex := Value;
      UpdateTabScroller;
    end;
  end
  else if (Value < FStartTabIndex) then
  begin
    Value := Max(0, Value);
    if (Value < FStartTabIndex) then
    begin
      done := False;
      //lv := GetFirstVisibleTabIndex;
      R := GetTabsRect;
      while not done do
      begin
        {if (lv >= 0) and (R.Left <= AdvPages[lv].TabLeft + j) then
        begin
          j := R.Left - AdvPages[lv].TabLeft;
          done := True;
        end;}

        if (R.Left <= AdvPages[Value].TabLeft + j) then
        begin
          j := R.Left - AdvPages[Value].TabLeft;
          done := True;
        end;

        for i := 0 to AdvPageCount -1 do
        begin
          AdvPages[i].TabLeft := AdvPages[i].TabLeft + j;
          InvalidateTab(-1);
        end;
      end;

      FStartTabIndex := Value;
      UpdateTabScroller;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.ScrollTabsPage(Value: Integer): Integer;
var
  i, k, j: Integer;
begin
  Result := 0;
  if (Value > 0) then
  begin
    Result := Min(Value, FTabScroller.Max - FTabScroller.Position);
    if FTabScroller.CanGoForward and (Result > 0) then
    begin
      FTabScroller.Position := FTabScroller.Position + Result;
      k := FStartTabIndex;
      j := 0;
      for i := 1 to Result do
      begin
        TabCountOnVisibleArea(k, True, j);
        k := j + 1;
        if (k >= AdvPageCount) then
          Break;
      end;

      ChangeLeftTabIndexTo(j +1);
      InvalidateScrollBtns;
      InvalidateActivePageAttachement;
    end;
  end
  else if (Value < 0) then
  begin
    Result := -Min(abs(Value), FTabScroller.Position - FTabScroller.Min);
    if FTabScroller.CanGoBack and (Result < 0) and (FStartTabIndex > 0) then
    begin
      FTabScroller.Position := FTabScroller.Position + Result;
      k := FStartTabIndex - 1;
      j := 0;
      for i := 1 to abs(Result) do
      begin
        TabCountOnVisibleArea(k, False, j);
        k := j - 1;
        if (k <= 0) then
        begin
          k := 0;
          Break;
        end;
      end;

      ChangeLeftTabIndexTo(k);
      InvalidateScrollBtns;
      InvalidateActivePageAttachement;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.InvalidateScrollBtns;
begin
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.ScrollInView(TabIndex: Integer);
begin
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.VisibleTabCount(FromIndex, ToIndex: Integer): Integer;
var
  i: Integer;
begin
  Result := 0;
  if (FromIndex < 0) or (FromIndex > ToIndex) or (ToIndex >= AdvPageCount) then
    Exit;
    
  for i:= FromIndex to ToIndex do
  begin
    if AdvPages[i].TabVisible then
    begin
      Result := Result + 1;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.VisibleTabCount: Integer;
begin
  Result := VisibleTabCount(0, AdvPageCount-1);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.PtOnTabScrollLeftBtn(X, Y: integer): Boolean;
var
  P: TPoint;
begin
  P := Point(X, Y);
  Result := PtInRect(GetTabScrollerLeftRect, P);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.PtOnTabScrollRightBtn(X, Y: integer): Boolean;
var
  P: TPoint;
begin
  P := Point(X, Y);
  Result := PtInRect(GetTabScrollerRightRect, P);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DrawTabScrollBtnLeft;
var
  R: TRect;
  y: Integer;
  Clr: TColor;
begin
  if FTabScroller.Visible then
  begin
    R := GetTabScrollerLeftRect;
    y := ((R.Bottom - R.Top) - 12) div 2;
    Clr := FCurrentToolBarStyler.TabAppearance.TextColor;
    if FScrollerDownLeftBtn then
      Clr := FCurrentToolBarStyler.TabAppearance.ColorSelected
    else if FScrollerHoverLeftBtn then
      Clr := FCurrentToolBarStyler.TabAppearance.ColorMirrorHotTo;

    if not FTabScroller.CanGoBack then
      Clr := clGray;
      
    with Canvas do
    begin
      //Brush.color:= Color;
      //FillRect(Rect(0,0,12,13));
      //Brush.Style := bsClear;
      //Rectangle(R);

      Pen.Color:= Clr;
        // |
      MoveTo(R.left+9, R.Top+y+0);
      LineTo(R.left+9, R.Top+y+8);
        // /
      MoveTo(R.left+9, R.Top+y+0);
      LineTo(R.left+5, R.Top+y+4);
        // \
      MoveTo(R.left+9, R.Top+y+8);
      LineTo(R.left+4, R.Top+y+3);
        // Fill arrow |
      MoveTo(R.left+8, R.Top+y+2);
      LineTo(R.left+8, R.Top+y+7);
      MoveTo(R.left+7, R.Top+y+3);
      LineTo(R.left+7, R.Top+y+6);
      Pixels[R.left+6, R.Top+y+4]:= Pen.Color;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DrawTabScrollBtnRight;
var
  R: TRect;
  y: Integer;
  Clr: TColor;
begin
  if FTabScroller.Visible then
  begin
    R := GetTabScrollerRightRect;
    y := ((R.Bottom - R.Top) - 12) div 2;
    Clr := FCurrentToolBarStyler.TabAppearance.TextColor;
    if FScrollerDownRightBtn then
      Clr := FCurrentToolBarStyler.TabAppearance.ColorSelected
    else if FScrollerHoverRightBtn then
      Clr := FCurrentToolBarStyler.TabAppearance.ColorMirrorHotTo;

    if not FTabScroller.CanGoForward then
      Clr := clGray;

    with Canvas do
    begin
      //Brush.color:= Color;
      //FillRect(Rect(12,0,24,13));
      //Brush.Style := bsClear;
      //Rectangle(R);

      Pen.Color:= Clr;
        // |
      MoveTo(R.Left+3, R.Top+y);
      LineTo(R.Left+3, R.Top+y+8);
        // \
      MoveTo(R.Left+3, R.Top+y);
      LineTo(R.Left+7, R.Top+y+4);
        // /
      MoveTo(R.Left+3, R.Top+y+8);
      LineTo(R.Left+8, R.Top+y+3);
        // Fill Arrow |
      MoveTo(R.Left+4, R.Top+y+2);
      LineTo(R.Left+4, R.Top+y+7);
      MoveTo(R.Left+5, R.Top+y+3);
      LineTo(R.Left+5, R.Top+y+6);
      Pixels[R.Left+6, R.Top+y+4]:= Pen.Color;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DrawTabScrollButtons;
begin
  DrawTabScrollBtnLeft;
  DrawTabScrollBtnRight;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DrawTabGroups;
var
  i, ImgTxtSp, Ind, ImgX, ImgY: Integer;
  R, R2, R3, CapR: TRect;
  GrpAppearance: TGroupAppearance;
  LnClrTo: TColor;
  ImgEnabled: Boolean;
  ImgList: TCustomImageList;
  Algn: TAlignment;
  DrawTabGpL, DrawTabGpR: Boolean;
  DTSTYLE: DWORD;
begin
  if HideState then
    Exit;
    
  ImgTxtSp := 3;
  Ind := 3;
  ImgList := nil;
  for i:= 0 to FTabGroups.Count -1 do
  begin
    DrawTabGpR := True;
    DrawTabGpL := True;
    R := GetTabGroupRect(i, DrawTabGpL, DrawTabGpR);
    if (R.Left > -1) and (R.Right > -1) then
    begin
      if TabGroups.Items[i].DefaultAppearance then
        GrpAppearance := FCurrentToolBarStyler.GroupAppearance
      else
        GrpAppearance := TabGroups.Items[i].GroupAppearance;

      R2 := R;
      R2.Bottom := GetTabsArea.Top;
      R2.Top := R2.Top + 8;
      DrawVistaGradient(Canvas, R2,GrpAppearance.Color, GrpAppearance.ColorTo, GrpAppearance.ColorMirror, GrpAppearance.ColorMirrorTo, clNone,
          GrpAppearance.Gradient, GrpAppearance.GradientMirror, '', Canvas.Font, Enabled, False, FAntiAlias, False);

      Canvas.Pen.Color := BlendColor(GrpAppearance.ColorMirrorTo, clBlack, 80); //GrpAppearance.ColorMirrorTo;
      Canvas.MoveTo(R.Left, R2.Bottom);
      Canvas.LineTo(R.Right, R2.Bottom);

      LnClrTo := GrpAppearance.BorderColor; // RGB(172, 184, 163);
      R3 := Rect(R.Left, R.Top+6, R.Left+1, R2.Bottom+1);
      DrawGradient(Canvas, FCurrentToolBarStyler.PagerCaption.Color, LnClrTo, 40, R3, False);
      R3 := Rect(R.Right-1, R.Top+6, R.Right, R2.Bottom+2{1});
      DrawGradient(Canvas, FCurrentToolBarStyler.PagerCaption.Color, LnClrTo, 40, R3, False);

      R3 := Rect(R.Left, R2.Bottom, R.Left+1, R.Bottom);
      DrawGradient(Canvas, LnClrTo, FCurrentToolBarStyler.TabAppearance.BackGround.Color, 40, R3, False);
      if DrawTabGpR then
      begin
        R3 := Rect(R.Right-1, R2.Bottom, R.Right, R.Bottom);
        DrawGradient(Canvas, LnClrTo, FCurrentToolBarStyler.TabAppearance.BackGround.Color, 40, R3, False);
      end;


      CapR := R2;
      CapR.Left := CapR.Left + Ind;
      Algn := TabGroups.Items[i].CaptionAlignment;
      Canvas.Font.Assign(GrpAppearance.Font);
      DTSTYLE := DT_SINGLELINE or DT_PATH_ELLIPSIS or DT_VCENTER or DT_LEFT;

      if (Assigned(FImages) or Assigned(DisabledImages)) and (TabGroups.Items[i].ImageIndex >= 0) then
      begin
        ImgEnabled := True;
        if Enabled then
        begin
          if Assigned(FImages) then
            ImgList := FImages;
        end
        else
        begin
          if Assigned(FDisabledImages) then
            ImgList := FDisabledImages
          else if Assigned(FImages) then
          begin
            ImgList := FImages;
            ImgEnabled := False;
          end;
        end;

        if (ImgList <> nil) then
        begin
          {Canvas.Font.Name := 'Tahoma';
          Canvas.Font.Size := 8;
          Canvas.Font.Style := []; }

          R3 := Rect(0,0, 1000, 100);
          DrawText(Canvas.Handle,PChar(TabGroups.Items[i].Caption),Length(TabGroups.Items[i].Caption), R3, DT_CALCRECT or DT_LEFT or DT_SINGlELINE);
          R3.Right := R3.Right + Length(TabGroups.Items[i].Caption);

          ImgX := CapR.left;
          case TabGroups.Items[i].CaptionAlignment of
            taLeftJustify:
              ImgX := CapR.Left;
            taCenter:
              ImgX := R2.Left + ((R2.Right - R2.Left) - (ImgList.Width + ImgTxtSp + R3.Right)) div 2;
            taRightJustify:
              ImgX := R2.Right - (ImgList.Width + ImgTxtSp + R3.Right + Ind);
          end;

          Algn := taLeftJustify;
          ImgX := Max(CapR.Left, ImgX);
          CapR.Left := ImgX + ImgList.Width + ImgTxtSp;
          ImgY := R2.Top + ((R2.Bottom - R2.Top) - ImgList.Height) div 2;
          ImgList.Draw(Canvas, ImgX, ImgY, TabGroups.Items[i].ImageIndex, ImgEnabled);
        end;
      end;

      Canvas.Brush.Style := bsClear;
      Canvas.Font.Color := GrpAppearance.TextColor;
      //DrawVistaText(Canvas, Algn, CapR, TabGroups.Items[i].Caption, TabGroups.Items[i].WideCaption, Canvas.Font, True, True,AntiAlias);
      DrawVistaText2(Canvas, Algn, DTSTYLE, CapR, TabGroups.Items[i].Caption, TabGroups.Items[i].WideCaption, Canvas.Font, True, True,AntiAlias, True, False);
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.PtOntTabGroup(X, Y: Integer): Integer;
var
  i: Integer;
  DrawTabGpR, DrawTabGpL: Boolean;
  p: TPoint;
  R: TRect;
begin
  Result := -1;
  P := Point(X, Y);
  for i:= 0 to FTabGroups.Count -1 do
  begin
    DrawTabGpR := True;
    DrawTabGpL := True;
    R := GetTabGroupRect(i, DrawTabGpL, DrawTabGpR);
    if PtInRect(R, P) then
    begin
      Result := i;
      break;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.IsTabGroupVisible(GroupIndex: Integer): Boolean;
begin
  Result := False;
  if (ActivePageIndex >= 0) and (GroupIndex >= 0) and (GroupIndex < FTabGroups.Count) then
  begin
    Result := (FTabGroups.Items[GroupIndex].TabIndexStart >= 0) and (FTabGroups.Items[GroupIndex].TabIndexEnd >= 0)
          and (FTabGroups.Items[GroupIndex].TabIndexStart <= FTabGroups.Items[GroupIndex].TabIndexEnd)
          and (FTabGroups.Items[GroupIndex].TabIndexEnd < FAdvPages.Count)
          and (ActivePageIndex >= FTabGroups.Items[GroupIndex].TabIndexStart) and (ActivePageIndex <= FTabGroups.Items[GroupIndex].TabIndexEnd);
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GroupOfTab(PageIndex: Integer): Integer;
var
  i: Integer;
begin
  Result := -1;
  if (PageIndex >= 0) and (PageIndex < FAdvPages.Count) then
  begin
    for i:= 0 to FTabGroups.Count -1 do
    begin
      if (PageIndex >= FTabGroups.Items[i].TabIndexStart) and (PageIndex <= FTabGroups.Items[i].TabIndexEnd) then
      begin
        Result := i;
        Break;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabGroupRect(GroupIndex: Integer; var LeftVisible, RightVisible: Boolean): TRect;
var
  i: Integer;
  R: TRect;
begin
  Result:= Rect(-1, -1, -1, -1);
  if (GroupIndex >= 0) and (GroupIndex < FTabGroups.Count) then
  begin
    if (FTabGroups.Items[GroupIndex].TabIndexStart >= 0) and (FTabGroups.Items[GroupIndex].TabIndexEnd >= 0)
      and (FTabGroups.Items[GroupIndex].TabIndexStart <= FTabGroups.Items[GroupIndex].TabIndexEnd) and (FTabGroups.Items[GroupIndex].TabIndexEnd < FAdvPages.Count) then
    begin
      for i := FTabGroups.Items[GroupIndex].TabIndexStart to FTabGroups.Items[GroupIndex].TabIndexEnd do
      begin
        if AdvPages[i].TabVisible then
        begin
          R := GetTabRect(i);
          if (R.Left > -1) and (R.Right > -1) then
          begin
            if (Result.Left <= -1) then
            begin
              Result:= R;
              LeftVisible := True;
              RightVisible := True;
            end;
            Result.Right := R.Right;              
          end;
        end;
      end;
      
      if (Result.Left > -1) and (Result.Right > -1) then
      begin
        Result.Bottom := Result.Bottom;
        Result.Top := GetCaptionRect.Top;

        if (FTabSettings.Spacing > 2) then
        begin
          Result.Left := Result.Left - (FTabSettings.Spacing div 2); //2
          Result.Right := Result.Right + (FTabSettings.Spacing div 2); //2
        end;

        if (FCaption.Visible and (FCaptionButtons <> [])) then
        begin
          R := GetCaptionButtonsRect;
          if (Result.Right > R.Left) and (Result.Left > R.Left) then
          begin
            Result:= Rect(-1, -1, -1, -1);
            LeftVisible := False;
            RightVisible := False;
          end;

          if (Result.Right > R.Left) and (Result.Left < R.Left) then
          begin
            Result.Right := R.Left - 1;
            RightVisible := False;
          end;
        end;

        if Assigned(FQuickAccessToolBar) and not ShowQATBelow and FQuickAccessToolBar.Visible then
        begin
          R := MaxQATRect;
          i := FQuickAccessToolBar.Width;
          if (Result.Left < R.Left + i) then
          begin
            Result:= Rect(-1, -1, -1, -1);
            LeftVisible := False;
            RightVisible := False;
          end;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnScrollLeftBtnClick(Sender: TObject);
begin
  ScrollTabsPage(-1);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnScrollRightBtnClick(Sender: TObject);
begin
  ScrollTabsPage(1);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabScrollerLeftRect: TRect;
begin
  Result := Rect(-1, -1, -1, -1);
  if FTabScroller.Visible then
  begin
    if Align in [daTop, daBottom] then
    begin
      Result := GetTabScrollerRect;
      Result.Right := Result.Left + (Result.Right - Result.Left) div 2 - 1;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabScrollerRect: TRect;
begin
  Result := Rect(-1, -1, -1, -1);
  if FTabScroller.Visible then
  begin
    if Align in [daTop, daBottom] then
    begin
      Result := GetTabsRect;
      Result.Left := Result.Right + 2;
      Result.Right := Result.Left + SCROLLER_SIZE;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetTabScrollerRightRect: TRect;
begin
  Result := Rect(-1, -1, -1, -1);
  if FTabScroller.Visible then
  begin
    if Align in [daTop, daBottom] then
    begin
      Result := GetTabScrollerRect;
      Result.Left := Result.Left + ((Result.Right - Result.Left) div 2);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMHintShow(var Message: TMessage);
var
  PHI: PHintInfo;
  R, TxtR: TRect;
  bmp: TBitmap;
  i: Integer;
  TabAppearance: TCustomTabAppearance;
begin
  PHI := TCMHintShow(Message).HintInfo;
  if ShowTabHint then
  begin
    if (FHintPageIndex >= 0) then
    begin
      if (AdvPages[FHintPageIndex].TabHint <> '') then
        PHI^.HintStr := AdvPages[FHintPageIndex].TabHint
      else
      begin
        R := GetTabRect(FHintPageIndex);
        TabAppearance := FCurrentToolBarStyler.TabAppearance;
        i := GroupOfTab(FHintPageIndex);
        if (i >= 0) and (i < FTabGroups.Count) then
        begin
          if not FTabGroups.Items[i].DefaultAppearance then
            TabAppearance := FTabGroups.Items[i].GroupAppearance.TabAppearance
          else
            TabAppearance := FCurrentToolBarStyler.GroupAppearance.TabAppearance;
        end;
        bmp := TBitmap.Create;
        bmp.Width := R.Right - R.Left;
        bmp.Height := R.Bottom - R.Top;
        bmp.Canvas.Font.Assign(TabAppearance.Font);
        TxtR := DrawVistaText(bmp.Canvas, taLeftJustify, Rect(0, 0, 1000, 100), AdvPages[FHintPageIndex].Caption, AdvPages[FHintPageIndex].WideCaption, bmp.Canvas.Font, AdvPages[FHintPageIndex].Enabled, False, AntiAlias);
        if (TxtR.Right - TxtR.Left > R.Right - R.left - FCurrentTabLeftMargin - FCurrentTabRightMargin) then
          PHI^.HintStr := AdvPages[FHintPageIndex].Caption;
        bmp.Free;
      end;
    end;
  end
  else
    PHI^.HintStr := '';
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetTabGroups(const Value: TTabGroups);
begin
  FTabGroups.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnTabGroupsChanged(Sender: TObject);
begin
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnCaptionChanged(Sender: TObject);
begin
  SetAllPagesPosition;
  UpdateCaptionButtons(True);
  if Assigned(FQuickAccessToolBar) then
  begin
    FQuickAccessToolBar.Left := FQuickAccessToolBar.Left + 1;
    FQuickAccessToolBar.Left := FQuickAccessToolBar.Left - 1;
  end;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnTabSettingsChanged(Sender: TObject);
begin
  SetAllPagesPosition;
  InitializeTabsSize;
  
  if Assigned(FQuickAccessToolBar) then
  begin
    FQuickAccessToolBar.UpdateSize;
    FQuickAccessToolBar.Invalidate;
  end;
  
  Invalidate;
  if Assigned(ActivePage) then
    ActivePage.Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateMe(PropID: integer);
begin
  Invalidate;
  if Assigned(ActivePage) then
    ActivePage.Invalidate;

  if Assigned(ToolBarStyler) then
  begin
    
    if Assigned(FCaptionMinBtn) then
    begin
      FCaptionMinBtn.Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
      FCaptionMinBtn.Invalidate;
    end;
    if Assigned(FCaptionMaxBtn) then
    begin
      FCaptionMaxBtn.Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
      FCaptionMaxBtn.Invalidate;
    end;
    if Assigned(FCaptionCloseBtn) then
    begin
      FCaptionCloseBtn.Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
      FCaptionCloseBtn.Invalidate;
    end;

    if Assigned(FMDIMinBtn) then
    begin
      FMDIMinBtn.Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
      FMDIMinBtn.Invalidate;
    end;
    if Assigned(FMDIMaxBtn) then
    begin
      FMDIMaxBtn.Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
      FMDIMaxBtn.Invalidate;
    end;
    if Assigned(FMDICloseBtn) then
    begin
      FMDICloseBtn.Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
      FMDICloseBtn.Invalidate;
    end;
  end;

  if (PropID = 11) then
    UpdateCaptionButtons(True);

  UpdateShapeButton;

  if {(PropID in [0, 7, 10, 11, 12]) and }Assigned(FQuickAccessToolBar) then
  begin
    FQuickAccessToolBar.UpdateMe(PropID);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.WMNCHitTest(var Msg: TWMNCHitTest);
var
  pt: TPoint;
begin
  inherited;

  if (csDesigning in ComponentState) then
    Exit;

  pt := ScreenToClient(point(msg.xpos,msg.ypos));

  if (pt.Y < 3) or (pt.X < 3) or (pt.X > Width - 6) then
    Msg.Result := HTTRANSPARENT;

{  pt := ScreenToClient(point(msg.xpos,msg.ypos));

  if (FCaption.Visible) and PtInRect(GetCaptionRect, pt)
     and (Msg.Result = htClient) and FCanMove then
  begin
    //MouseMove([],pt.X,pt.Y);

    Msg.Result := htCaption;
    //FInMove := true;

    SetWindowPos(GetParentForm(Self).Handle, HWND_TOP,0,0,0,0,  SWP_NOMOVE or SWP_NOSIZE);
  end;
}
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetCaptionButtons(const Value: TCaptionButtons);
begin
  if (FCaptionButtons <> Value) then
  begin
    FCaptionButtons := Value;
    UpdateCaptionButtons(True);
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.MaxQATRect: TRect;
var
  i: Integer;
begin
  Result := Rect(-1, -1, -1, -1);
  if Assigned(FQuickAccessToolBar) then
  begin
    if ShowQATBelow then
    begin
      Result := ClientRect;
      Result := Rect(Result.Left + 2, Result.Bottom - GetQATHeight, Result.Right - 2, Result.Bottom);
    end
    else
    begin
      if Caption.Visible then
      begin
        i := Caption.MinWidth;
        if (FCaptionButtons <> []) then
          i := i + (Width - GetCaptionButtonsRect.Left) + 2;
        i := Min(Width, i);  
        Result := Rect(TabSettings.StartMargin - 6, GetCaptionRect.Bottom - GetQATHeight{GetCaptionRect.Top+2}, Width - i, GetCaptionRect.Bottom);
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetCaptionButtonsRect: TRect;
begin
  Result := Rect(-1, -1, -1, -1);
  if (FCaption.Visible and (FCaptionButtons <> [])) then
  begin
    Result.Left := FCaptionMinBtn.Left;
    Result.Right := FCaptionCloseBtn.Left + FCaptionCloseBtn.Width;
    Result.Top := FCaptionMaxBtn.Top;
    Result.Bottom := Result.Top + FCaptionMaxBtn.Height;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateShapeButton;
var
  i: integer;
begin

  for i := 0 to ControlCount - 1 do
  begin
    if (Controls[i].ClassName = 'TAdvShapeButton') then
    begin
      Controls[i].Invalidate;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateCaptionButtons(UpdateImage: Boolean);
var
  sp, W: Integer;
  bmp: TBitMap;
  R: TRect;
  PrtForm: TCustomForm;
begin
  if not FCaption.Visible or (FCaptionButtons = []) then
  begin
    if (FCaptionCloseBtn <> nil) or (FCaptionMinBtn <> nil) or (FCaptionMaxBtn <> nil) then
      FCaption.RightIndent := FOldCapRightIndent;
    if (FCaptionCloseBtn <> nil) then
    begin
      FCaptionCloseBtn.Free;
      FCaptionCloseBtn := nil;
    end;
    if (FCaptionMinBtn <> nil) then
    begin
      FCaptionMinBtn.Free;
      FCaptionMinBtn := nil;
    end;
    if (FCaptionMaxBtn <> nil) then
    begin
      FCaptionMaxBtn.Free;
      FCaptionMaxBtn := nil;
    end;
    Exit;
  end;

  sp := 2;
  W := 16;
  if (FCaptionButtons <> []) then
  begin
    if (FCaptionCloseBtn = nil) then
    begin
      FOldCapRightIndent := FCaption.RightIndent;
      FCaptionCloseBtn := TAdvGlowButton.Create(self);
      FCaptionCloseBtn.Parent := Self;
      FCaptionCloseBtn.Caption := '';
      FCaptionCloseBtn.Transparent := True;
      FCaptionCloseBtn.OnClick := OnCaptionCloseBtnClick;
      FCaptionCloseBtn.Width := W;
      FCaptionCloseBtn.Height := W;
    end;
    if (FCaptionMinBtn = nil) then
    begin
      FCaptionMinBtn := TAdvGlowButton.Create(self);
      FCaptionMinBtn.Parent := Self;
      FCaptionMinBtn.Caption := '';
      FCaptionMinBtn.Transparent := True;
      FCaptionMinBtn.OnClick := OnCaptionMinBtnClick;
      FCaptionMinBtn.Width := W;
      FCaptionMinBtn.Height := W;
    end;
    if (FCaptionMaxBtn = nil) then
    begin
      FCaptionMaxBtn := TAdvGlowButton.Create(self);
      FCaptionMaxBtn.Parent := Self;
      FCaptionMaxBtn.Caption := '';
      FCaptionMaxBtn.Transparent := True;
      FCaptionMaxBtn.OnClick := OnCaptionMaxBtnClick;
      FCaptionMaxBtn.Width := W;
      FCaptionMaxBtn.Height := W;
    end;

    if Assigned(FCurrentToolBarStyler) then
    begin
      FCaptionCloseBtn.Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
      FCaptionMinBtn.Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
      FCaptionMaxBtn.Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance); 
    end;

    FCaptionCloseBtn.Left := Self.Width - ADVPAGE_OFFSET - sp - FCaptionCloseBtn.Width;
    FCaptionMaxBtn.Left := FCaptionCloseBtn.Left - sp - FCaptionMaxBtn.Width;
    FCaptionMinBtn.Left := FCaptionMaxBtn.Left - sp - FCaptionMinBtn.Width;

    FCaptionCloseBtn.Top := GetCaptionRect.Top + ADVPAGE_OFFSET; //GetCaptionRect.Bottom - ADVPAGE_OFFSET - FCaptionCloseBtn.Height;
    FCaptionMinBtn.Top := FCaptionCloseBtn.Top;
    FCaptionMaxBtn.Top := FCaptionCloseBtn.Top;

    FCaption.RightIndent := Max(FCaption.RightIndent, Width - FCaptionMinBtn.Left);

    if Assigned(FCurrentToolBarStyler) and UpdateImage then
    begin
      if (FCaptionBtnImages = nil) then
      begin
        FCaptionBtnImages := TImageList.Create(Self);
        FCaptionBtnImages.Width := 14;
        FCaptionBtnImages.Height := 14;
        FCaptionBtnImages.DrawingStyle := dsTransparent;
        FCaptionBtnImages.Masked := true;
      end;
      FCaptionBtnImages.Clear;

      bmp := TBitMap.Create;
      bmp.Width := 14;
      bmp.Height := 14;
      bmp.Transparent := True;
      R := Rect(0, 0, FCaptionCloseBtn.Width, FCaptionCloseBtn.Height);

      bmp.Canvas.Brush.Color := clFuchsia;
      bmp.Canvas.Pen.Color := clFuchsia;
      bmp.Canvas.Rectangle(R);
      DrawCross(bmp.Canvas, R, FCurrentToolBarStyler.PagerCaption.TextColor, 7);
      FCaptionBtnImages.AddMasked(bmp, clFuchsia);
      FCaptionCloseBtn.Images := FCaptionBtnImages;
      FCaptionCloseBtn.ImageIndex := 0;

      bmp.Canvas.Brush.Color := clFuchsia;
      bmp.Canvas.Pen.Color := clFuchsia;
      bmp.Canvas.Rectangle(R);
      PrtForm := GetParentForm(Self);
      if (PrtForm <> nil) then
      begin
        if (PrtForm.WindowState = wsNormal) then
          DrawNormalIcon(bmp.Canvas, R, FCurrentToolBarStyler.PagerCaption.TextColor, True)
        else
          DrawMaximize(bmp.Canvas, R, FCurrentToolBarStyler.PagerCaption.TextColor, True);
        FCaptionBtnImages.AddMasked(bmp, clFuchsia);
        FCaptionMaxBtn.Images := FCaptionBtnImages;
        FCaptionMaxBtn.ImageIndex := 1;
      end;

      bmp.Canvas.Brush.Color := clFuchsia;
      bmp.Canvas.Pen.Color := clFuchsia;
      bmp.Canvas.Rectangle(R);
      DrawMinimize(bmp.Canvas, R, FCurrentToolBarStyler.PagerCaption.TextColor, True);
      FCaptionBtnImages.AddMasked(bmp, clFuchsia);
      FCaptionMinBtn.Images := FCaptionBtnImages;
      FCaptionMinBtn.ImageIndex := 2;

      bmp.Free;
    end;
    
    FCaptionCloseBtn.Visible := True;
    FCaptionMinBtn.Visible := True;
    FCaptionMaxBtn.Visible := True;
    FCaptionCloseBtn.Enabled := (cbClose in FCaptionButtons);
    FCaptionMinBtn.Enabled := (cbMinimize in FCaptionButtons);
    FCaptionMaxBtn.Enabled := (cbMaximize in FCaptionButtons);
    FCaptionCloseBtn.BringToFront;
    FCaptionMinBtn.BringToFront;
    FCaptionMaxBtn.BringToFront;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnCaptionCloseBtnClick(Sender: TObject);
var
  PrtForm: TCustomForm;
begin
  if Assigned(FOnCloseButtonClick) then
    FOnCloseButtonClick(FCaptionCloseBtn)
  else
  begin
    PrtForm := GetParentForm(Self);
    if (PrtForm <> nil) then
      PrtForm.Close;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnCaptionMaxBtnClick(Sender: TObject);
var
  PrtForm: TCustomForm;
begin
  if Assigned(FOnMaxButtonClick) then
    FOnMaxButtonClick(FCaptionMaxBtn)
  else
  begin
    PrtForm := GetParentForm(Self);
    if (PrtForm <> nil) then
    begin
      if (PrtForm.WindowState = wsNormal) then
        PrtForm.WindowState := wsMaximized
      else
        PrtForm.WindowState := wsNormal;
        
      UpdateCaptionButtons(True);  
    end;  
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnCaptionMinBtnClick(Sender: TObject);
//var
  //PrtForm: TCustomForm;
begin
  if Assigned(FOnMinButtonClick) then
    FOnMinButtonClick(FCaptionMinBtn)
  else
  begin
    Application.Minimize;
    //PrtForm := GetParentForm(Self);
    //if (PrtForm <> nil) then
    //  PrtForm.WindowState := wsMinimized;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetVersion: string;
var
  vn: Integer;
begin
  vn := GetVersionNr;
  Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn)));
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetVersion(const Value: string);
begin

end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetVersionNr: integer;
begin
  Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetOfficeHint(const Value: TAdvHintInfo);
begin
  FOfficeHint.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetAntiAlias(const Value: TAntiAlias);
begin
  FAntiAlias := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMDialogChar(var Message: TCMDialogChar);
var
  I: Integer;
begin
  FOnlyALT := False;
  if (GetKeyState(VK_MENU) and $8000 = $8000) then
  begin
  for I:= 0 to FAdvPages.Count-1 do
    if IsAccel(Message.CharCode, AdvPages[I].Caption) and CanShowTab(I) and CanFocus then
    begin
      Message.Result := 1;
      ActivePageIndex := I;
      Exit;
    end;
  end;
  
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.WMKeyDown(var Message: TWMKeyDown);
var
  ATB: TAdvToolBar;
  i, c: Integer;
  s, sub: String;
  found: Boolean;
  Ctrl: TWinControl;
  obj: TObject;
  ShCutHint: string;
begin
  case Message.CharCode of
    VK_LEFT:
    begin
      HideShortCutHintOfAllPages;
      SelectNextPage(False);
    end;
    VK_RIGHT:
    begin
      HideShortCutHintOfAllPages;
      SelectNextPage(True);
    end;
    VK_DOWN:
    begin
      if Assigned(ActivePage) and Focused and (ActivePage.AdvToolBarCount > 0) and (ActivePage.AdvToolBars[0].CanFocus) then
      begin
        ATB := ActivePage.GetFirstToolBar(True);
        ATB.SetFocus; //ActivePage.AdvToolBars[0].SetFocus;
        HideShortCutHintOfAllPages;
        //ActivePage.ShowShortCutHintOfAllToolBars;  //--- should not show shortcut on arrow down
      end;
    end;
    VK_ESCAPE:
    begin
      HideShortCutHintOfAllPages;
      if Assigned(Self.Parent) then
      begin
        Ctrl := TProWinControl(Self.Parent).FindNextControl(Self, False, False, True);
        if Assigned(Ctrl) and Ctrl.CanFocus then
        begin
          Ctrl.SetFocus;
        end;
      end;
    end;
    else
    begin
      if FTabShortCutHintShowing then
      begin
        s := char(Message.CharCode);
        FTabShortCutChars := FTabShortCutChars + s;
        found := False;
        c := 0;
        for i := 0 to FAdvPages.Count-1 do
        begin
          if (UpperCase(AdvPages[i].ShortCutHint) = UpperCase(FTabShortCutChars)) then
          begin
            HideShortCutHintOfAllPages;
            if AdvPages[i].TabEnabled and AdvPages[i].TabVisible then
            begin
              ActivePageIndex := i;
              if Assigned(ActivePage) then
              begin
                if Expanded then
                begin
                  ATB := ActivePage.GetFirstToolBar(True);
                  if Assigned(ATB) then
                    ATB.SetFocus; //ActivePage.AdvToolBars[0].SetFocus;
                  ActivePage.ShowShortCutHintOfAllToolBars;
                end
                else
                begin
                  if not IsFloatingRibbonShowing then
                  begin
                    ShowFloatingRibbon;
                  end;

                  if Assigned(ActivePage) and Assigned(ActivePage.FSelfClone) then
                  begin
                    ATB := ActivePage.FSelfClone.GetFirstToolBar(True);
                    if Assigned(ATB) then
                      ATB.SetFocus; //ActivePage.AdvToolBars[0].SetFocus;
                    ActivePage.FSelfClone.ShowShortCutHintOfAllToolBars;
                  end;
                end;
              end;
            end;  
            found := True;
            Break;
          end
          else if (Length(AdvPages[i].ShortCutHint) > 0) then
          begin
            sub := Copy(AdvPages[i].ShortCutHint, 1, Length(FTabShortCutChars));
            if (UpperCase(sub) <> UpperCase(FTabShortCutChars)) then
            begin
              AdvPages[i].HideShortCutHint;
            end
            else
            begin
              found := True;
            end;
          end;

          if Assigned(AdvPages[i].FShortCutHint) and (AdvPages[i].FShortCutHint.Visible) then
          begin
            Inc(c);
          end;
        end;

        //-- Quick Access ToolBar
        if not found then
        begin
          if Assigned(FQuickAccessToolBar) then
          begin
            //i := 0;
            found := FQuickAccessToolBar.HasShortCut(FTabShortCutChars, c);
            if found then
            begin
              HideShortCutHintOfAllPages;
            end;
          end;
        end;
        //--
        
        //-- AdvShapeButton hints
        for i:= 0 to ControlCount - 1 do
        begin
          if (UpperCase(Controls[i].ClassName) = 'TADVSHAPEBUTTON') then
          begin
            if IsPublishedProp(Controls[i],'ShortCutHint') then
            begin
              obj := GetObjectProp(Controls[i],'ShortCutHint');

              if Assigned(obj) then
              begin
                ShCutHint := string(obj);

                if (UpperCase(ShCutHint) = UpperCase(FTabShortCutChars)) then
                begin
                  // Click buton
                  if Controls[i].Enabled then
                  begin
                    TProControl(Controls[i]).Invalidate;
                    TProControl(Controls[i]).Click;
                  end;    
                  HideShortCutHintOfAllPages;
                  found := True;
                  Break;
                end
                else if (Length(ShCutHint) > 0) then
                begin
                  sub := Copy(ShCutHint, 1, Length(FTabShortCutChars));
                  if (UpperCase(sub) <> UpperCase(FTabShortCutChars)) then
                  begin
                    // Hide Hint
                    Controls[i].Perform(CM_HINTSHOW, 1, 0);
                  end
                  else
                  begin
                    found := True;
                  end;
                end;

                {if Assigned(AdvPages[i].FShortCutHint) and (AdvPages[i].FShortCutHint.Visible) then
                begin
                  Inc(c);
                end;}
              end;
            end;
          end;
        end;

        if (c = 0) then
        begin
          HideShortCutHintOfAllPages;
          FTabShortCutHintShowing := False;
        end;

        if not found then
        begin
          Beep;
        end;
      end;
    end;
  end;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
  Message.Result := DLGC_WANTARROWS + DLGC_WANTCHARS;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.KeyDown(var Key: Word; Shift: TShiftState);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.ShowShortCutHintOfAllPages;
var
  i: Integer;
begin
  if not FTabShortCutHintShowing and CANCAPTURE then
  begin
    SetCapture(Handle);
  end;

  for I:= 0 to FAdvPages.Count-1 do
  begin
    AdvPages[I].ShowShortCutHint;
  end;

  if Assigned(FQuickAccessToolBar) then
  begin
    FQuickAccessToolBar.ShowShortCutHintOfButtons;
  end;

  FTabShortCutHintShowing := True;
  FTabShortCutChars := '';

  //--- TAdvShapeButton hints
  for i := 0 to ControlCount - 1 do
  begin
    if (UpperCase(Controls[i].ClassName) = 'TADVSHAPEBUTTON') then
    begin
      Controls[i].Perform(CM_HINTSHOW, 1, 1{0});
      //SendMessage(Handle, CM_HINTSHOW, 0, 0);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.HideShortCutHintOfAllPages(ToolBarHint: Boolean = false);
var
  i: Integer;
begin
  if (GetCapture = Handle) and CANCAPTURE then
    ReleaseCapture;

  for I:= 0 to FAdvPages.Count-1 do
  begin
    AdvPages[I].HideShortCutHint;
    if ToolBarHint then
      AdvPages[I].HideShortCutHintOfAllToolBars;
  end;

  if Assigned(FQuickAccessToolBar) then
  begin
    FQuickAccessToolBar.HideShortCutHintOfButtons;
  end;

  //--- TAdvShapeButton hints
  if FTabShortCutHintShowing then
  begin
    for i:= 0 to ControlCount - 1 do
    begin
      if (UpperCase(Controls[i].ClassName) = 'TADVSHAPEBUTTON') then
      begin
        Controls[i].Perform(CM_HINTSHOW, 1, 0);
      end;
    end;
  end;

  FTabShortCutHintShowing := False;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.KeyUp(var Key: Word; Shift: TShiftState);
begin
  inherited;
  FALTDown := (ssALT in Shift);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnShortCutTime(Sender: TObject);
var
  DoShowShortCut: Boolean;
  PForm: TCustomForm;
begin
  {FShortCutTimer.Enabled := False;
  if (GetKeyState(18) and $8000 = $8000) and Focused then
    ShowShortCutHintOfAllPages;}
  if FOnlyALT then
  begin
    DoShowShortCut := not ((GetKeyState(VK_MENU) and $8000 = $8000)) and not ((GetKeyState(VK_F10) and $8000 = $8000));
    if DoShowShortCut then
    begin
      FShortCutDelay := 0;
      FShortCutTimer.Enabled := False;
      FOnlyALT := False;
      FALTDown := False;
      PForm := GetParentForm(Self);
      if Assigned(PForm) and (GetActiveWindow = PForm.Handle) then
      begin
        if not Focused then
          Self.SetFocus;
        ShowShortCutHintOfAllPages;
      end;
      if Assigned(ActivePage) then
        if ActivePage.FToolBarShortCutShowing then
          ActivePage.HideShortCutHintOfAllToolBars;
    end
    else
    begin
      FShortCutDelay := FShortCutDelay + FShortCutTimer.Interval;
      if (FShortCutDelay >= SHORTCUT_DELAY) and (GetKeyState(VK_MENU) and $8000 = $8000) then
      begin
        FShortCutDelay := 0;
        FShortCutTimer.Enabled := False;
        FOnlyALT := False;
        PForm := GetParentForm(Self);
        if Assigned(PForm) and (GetActiveWindow = PForm.Handle) then
        begin
          if not Focused then
            Self.SetFocus;
          ShowShortCutHintOfAllPages;
        end;
        if Assigned(ActivePage) then
          if ActivePage.FToolBarShortCutShowing then
            ActivePage.HideShortCutHintOfAllToolBars;
      end;
    end;
  end
  else
  begin
    FShortCutTimer.Enabled := False;
    FOnlyALT := False;
    FShortCutDelay := 0;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMDialogKey(var Message: TCMDialogKey);
begin
  if TabStop and Assigned(ActivePage) and (Message.CharCode in [VK_MENU, VK_F10] {18 ALT}) then
  begin
    if not FTabShortCutHintShowing and (CanFocus) then
    begin
      {if not Focused then
        Self.SetFocus;}
      Message.Result := 1;
      FALTDown := True;
      FOnlyALT := True;
      if not FTabShortCutHintShowing then
      begin
        FShortCutTimer.Enabled := True;
      end;
      {if Assigned(ActivePage) then
        if ActivePage.FToolBarShortCutShowing then
          ActivePage.HideShortCutHintOfAllToolBars;
      Exit;}
    end
    else if FTabShortCutHintShowing and not FALTDown then
    begin
      HideShortCutHintOfAllPages;
      Message.Result := 1;
      Exit;
    end;
  end
  else
  begin
    FOnlyALT := False;
  end;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CMFocusChanged(var Message: TCMFocusChanged);
var
  i: Integer;
  h: HWND;
  Active: Boolean;
begin
  inherited;
  //HideShortCutHintOfAllPages;
  //if Assigned(ActivePage) then
    //ActivePage.HideShortCutHintOfAllToolBars;

  Active := Self.Focused;
  if not Active and (Message.Sender <> Self) and (self.HandleAllocated) then
  begin
    h := GetFocus;
    i := 1;
    while (h <> 0) do
    begin
      if (h = self.Handle) then
      begin
        Active := True;
        Break;
      end;
      h := GetParent(h);
      inc(i);
      if (i > 50) then
        Break;
    end;
  end;

  if not Active then
  begin
    HideShortCutHintOfAllPages;
    if Assigned(ActivePage) then
      ActivePage.HideShortCutHintOfAllToolBars;
  end;

  InvalidateTab(-1);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.CanShowTab(PageIndex: Integer): Boolean;
begin
  Result := (PageIndex >= 0) and (PageIndex < FAdvPages.Count) and (AdvPages[PageIndex].TabVisible);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.MoveAdvPage(CurIndex, NewIndex: Integer);
var
  OldActivePage: TAdvPage;
begin
  if (CurIndex >= 0) and (CurIndex < FAdvPages.Count) and
     (NewIndex >= 0) and (NewIndex < FAdvPages.Count) then
  begin
    OldActivePage := ActivePage;
    FAdvPages.Move(CurIndex, NewIndex);
    ActivePage := OldActivePage;
    UpdateTabScroller;
    UpdateTabPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetPageLeftMargin(const Value: Integer);
begin
  if (FPageLeftMargin <> Value) and (Value >= 0) then
  begin
    FPageLeftMargin := Value;
    SetAllPagesPosition;
    if Assigned(ActivePage) then
      ActivePage.Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetPageRightMargin(const Value: Integer);
begin
  if (FPageRightMargin <> Value) and (Value >= 0) then
  begin
    FPageRightMargin := Value;
    SetAllPagesPosition;
    if Assigned(ActivePage) then
      ActivePage.Invalidate;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.CreateShortCutHintWin: TShortCutHintWindow;
begin
  Result := TShortCutHintWindow.Create(Self);
  Result.Color := clWhite;
  Result.ColorTo := FCurrentToolBarStyler.ButtonAppearance.Color;
  Result.Parent := Self;
  FShortCutHintWinList.Add(Result);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DestroyShortCutHintWin(ShortCutWin: TShortCutHintWindow);
var
  i: Integer;
begin
  i := FShortCutHintWinList.IndexOf(ShortCutWin);
  if (i >= 0) then
  begin
    TShortCutHintWindow(FShortCutHintWinList.Items[i]).Free;
    FShortCutHintWinList.Items[i] := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.WndProc(var Msg: TMessage);
var
  p: TWinControl;
begin

  if (Msg.Msg = WM_DESTROY) then
  begin
    // restore subclassed proc
    if not (csDesigning in ComponentState) then
    begin
      p := self;
      repeat
        p := p.Parent;
      until (p is TForm) {$IFNDEF TMSDOTNET} or (p is TActiveForm) {$ENDIF} or not Assigned(p);

      if (p <> nil) then
        p.WindowProc := FFormWndProc;
    end;
  end;

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.PrevActivePage;
var
  i: integer;
  found: boolean;
begin
  i := ActivePageIndex;
  found := false;
  while (i > 0) do
  begin
    i := i - 1;
    if (i >= 0) and AdvPages[i].TabEnabled and AdvPages[i].TabVisible then
    begin
      found := true;
      break;
    end;
  end;

  if found then
    ActivePageIndex := i;
end;

procedure TAdvToolBarPager.NextActivePage;
var
  i: integer;
  found: boolean;
begin
  i := ActivePageIndex;
  found := false;
  while (i < AdvPageCount - 1) do
  begin
    i := i + 1;
    if (i < AdvPageCount) and AdvPages[i].TabEnabled and AdvPages[i].TabVisible then
    begin
      found := true;
      break;
    end;
  end;

  if found then
    ActivePageIndex := i;
end;

procedure TAdvToolBarPager.SubclassProc(var Msg: TMessage);
var
  pt: TPoint;
begin
  if (Msg.Msg = CM_MOUSEWHEEL) and EnableWheel and Expanded then
  begin
    GetCursorPos(pt);
    pt := ScreenToClient(pt);

    if PtInRect(ClientRect,pt) and (not NonActiveMouseWheelOnFocus or (GetFocus <> self.Handle)) then
    begin
      if (Msg.Wparam > 0) then
      begin
        PrevActivePage;
      end
      else
      begin
        NextActivePage;
      end;
      
      Msg.Result := 1;
      Exit;
      
    end;
  end;

  FFormWndProc(Msg);

  //if (Msg.Msg = WM_CLOSE) then

  if ((Msg.Msg = WM_MOVING) or (Msg.Msg = WM_LBUTTONDOWN) or (Msg.Msg = WM_SIZE)) or
     ((Msg.Msg = WM_SYSCOMMAND) and ((Msg.WParam = SC_MAXIMIZE) or (Msg.WParam = SC_MINIMIZE))) then
  begin
    HideShortCutHintOfAllPages(True);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CreateWnd;
var
  p: TWinControl;
  t: TAdvPage;
  gotpages: boolean;
  i: integer;
begin
  inherited;

  gotpages := false;

  if not (csDesigning in ComponentState) then
  begin
    p := self;

    repeat
      p := p.Parent;
    until (p is TForm) {$IFNDEF TMSDOTNET} or (p is TActiveForm) {$ENDIF} or not Assigned(p);

    if Assigned(p) then
    begin
      for i := 0 to p.ComponentCount - 1 do
      begin
        if p.Components[i].Name = Name + '1' then
          gotpages := true;
      end;

      FFormWndProc := p.WindowProc;
      p.WindowProc := SubClassProc;
    end;
  end;

  if FDesignTime and (Name <> '') and not gotpages then
  begin
    FDesignTime := false;
    
    for i := 0 to self.ComponentCount - 1 do
    begin
      if self.Components[i].Name = Name + '1' then
        gotpages := true;
    end;

    if not gotpages then
    begin
      t := TAdvPage.Create(Owner);
      t.Parent := self;
      t.AdvToolBarPager := self;
      t.Name := Name + '1';
      t.Caption := t.Name;
      ActivePage := t;
      t := TAdvPage.Create(Owner);
      t.Parent := self;
      t.AdvToolBarPager := self;
      t.Name := Name + '2';
      t.Caption := t.Name;
      t := TAdvPage.Create(Owner);
      t.Parent := self;
      t.AdvToolBarPager := self;
      t.Name := Name + '3';
      t.Caption := t.Name;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnOptionPictureChanged(Sender: TObject);
begin
  Invalidate;
  if Assigned(ActivePage) then
  begin
    ActivePage.Invalidate;
    ActivePage.InvalidateAllAdvToolBars;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetOptionPicture(const Value: TGDIPPicture);
begin
  FIOptionPicture.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetOptionDisabledPicture(
  const Value: TGDIPPicture);
begin
  FIOptionDisabledPicture.Assign(Value);
end;

//------------------------------------------------------------------------------

{ Auto MDI Buttons Support }

var
  MDIToolBarPager: TAdvToolBarPager;
  WindowProcHooked: Boolean;

function PagerWindowProc(hWnd: HWND; uMsg: Integer; WParam: WPARAM; lParam: LPARAM): LRESULT; {$IFNDEF TMSDOTNET} stdcall; {$ENDIF}
begin
  if Assigned(MDIToolBarPager) then
  begin
    if (uMsg = WM_WINDOWPOSCHANGED) then
    begin

      MDIToolBarPager.Invalidate;
    end;
  end;
  Result := CallWindowProc(IntPtr(GetWindowLong(hWnd, GWL_USERDATA)), hwnd, uMsg, wParam, lParam);
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetMDIButtonsRectRect: TRect;
begin
  Result := Rect(-1, -1, -1, -1);
  if FMDIButtonsVisible and FAutoMDIButtons then
  begin
    if FTabScroller.Visible then
      Result := GetTabScrollerRect
    else
      Result := GetTabsRect;
    Result.Left := Result.Right + 2;
    Result.Right := Result.Left + ((FMDIButtonsWidth + FMDIButtonsSpace)*3);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetAutoMDIButtons(const Value: Boolean);
var
  WindowHandle: THandle;
  OldWndProc: Integer;
begin
  if (FAutoMDIButtons <> Value) then
  begin
    FAutoMDIButtons := Value;
    if (csDesigning in ComponentState) or (csLoading in ComponentState) then
      Exit;

    if FAutoMDIButtons then
    begin
      WindowHandle :=  GetParentForm(Self).Handle;
      if (GetWindowLong(WindowHandle, GWL_WNDPROC) <> Integer(@PagerWindowProc)) then
      begin
        MDIToolBarPager := Self;
        FMDIChildForm := nil;
        SetWindowLong(WindowHandle, GWL_USERDATA, GetWindowLong(WindowHandle, GWL_WNDPROC));
        SetWindowLong(WindowHandle, GWL_WNDPROC, Integer(@PagerWindowProc));
        WindowProcHooked := True;
      end;
    end
    else
    begin
      if WindowProcHooked then
      begin // UnHook here
        WindowProcHooked := False;
        MDIToolBarPager := nil;
        FMDIChildForm := nil;

        WindowHandle := GetParentForm(Self).Handle;
        OldWndProc := GetWindowLong(WindowHandle, GWL_USERDATA);
        SetWindowRgn(WindowHandle, 0, True);
        if OldWndProc <> 0 then
        begin
          SetWindowLong(WindowHandle, GWL_WNDPROC, OldWndProc);
          SetWindowLong(WindowHandle, GWL_USERDATA, 0);
        end;

        Invalidate;
      end;
      FAutoMDIButtons := False;
    end;

    UpdateMDIButtons(True);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetMDIButtonsVisible(const Value: Boolean);
begin
  if (FMDIButtonsVisible <> Value) then
  begin
    FMDIButtonsVisible := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateMDIButtonsShowing;
var
  OldValue: Boolean;
begin
  OldValue := FMDIButtonsVisible;
  if FAutoMDIButtons then
    FMDIChildForm := TProForm(GetParentForm(Self)).ActiveMDIChild
  else
    FMDIChildForm := nil;
  if FAutoMDIButtons and Assigned(FMDIChildForm) and (FMDIChildForm.WindowState = wsMaximized) then
    FMDIButtonsVisible := True
  else if FMDIButtonsVisible then
    FMDIButtonsVisible := False;

  if (OldValue <> FMDIButtonsVisible) then
    UpdateMDIButtons(True);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnMDICloseBtnClick(Sender: TObject);
begin
  FMDIChildForm := TProForm(GetParentForm(Self)).ActiveMDIChild;
  if FAutoMDIButtons and Assigned(FMDIChildForm) and (FMDIChildForm.WindowState = wsMaximized) and FMDIButtonsVisible then
    FMDIChildForm.Close;
  UpdateMDIButtons(True);  
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnMDIMaxBtnClick(Sender: TObject);
begin
  FMDIChildForm := TProForm(GetParentForm(Self)).ActiveMDIChild;
  if FAutoMDIButtons and Assigned(FMDIChildForm) and (FMDIChildForm.WindowState = wsMaximized) and FMDIButtonsVisible
    and (biMaximize in TProForm(FMDIChildForm).BorderIcons) then
    FMDIChildForm.WindowState := wsNormal;
  UpdateMDIButtons(True);  
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnMDIMinBtnClick(Sender: TObject);
begin
  FMDIChildForm := TProForm(GetParentForm(Self)).ActiveMDIChild;
  if FAutoMDIButtons and Assigned(FMDIChildForm) and (FMDIChildForm.WindowState = wsMaximized) and FMDIButtonsVisible
    and (biMinimize in TProForm(FMDIChildForm).BorderIcons) then
    FMDIChildForm.WindowState := wsMinimized;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.UpdateMDIButtons(UpdateImage: Boolean);
var
  sp, W: Integer;
  bmp: TBitMap;
  R: TRect;
  PrtForm: TCustomForm;
begin
  if (csDesigning in ComponentState) then
    Exit;

  PrtForm := GetParentForm(Self);
  {if FAutoMDIButtons and (Assigned(TProForm(PrtForm).ActiveMDIChild) and (TProForm(PrtForm).ActiveMDIChild.WindowState <> wsMaximized)) then
    FMDIButtonsVisible := True
  else if FMDIButtonsVisible then
    FMDIButtonsVisible := False;}

  if not FMDIButtonsVisible or not FAutoMDIButtons or (not Assigned(PrtForm)) or (Assigned(PrtForm) and (TForm(PrtForm).BorderIcons = []))
    or (Assigned(TProForm(PrtForm).ActiveMDIChild) and (TProForm(PrtForm).ActiveMDIChild.WindowState <> wsMaximized)) then
  begin
    if (FMDICloseBtn <> nil) then
    begin
      FMDICloseBtn.Visible := False;
      //FMDICloseBtn.Free;
      //FMDICloseBtn := nil;
    end;
    if (FMDIMinBtn <> nil) then
    begin
      FMDIMinBtn.Visible := False;
      //FMDIMinBtn.Free;
      //FMDIMinBtn := nil;
    end;
    if (FMDIMaxBtn <> nil) then
    begin
      FMDIMaxBtn.Visible := False;
      //FMDIMaxBtn.Free;
      //FMDIMaxBtn := nil;
    end;
    Exit;
  end;

  sp := FMDIButtonsSpace;
  W := FMDIButtonsWidth;
  if (TForm(PrtForm).BorderIcons <> []) then
  begin
    if (FMDICloseBtn = nil) then
    begin
      FMDICloseBtn := TAdvGlowButton.Create(self);
      FMDICloseBtn.Parent := Self;
      FMDICloseBtn.Caption := '';
      FMDICloseBtn.Transparent := True;
      FMDICloseBtn.OnClick := OnMDICloseBtnClick;
      FMDICloseBtn.Width := W;
      FMDICloseBtn.Height := W;
    end;
    if (FMDIMinBtn = nil) then
    begin
      FMDIMinBtn := TAdvGlowButton.Create(self);
      FMDIMinBtn.Parent := Self;
      FMDIMinBtn.Caption := '';
      FMDIMinBtn.Transparent := True;
      FMDIMinBtn.OnClick := OnMDIMinBtnClick;
      FMDIMinBtn.Width := W;
      FMDIMinBtn.Height := W;
    end;
    if (FMDIMaxBtn = nil) then
    begin
      FMDIMaxBtn := TAdvGlowButton.Create(self);
      FMDIMaxBtn.Parent := Self;
      FMDIMaxBtn.Caption := '';
      FMDIMaxBtn.Transparent := True;
      FMDIMaxBtn.OnClick := OnMDIMaxBtnClick;
      FMDIMaxBtn.Width := W;
      FMDIMaxBtn.Height := W;
    end;

    if Assigned(FCurrentToolBarStyler) then
    begin
      FMDICloseBtn.Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
      FMDIMinBtn.Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance);
      FMDIMaxBtn.Appearance.Assign(FCurrentToolBarStyler.GlowButtonAppearance); 
    end;

    R := GetMDIButtonsRectRect;
    FMDIMinBtn.Left := R.Left;
    FMDIMaxBtn.Left := FMDIMinBtn.Left + FMDIMinBtn.Width + sp;
    FMDICloseBtn.Left := FMDIMaxBtn.Left + FMDIMaxBtn.Width + sp;

    FMDICloseBtn.Top := R.Top + ((R.Bottom - R.Top - FMDICloseBtn.Height) div 2) - 4;
    FMDIMinBtn.Top := FMDICloseBtn.Top;
    FMDIMaxBtn.Top := FMDICloseBtn.Top;

    if Assigned(FCurrentToolBarStyler) and UpdateImage then
    begin
      if (FMDIBtnImages = nil) then
      begin
        FMDIBtnImages := TImageList.Create(Self);
        FMDIBtnImages.Width := 14;
        FMDIBtnImages.Height := 14;
        FMDIBtnImages.DrawingStyle := dsTransparent;
        FMDIBtnImages.Masked := true;
      end;
      FMDIBtnImages.Clear;

      bmp := TBitMap.Create;
      bmp.Width := 14;
      bmp.Height := 14;
      bmp.Transparent := True;
      R := Rect(0, 0, FMDICloseBtn.Width, FMDICloseBtn.Height);

      bmp.Canvas.Brush.Color := clFuchsia;
      bmp.Canvas.Pen.Color := clFuchsia;
      bmp.Canvas.Rectangle(R);
      DrawCross(bmp.Canvas, R, FCurrentToolBarStyler.PagerCaption.TextColor, 7);
      FMDIBtnImages.AddMasked(bmp, clFuchsia);
      FMDICloseBtn.Images := FMDIBtnImages;
      FMDICloseBtn.ImageIndex := 0;

      bmp.Canvas.Brush.Color := clFuchsia;
      bmp.Canvas.Pen.Color := clFuchsia;
      bmp.Canvas.Rectangle(R);
      PrtForm := GetParentForm(Self);
      if (PrtForm <> nil) then
      begin
        if (PrtForm.WindowState = wsNormal) then
          DrawNormalIcon(bmp.Canvas, R, FCurrentToolBarStyler.PagerCaption.TextColor, True)
        else
          DrawMaximize(bmp.Canvas, R, FCurrentToolBarStyler.PagerCaption.TextColor, True);
        FMDIBtnImages.AddMasked(bmp, clFuchsia);
        FMDIMaxBtn.Images := FMDIBtnImages;
        FMDIMaxBtn.ImageIndex := 1;
      end;

      bmp.Canvas.Brush.Color := clFuchsia;
      bmp.Canvas.Pen.Color := clFuchsia;
      bmp.Canvas.Rectangle(R);
      DrawMinimize(bmp.Canvas, R, FCurrentToolBarStyler.PagerCaption.TextColor, True);
      FMDIBtnImages.AddMasked(bmp, clFuchsia);
      FMDIMinBtn.Images := FMDIBtnImages;
      FMDIMinBtn.ImageIndex := 2;

      bmp.Free;
    end;

    FMDICloseBtn.Visible := True;
    FMDIMinBtn.Visible := True;
    FMDIMaxBtn.Visible := True;
    FMDICloseBtn.Enabled := Assigned(TProForm(PrtForm).ActiveMDIChild) and (biSystemMenu in TForm(TProForm(PrtForm).ActiveMDIChild).BorderIcons);
    FMDIMinBtn.Enabled := Assigned(TProForm(PrtForm).ActiveMDIChild) and (biMinimize in TForm(TProForm(PrtForm).ActiveMDIChild).BorderIcons);
    FMDIMaxBtn.Enabled := Assigned(TProForm(PrtForm).ActiveMDIChild) and (biMaximize in TForm(TProForm(PrtForm).ActiveMDIChild).BorderIcons);
    FMDICloseBtn.BringToFront;
    FMDIMinBtn.BringToFront;
    FMDIMaxBtn.BringToFront;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.WMLButtonDblClk(var Message: TWMLButtonDblClk);
var
  PrtForm: TCustomForm;
  Tab: integer;
  p: TPoint;
begin
  inherited;

  p := Point(Message.XPos, Message.YPos);

  if PtInRect(GetTabsArea, p) then
  begin
    Tab := PTOnTab(p.X, p.Y);
    if (Tab >= 0) then
    begin
      {if FExpanded then
        Collaps
      else
        Expand;
      }
      if Assigned(FOnTabDblClick) then
        FOnTabDblClick(Self, Tab);
    end;
  end;


  if (cbMaximize in FCaptionButtons) and (PtInRect(GetCaptionRect, Point(Message.XPos, Message.YPos))) then
  begin
    PrtForm := GetParentForm(Self);
    if (PrtForm <> nil) then
    begin
      if (PrtForm.WindowState = wsNormal) then
        PrtForm.WindowState := wsMaximized
      else
        PrtForm.WindowState := wsNormal;

      UpdateCaptionButtons(True);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetExpanded(Value: Boolean);
var
  R: TRect;
  i: Integer;
begin
  if Value then  // Expand
  begin
    if not FExpanded then
    begin
      i := FExpandedHeight;
      if ShowQATBelow then
        i := i + GetQATHeight;
      Height := i;
      FExpanded := Value;
      if Assigned(FOnExpand) then
        FOnExpand(Self);
    end;
  end
  else // Collaps
  begin
    if FExpanded then
    begin
      FExpandedHeight := Height;
      R := GetAdvPageRect;
      i := R.Top;
      if ShowQATBelow then
      begin
        i := i + GetQATHeight;
        FExpandedHeight := FExpandedHeight - GetQATHeight;
      end;
      Height := i;
      FExpanded := Value;
      if Assigned(FOnCollaps) then
        FOnCollaps(Self);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.Collaps;
begin
  SetExpanded(False);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.Expand;
begin
  SetExpanded(True);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetShowQATBelow(const Value: Boolean);
begin
  if (ShowQATBelow <> Value) then
  begin
    if Assigned(FQuickAccessToolBar) then
    begin
      if Value then
      begin
        Height := Height + GetQATHeight;
      end
      else
      begin
        Height := Height - GetQATHeight;
      end;
      FQuickAccessToolBar.FullSize := Value;
      SetAllPagesPosition;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetShowQATBelow: Boolean;
begin
  Result := Assigned(FQuickAccessToolBar) and FQuickAccessToolBar.FullSize and FQuickAccessToolBar.Visible;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.GetQATHeight: Integer;
begin
  Result := Caption.Height - 2;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.HideShortCutHint;
begin
  HideShortCutHintOfAllPages(True);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.ShowShortCutHint;
begin
  ShowShortCutHintOfAllPages;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetPersistence(const Value: TPersistence);
begin
  FPersistence.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnPersistenceChanged(Sender: TObject);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SaveState;
var
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
begin
  if (FPersistence.Enabled) and (FPersistence.Key <>'') and
     (FPersistence.Section <>'') and
     (not (csDesigning in ComponentState)) then
  begin
    {$IFDEF DELPHI4_LVL}
    if FPersistence.Location = plRegistry then
      IniFile := TRegistryIniFile.Create(FPersistence.Key)
    else
    {$ENDIF}
      IniFile := TIniFile.Create(FPersistence.Key);

    with IniFile do
    begin
      WriteInteger(FPersistence.section,'Minimized', Integer(not Expanded));
      WriteInteger(FPersistence.section,'ShowQATBelow', Integer(ShowQATBelow));
    end;
    IniFile.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.LoadState;
var
  {$IFDEF DELPHI4_LVL}
  IniFile: TCustomIniFile;
  {$ELSE}
  IniFile: TIniFile;
  {$ENDIF}
  i: Integer;
begin
  if (FPersistence.Enabled) and (FPersistence.Key <>'') and
     (FPersistence.Section<>'') and
     (not (csDesigning in ComponentState)) then
  begin
    {$IFDEF DELPHI4_LVL}
    if FPersistence.location = plRegistry then
      IniFile := TRegistryIniFile.Create(FPersistence.Key)
    else
    {$ENDIF}
      IniFile := TIniFile(tIniFile.Create(FPersistence.Key));

    with IniFile do
    begin
      i:= ReadInteger(FPersistence.section,'Minimized', Integer(not Expanded));

      if (i > 0) then
        Collaps;

      i := ReadInteger(FPersistence.section,'ShowQATBelow', Integer(ShowQATBelow));
      if (i > 0) then
        ShowQATBelow := True;
    end;
    IniFile.Free;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.SetHideState(const Value: Boolean);
var
  i: Integer;
begin
  if (FHideState <> Value) then
  begin
    FHideState := Value;
    if FHideState then
    begin
      FOldHeight := Self.Height;
      Height := Caption.Height;
      if Assigned(FQuickAccessToolBar) then
      begin
        FQATOldVisible := FQuickAccessToolBar.Visible;
        FQuickAccessToolBar.Visible := False;
      end;

      for i := 0 to ControlCount - 1 do
      begin
        if (Controls[i].ClassName = 'TAdvShapeButton') then
        begin
          FShapeBtnOldVisible := Controls[i].Visible;
          Controls[i].Visible := False;
          break;
        end;
      end;
    end
    else
    begin
      Height := FOldHeight;
      if Assigned(FQuickAccessToolBar) then
        FQuickAccessToolBar.Visible := FQATOldVisible;

      for i := 0 to ControlCount - 1 do
      begin
        if (Controls[i].ClassName = 'TAdvShapeButton') then
        begin
          Controls[i].Visible := FShapeBtnOldVisible;
          break;
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnDblClickTimer(Sender: TObject);
begin
  FDblClickTimer.Enabled := False;
  FClickCount := 0;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.CreateFloatingRibbon;
begin
  if (ActivePageIndex < 0) or not Assigned(ActivePage) then
    Exit;

  if (FMinimizedRibbonWindow = nil) then
  begin
    FMinimizedRibbonWindow := TMinimizedRibbonWindow.CreateNew(self);
    if Name <> '' then //give it a name for debugging
      FMinimizedRibbonWindow.Name := Name + '_RibbonWindow';
    FMinimizedRibbonWindow.Parent := Self;
    FMinimizedRibbonWindow.BorderIcons := [];
    FMinimizedRibbonWindow.BorderStyle := bsNone;
    FMinimizedRibbonWindow.Ctl3D := false;
    FMinimizedRibbonWindow.FormStyle := fsStayOnTop;
    FMinimizedRibbonWindow.Visible := False;
    FMinimizedRibbonWindow.Width := 0;
    FMinimizedRibbonWindow.Height := 0;
    FMinimizedRibbonWindow.AutoScroll := False;
    FMinimizedRibbonWindow.BorderWidth := 0;
    FMinimizedRibbonWindow.AdvToolBarPager := Self;
    FMinimizedRibbonWindow.OnCloseQuery := OnFloatingRibbonWindowCloseQuery;
    FMinimizedRibbonWindow.OnHide := OnRibbonWindowHide;
    FMinimizedRibbonWindow.OnClose := OnFloatingRibbonWindowClose;
    if Assigned(FCurrentToolBarStyler) then
      FMinimizedRibbonWindow.Color := FCurrentToolBarStyler.PagerCaption.BorderColor;
  end;

  if (FMinimizedRibbonWindow.AdvPage = nil) then
  begin
    FMinimizedRibbonWindow.AdvPage := ActivePage.CreateClone(FMinimizedRibbonWindow);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.DestroyFloatingRibbon;
begin
  if Assigned(FMinimizedRibbonWindow) then
  begin
    if Assigned(ActivePage) then
      ActivePage.DestroyClone;

    FMinimizedRibbonWindow.Free;
    FMinimizedRibbonWindow := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.ShowFloatingRibbon;
var
  p: TPoint;
  h, w: Integer;
begin
  if (ActivePageIndex < 0) or not Assigned(ActivePage) then
    Exit;

  CreateFloatingRibbon;

  FMinimizedRibbonWindow.SetWindowSize;
  w := FMinimizedRibbonWindow.Width;
  h := FMinimizedRibbonWindow.Height;
  FMinimizedRibbonWindow.Width := 1;
  FMinimizedRibbonWindow.Height := 1;
  FMinimizedRibbonWindow.Visible := True;

  //FMinimizedRibbonWindow.SetWindowSize;
  P := Point(GetAdvPageRect.Left - 2, GetTabsArea.Bottom);
  P := ClientToScreen(P);
  FMinimizedRibbonWindow.Left := P.X;
  FMinimizedRibbonWindow.Top := P.Y;
  //FMinimizedRibbonWindow.Visible := True;
  {$IFDEF DELPHI9_LVL}
  //FMinimizedRibbonWindow.Left := P.X;
  //FMinimizedRibbonWindow.Top := P.Y;
  {$ENDIF}
  FMinimizedRibbonWindow.width := w;
  FMinimizedRibbonWindow.Height := h;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnFloatingRibbonWindowCloseQuery(Sender: TObject; var CanClose: Boolean);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.HideFloatingRibbon;
begin
  if Assigned(FMinimizedRibbonWindow) then
  begin
    FMinimizedRibbonWindow.Hide;
    DestroyFloatingRibbon;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnRibbonWindowHide(Sender: TObject);
begin
  //DestroyFloatingRibbon;
end;

//------------------------------------------------------------------------------

function TAdvToolBarPager.IsFloatingRibbonShowing: Boolean;
begin
  Result := Assigned(FMinimizedRibbonWindow) and (FMinimizedRibbonWindow.Visible) and not Expanded;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.OnFloatingRibbonWindowClose(Sender: TObject;
  var Action: TCloseAction);
begin

end;

//------------------------------------------------------------------------------

procedure TAdvToolBarPager.HandleKey(Code: Word);
var
  shf, Ctrl, Alt: Boolean;
begin
  if (Code = VK_F1) then
  begin
    Shf := (GetKeyState(VK_SHIFT) and $8000 = $8000);
    Ctrl := (GetKeyState(VK_CONTROL) and $8000 = $8000);
    Alt := (GetKeyState(18) and $8000 = $8000);

    if Ctrl and not Shf and not Alt then
    begin
      if Expanded then
        Collaps
      else
        Expand;
    end;
  end;
end;

//------------------------------------------------------------------------------

{ TAdvPage }

constructor TAdvPage.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  ControlStyle := ControlStyle + [csAcceptsControls] - [csOpaque];
  FLeftATBIndex := 0;
  FAdvToolBars := TDbgList.Create;
  FCaption := '';
  FTabVisible := True;
  FTabEnabled := True;
  FImageIndex := -1;
  FAutoPosition := True;
  FTimer := nil;
  FTabHint := '';
  FLeftScrollBtn := nil;
  FRightScrollBtn := nil;
  FOfficeHint := TAdvHintInfo.Create;
  DoubleBuffered := true;

  FShortCutHint := nil;
  FShortCutHintPos := shpBottom;
  FToolBarScroller := TATBTabScroller.Create;
  FTabWidth := 0;
  FTabLeft := 0;
  FTabClientWidth := 0;
  FTabRealClientWidth := 0;
  FOldWidth := Width;
  FSelfClone := nil;
  FCloning := False;
end;

//------------------------------------------------------------------------------

destructor TAdvPage.Destroy;
begin
  if (FAdvToolBarPager <> nil) then
  begin
    FAdvToolBarPager.RemoveAdvPage(Self);
  end;

  //if Assigned(FShortCutHint) then
    //FShortCutHint.Free;
  
  FAdvToolBars.Free;
  FOfficeHint.Free;
  FToolBarScroller.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.AlignControls(AControl: TControl; var ARect: TRect);
begin
  inherited;
  UpdateAdvToolBarsPosition;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.CMShowingChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.CMVisibleChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

function TAdvPage.GetAdvToolBarCount: integer;
begin
  Result := FAdvToolBars.Count;
end;

//------------------------------------------------------------------------------

function TAdvPage.GetAdvToolBars(index: integer): TAdvToolBar;
begin
  Result := nil;
  if (Index >= 0) and (Index < FAdvToolBars.Count) then
    Result := FAdvToolBars[Index];
end;

//------------------------------------------------------------------------------

function TAdvPage.IndexOfAdvToolBar(ToolBar: TAdvToolBar): Integer;
begin
  Result := FAdvToolBars.IndexOf(ToolBar);
end;

//------------------------------------------------------------------------------

function TAdvPage.CreateAdvToolBar: TAdvToolBar;
begin
  Result := TAdvToolBar.Create(Self);
  Result.AutoSize := False;
  Result.ShowRightHandle := False;
  Result.ShowCaption := True;
  Result.CaptionPosition := cpBottom;
  Result.CaptionAlignment := taCenter;
  Result.Width := 120;
  Result.Height := 26;
  Result.Caption := 'Untitled';
  AddAdvToolBar(Result);
  Result.ParentStyler := True;

  if not (csDesigning in ComponentState) and not (csLoading in ComponentState) then
    Result.FPropertiesLoaded := True;
end;

//------------------------------------------------------------------------------

function TAdvPage.AddAdvToolBar(ToolBar: TAdvToolBar): Integer;
begin
  Result := -1;
  if not Assigned(ToolBar) or FCloning then
    Exit;
  if (FAdvToolBars.IndexOf(ToolBar) < 0) then
  begin
    if not (csLoading in ComponentState) and not (csDesigning in ComponentState) then
    begin
      ToolBar.ShowRightHandle := False;
      ToolBar.ShowCaption := True;
      ToolBar.CaptionPosition := cpBottom;
      ToolBar.CaptionAlignment := taCenter;
    end;

    Result := FAdvToolBars.Add(ToolBar);
    if (ToolBar.Parent <> Self) then
      ToolBar.Parent := Self;
    if not (csLoading in ComponentState) and not (csDesigning in ComponentState) and not Assigned(ToolBar.ToolBarStyler) then
      ToolBar.ParentStyler := True;  
    UpdateAdvToolBarsPosition;

  if not (csDesigning in ComponentState) and not (csLoading in ComponentState) and not (csReading in ComponentState) and not ToolBar.FPropertiesLoaded then
    ToolBar.FPropertiesLoaded := True;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.RemoveAdvToolBar(ToolBar: TAdvToolBar);
var
  I: Integer;
begin
  if FCloning then
    Exit;
    
  I := FAdvToolBars.IndexOf(ToolBar);
  if (I >= 0) then
  begin
    FAdvToolBars.Delete(I);
    if (ToolBar.Parent = Self) and not (csDestroying in ToolBar.ComponentState) then
      ToolBar.Parent := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.InsertAdvToolBar(Index: integer; ToolBar: TAdvToolBar);
begin
  if (FAdvToolBars.IndexOf(ToolBar) < 0) and not FCloning then
  begin
    FAdvToolBars.Insert(Index, ToolBar);
    if (ToolBar.Parent <> Self) then
    begin
      ToolBar.Parent := Self;
    end;
    UpdateAdvToolBarsPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.MoveAdvToolBar(CurIndex, NewIndex: Integer);
begin
  if not FCloning and (CurIndex >= 0) and (CurIndex < FAdvToolBars.Count) and (NewIndex >= 0) and (NewIndex < FAdvToolBars.Count) then
  begin
    FAdvToolBars.Move(CurIndex, NewIndex);
    UpdateAdvToolBarsPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.Loaded;
var
  i, j: Integer;
  added: Boolean;
begin
  inherited;

  FAdvToolBars.Clear;
  for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TAdvToolBar) then
    begin
      added := False;
      for j := 0 to FAdvToolBars.Count-1 do
      begin
        if (AdvToolBars[j].Left > TAdvToolBar(Controls[i]).Left) then
        begin
          FAdvToolBars.Insert(j, Controls[i]);
          added := True;
          Break;
        end;
      end;

      if not added then
      begin
        FAdvToolBars.Add(Controls[i]);
      end;
    end;
  end;

  UpdateAdvToolBarsPosition;
  UpdateAllToolBars;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvPage.Paint;
var
  R, TabR: TRect;
  i: Integer;
  LnClr: TColor;
  bmp: TBitMap;
begin
  //inherited;

  if not Assigned(FAdvToolBarPager) or not Assigned(FAdvToolBarPager.FCurrentToolBarStyler) then
    Exit;

  if self.Color <> FAdvToolBarPager.FCurrentToolBarStyler.PageAppearance.Color then
    self.Color := FAdvToolBarPager.FCurrentToolBarStyler.PageAppearance.Color;

  R := ClientRect;

  bmp := TBitMap.Create;
  bmp.Height := R.Bottom - R.Top;
  bmp.Width := R.Right - R.Left;

  i := FAdvToolBarPager.GroupOfTab(FAdvToolBarPager.IndexOfPage(Self));
  if (FAdvToolBarPager.ActivePage = self) and (i >= 0) then
  begin
    if not FAdvToolBarPager.TabGroups.Items[i].DefaultAppearance then
    begin
      with FAdvToolBarPager.TabGroups.Items[i].GroupAppearance.PageAppearance do
      begin
        LnClr := Color;
       (* DrawVistaBackGround(Canvas, R, Color, ColorTo, ColorMirror, ColorMirrorTo, BorderColor,
          Gradient, GradientMirror, FCaption, Font, {ImgList, ImageIndex, EnabledImg, Layout, }
          Enabled{, GetFocus = self.Handle,Pic}, FAdvToolBarPager.FCurrentToolBarStyler.RoundEdges); *)
        DrawVistaGradient(bmp.Canvas, Rect(0, 0, bmp.Width, bmp.Height), Color, ColorTo, ColorMirror, ColorMirrorTo, BorderColor,
          Gradient, GradientMirror, '', Font, Enabled, False, FAdvToolBarPager.AntiAlias, FAdvToolBarPager.FCurrentToolBarStyler.RoundEdges);
        Canvas.Draw(R.Left, R.Top, bmp);
      end;
    end
    else
    begin
      with FAdvToolBarPager.FCurrentToolBarStyler.GroupAppearance.PageAppearance do
      begin
        LnClr := Color;
        (*DrawVistaBackGround(Canvas, R, Color, ColorTo, ColorMirror, ColorMirrorTo, BorderColor,
          Gradient, GradientMirror, FCaption, Font, {ImgList, ImageIndex, EnabledImg, Layout, }
          Enabled{, GetFocus = self.Handle,Pic}, FAdvToolBarPager.FCurrentToolBarStyler.RoundEdges);*)
        DrawVistaGradient(bmp.Canvas, Rect(0, 0, bmp.Width, bmp.Height), Color, ColorTo, ColorMirror, ColorMirrorTo, BorderColor,
          Gradient, GradientMirror, '', Font, Enabled, False, FAdvToolBarPager.AntiAlias, FAdvToolBarPager.FCurrentToolBarStyler.RoundEdges);
        Canvas.Draw(R.Left, R.Top, bmp);
      end;
    end;
  end
  else
  begin
    with FAdvToolBarPager.FCurrentToolBarStyler.PageAppearance do
    begin
      LnClr := Color;
     (* DrawVistaBackGround(Canvas, R, Color, ColorTo, ColorMirror, ColorMirrorTo, BorderColor,
        Gradient, GradientMirror, FCaption, Font, {ImgList, ImageIndex, EnabledImg, Layout, }
        Enabled{, GetFocus = self.Handle,Pic}, FAdvToolBarPager.FCurrentToolBarStyler.RoundEdges); *)

      //DrawVistaGradient(bmp.Canvas, Rect(0, 0, bmp.Width, bmp.Height), Color, ColorTo, ColorMirror, ColorMirrorTo, BorderColor,
        //Gradient, GradientMirror, '', Font, Enabled, False, FAdvToolBarPager.AntiAlias, FAdvToolBarPager.FCurrentToolBarStyler.RoundEdges);
      DrawVistaPageGradient(bmp.Canvas, Rect(0, 0, bmp.Width, bmp.Height), PAGEGRAD_HEIGHT, Color, ColorTo, ColorMirror, ColorMirrorTo, BorderColor, 3);

      Canvas.Draw(R.Left, R.Top, bmp);

      Canvas.Pen.Color := FAdvToolBarPager.FCurrentToolBarStyler.PageAppearance.ShadowColor;
      Canvas.MoveTo(R.Left + 2, R.Bottom - 1);
      Canvas.LineTo(R.Right-2, R.Bottom - 1);

      // Draw 3D effect
      Canvas.Pen.Color := FAdvToolBarPager.FCurrentToolBarStyler.PageAppearance.HighLightColor; //BlendColor(clWhite, BorderColor, 50);
      Canvas.MoveTo(R.Left+1, R.Top + 10);
      Canvas.LineTo(R.Left+1, R.Bottom-2);
      //Canvas.Pixels[R.Left+2, R.Bottom-3] := Canvas.Pen.Color;
      Canvas.MoveTo(R.Right-2, R.Top + 10);
      Canvas.LineTo(R.Right-2, R.Bottom - 2);
      //Canvas.Pixels[R.Right-3, R.Bottom-3] := Canvas.Pen.Color;

      Canvas.MoveTo(R.Left + 3, R.Bottom - 2);
      Canvas.LineTo(R.Right - 2, R.Bottom - 2);

    end;
  end;

  if (FAdvToolBarPager.ActivePage = self) then
  begin
    TabR := FAdvToolBarPager.GetTabVisibleRect(Self); //FAdvToolBarPager.GetTabRect(Self);
    if (FAdvToolBarPager.Align in [daTop, daBottom]) and (TabR.Left > 0) and (TabR.Right > 0) then
    begin
      if (FAdvToolBarPager.TabSettings.Height > 0) then
      begin
        // Attaching to Tab
        TabR.Left := TabR.Left - ADVPAGE_OFFSET - FAdvToolBarPager.PageLeftMargin;
        TabR.Right := TabR.Right - ADVPAGE_OFFSET - FAdvToolBarPager.PageLeftMargin;
        Canvas.Pen.Color := LnClr;
        Canvas.MoveTo(TabR.Left, 0);
        Canvas.LineTo(TabR.Right, 0);
      end;

      if FAdvToolBarPager.FCurrentToolBarStyler.RoundEdges then
      begin
        // Clean up edges
        Canvas.Pixels[R.Left, R.Top] := FAdvToolBarPager.Canvas.Pixels[self.Left - 1, self.Top - 1];
        Canvas.Pixels[R.Left + 1, R.Top] := FAdvToolBarPager.Canvas.Pixels[self.Left + 1, self.Top - 1];
        Canvas.Pixels[R.Left, R.Top + 1] := FAdvToolBarPager.Canvas.Pixels[self.Left - 1, self.Top];

        Canvas.Pixels[R.Left, R.Bottom - 1] := FAdvToolBarPager.Canvas.Pixels[self.Left - 1, self.Top + Height];
        Canvas.Pixels[R.Left + 1, R.Bottom - 1] := FAdvToolBarPager.Canvas.Pixels[self.Left - 1, self.Top + Height];
        Canvas.Pixels[R.Left, R.Bottom - 2] := FAdvToolBarPager.Canvas.Pixels[self.Left - 1, self.Top + Height];

        Canvas.Pixels[R.Right - 1, R.Top] := FAdvToolBarPager.Canvas.Pixels[self.Left + Width + 1, self.Top];
        Canvas.Pixels[R.Right - 2, R.Top] := FAdvToolBarPager.Canvas.Pixels[self.Left + Width + 1, self.Top];
        Canvas.Pixels[R.Right - 1, R.Top + 1] := FAdvToolBarPager.Canvas.Pixels[self.Left + Width + 1, self.Top];

        Canvas.Pixels[R.Right - 1, R.Bottom - 1] := FAdvToolBarPager.Canvas.Pixels[self.Left + Width +1, self.Top + Height];
        Canvas.Pixels[R.Right - 2, R.Bottom - 1] := FAdvToolBarPager.Canvas.Pixels[self.Left + Width +1, self.Top + Height];
        Canvas.Pixels[R.Right - 1, R.Bottom - 2] := FAdvToolBarPager.Canvas.Pixels[self.Left + Width +1, self.Top + Height];
      end;
    end;
  end;


  bmp.Free;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetAdvToolBarPager(const Value: TAdvToolBarPager);
begin
  if (FAdvToolBarPager <> Value) then
  begin
    if FAdvToolBarPager <> nil then FAdvToolBarPager.RemoveAdvPage(Self);
    Parent := Value;
    if (Value <> nil) then
    begin
      Value.AddAdvPage(Self);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
  if (AWidth <> Width) then
    FOldWidth := Width;
  inherited;
  UpdateAdvToolBarsPosition;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetParent(AParent: TWinControl);
var
  ci, ni: Integer;
  AToolBarPager: TAdvToolBarPager;
begin
  if (AParent is TAdvDockPanel) or (AParent is TAdvCustomToolBar){ or (AParent is TAdvPage)} then
    raise Exception.Create('Invalid Parent');

  if ((AParent is TAdvPage) or (AParent is TAdvToolBarPager)) and not (FUpdatingParent) then
  begin
    AToolBarPager := nil;
    if (AParent is TAdvPage) then
    begin
      AToolBarPager := TAdvPage(AParent).FAdvToolBarPager;
    end
    else if (AParent is TAdvToolBarPager) then
    begin
      AToolBarPager := TAdvToolBarPager(AParent);
    end;

    if Assigned(FAdvToolBarPager) and Assigned(AToolBarPager) then
    begin

      if (FAdvToolBarPager <> AToolBarPager) then
      begin
        FUpdatingParent := True;
        AdvToolBarPager := AToolBarPager;
        FUpdatingParent := False;
      end;

      if (FAdvToolBarPager = AToolBarPager) then
      begin
        if (AParent is TAdvPage) then
        begin
          ci := FAdvToolBarPager.IndexOfPage(self);
          ni := FAdvToolBarPager.IndexOfPage(TAdvPage(AParent));
          AParent := AToolBarPager;
          if (ci >= 0) and (ci < FAdvToolBarPager.FAdvPages.Count) and
             (ni >= 0) and (ni < FAdvToolBarPager.FAdvPages.Count) then
          begin
            FAdvToolBarPager.MoveAdvPage(ci, ni);
          end
          else
            raise Exception.Create('Invalid Parent '+inttostr(ci)+':'+inttostr(ni));
        end
        else if (AParent is TAdvToolBarPager) then
        begin
          AParent := AToolBarPager;
        end;

        FAdvToolBarPager.Invalidate;
        Invalidate;
      end
      else
        raise Exception.Create('Invalid Parent');
    end;
  end;

  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetTabVisible(const Value: Boolean);
var
  i: Integer;
begin
  if (FTabVisible <> Value) then
  begin
    FTabVisible := Value;
    // Hide CompactDropDown, in case if control over compactdropdown set TabVisibility
    if not FTabVisible then
    begin
      for i:= 0 to AdvToolBarCount-1 do
      begin
        AdvToolBars[i].HideCompactWindow;
      end;
    end;

    if Assigned(FAdvToolBarPager) then
    begin
      FAdvToolBarPager.UpdateTabSizes;
      FAdvToolBarPager.InitializeScroller; //InitializeTabsSize;
      FAdvToolBarPager.Invalidate;
      if Assigned(FAdvToolBarPager.ActivePage) then
        FAdvToolBarPager.ActivePage.Invalidate;
    end;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.TimerProc(Sender: TObject);
var
  P: TPoint;
begin
  case FGlowState of
    gsHover:
    begin
      FStepHover := FStepHover + FTimeInc;
      if ((FStepHover > 100) and (FTimeInc > 0))
         or ((FStepHover < 0) and (FTimeInc < 0)) then
      begin
        if (FStepHover > 100) and (FTimeInc > 0) and Assigned(FAdvToolBarPager) then
        begin
          FStepHover := 120;
          GetCursorPos(P);
          P := FAdvToolBarPager.ScreenToClient(P);
          if not PtInRect(FAdvToolBarPager.GetTabRect(Self), P) then
          begin
            FTimeInc := -20;
            FGlowState := gsHover;
            FAdvToolBarPager.FHotPageIndex := -1;
            Exit;
          end;
        end
        else if ((FStepHover < 0) and (FTimeInc < 0)) then
        begin
          FreeAndNil(FTimer);
          FGlowState := gsNone;
          if Assigned(FAdvToolBarPager) then
            FAdvToolBarPager.InvalidateTab(-1);
        end;

        FStepPush := 0;
        if (FStepHover > 100) then
          FStepHover := 120;
        if (FStepHover < 0) then
          FStepHover := -20;
      end
      else if Assigned(FAdvToolBarPager) then
        FAdvToolBarPager.InvalidateTab(-1);
    end;
    gsPush:
    begin
      FStepPush := FStepPush + FTimeInc;
      if ((FStepPush > 100) and (FTimeInc > 0))
         or ((FStepPush < 0) and (FTimeInc < 0)) then
      begin
        FreeAndNil(FTimer);
        FGlowState := gsNone;
        FStepPush := 0;
        //FStepHover := 0;
      end
      else if Assigned(FAdvToolBarPager) then
        FAdvToolBarPager.InvalidateTab(-1);
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvPage.WMSize(var Message: TWMSize);
begin
  inherited;
  //UpdateAllToolBars;
  if (FOldWidth <> Width) then
  begin
    if (FOldWidth > Width) then
      DecreaseToolBarSize
    else
      IncreaseToolBarSize;
  end;
  InitializeScroller;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.CMControlChange(var Message: TCMControlChange);
begin
  inherited;
  with Message do
  begin
    if (Control is TAdvToolBar) then
    begin
      if Inserting then
      begin
        AddAdvToolBar(TAdvToolBar(Control));
      end  
      else
        RemoveAdvToolBar(TAdvToolBar(Control));
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.CMControlListChange(var Message: TCMControlListChange);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.WMEraseBkGnd(var Message: TWMEraseBkGnd);
{var
  DC: HDC;
  i: Integer;
  p: TPoint; }
begin
  if {FTransparent} False then
  begin
    if Assigned(Parent) then
    begin
     { DC := Message.DC;
      i := SaveDC(DC);
      p := ClientOrigin;
      Windows.ScreenToClient(Parent.Handle, p);
      p.x := -p.x;
      p.y := -p.y;
      MoveWindowOrg(DC, p.x, p.y);
      SendMessage(Parent.Handle, WM_ERASEBKGND, DC, 0);
      SendMessage(Parent.Handle, WM_PAINT, DC, 0);
      if (Parent is TWinCtrl) then
        (Parent as TWinCtrl).PaintCtrls(DC, nil);
      RestoreDC(DC, i); }
    end;
  end
  else
  begin
    inherited;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.ReadState(Reader: TReader);
begin
  inherited ReadState(Reader);
  if Reader.Parent is TAdvToolBarPager then
    AdvToolBarPager := TAdvToolBarPager(Reader.Parent);
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetCaption(const Value: TCaption);
begin
  if (FCaption <> Value) then
  begin
    FCaption := Value;
    if Assigned(FAdvToolBarPager) then
    begin
      FAdvToolBarPager.InitializeTabsSize;

      FAdvToolBarPager.UpdateTabSizes;
      FAdvToolBarPager.InitializeScroller;

      FAdvToolBarPager.Invalidate;
    end;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetWideCaption(const Value: widestring);
begin
  if FWideCaption <> Value then
  begin
    FWideCaption := Value;
    if Assigned(FAdvToolBarPager) then
    begin
      FAdvToolBarPager.InitializeTabsSize;

      FAdvToolBarPager.UpdateTabSizes;
      FAdvToolBarPager.InitializeScroller;

      FAdvToolBarPager.Invalidate;
    end;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetTabEnabled(const Value: Boolean);
begin
  if (FTabEnabled <> Value) then
  begin
    FTabEnabled := Value;
    Invalidate;
    if Assigned(FAdvToolBarPager) then
      FAdvToolBarPager.Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetImageIndex(const Value: Integer);
begin
  FImageIndex := Value;
  if Assigned(FAdvToolBarPager) then
  begin
    FAdvToolBarPager.InitializeTabsSize;
    FAdvToolBarPager.Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetAutoPosition(const Value: Boolean);
begin
  if (FAutoPosition <> Value) then
  begin
    FAutoPosition := Value;
    UpdateAdvToolBarsPosition;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.GetSequencialToolBarList(ATBList: TDbgList);
var
  i, j: Integer;
  Added: Boolean;
begin
  if not Assigned(ATBList) then
    Exit;
    
  for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TAdvToolBar) and ((Controls[i].Visible) or (csDesigning in ComponentState)) then
    begin
      Added := False;
      for j:= 0 to ATBList.Count-1 do
      begin
        if (TAdvToolBar(ATBList[j]).Left > TAdvToolBar(Controls[i]).Left) then
        begin
          ATBList.Insert(j, Controls[i]);
          Added := True;
        end;
      end;

      if not Added then
        ATBList.Add(Controls[i]);
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvPage.IncreaseToolBarSize;
var
  i, l, idx, d, j: Integer;
  ATBList: TDbgList;
  BtnState, NewState: TButtonSizeState;
  found: Boolean;
begin

  if (csDesigning in ComponentState) then
    Exit;

  ATBList := TDbgList.Create;
  GetSequencialToolBarList(ATBList);

  if (ATBList.Count > 0) then
  begin
    l := Width - (TAdvToolBar(ATBList[ATBList.Count-1]).Left + TAdvToolBar(ATBList[ATBList.Count-1]).Width) - 2;
    if (l > 0) then  // InCompact ToolBar
    begin
      found := False;
      for i:= 0 to ATBList.Count-1 do
      begin
        if ((TAdvToolBar(ATBList[i]).Visible) or (csDesigning in ComponentState)) and (TAdvToolBar(ATBList[i]).Compact and TAdvToolBar(ATBList[i]).CanUnCompact) then
        begin
          if (l >= (TAdvToolBar(ATBList[i]).GetInCompactWidth - TAdvToolBar(ATBList[i]).GetCompactWidth + ADVPAGE_OFFSET)) then
          begin
            TAdvToolBar(ATBList[i]).SetCompact(False); // .Compact := False;
            IncreaseToolBarSize;
          end;
          found := True;
          Break;
        end;
      end;

      if not found then
      begin
        BtnState := bsLabel;
        NewState := bsLarge;
        d := 0;
        idx := -1;
        for i:= 0 to ATBList.Count-1 do
        begin
          if ((TAdvToolBar(ATBList[i]).Visible) or (csDesigning in ComponentState)) and not (TAdvToolBar(ATBList[i]).Compact) and (TAdvToolBar(ATBList[i]).FPropertiesLoaded) then
          begin
            j := TAdvToolBar(ATBList[i]).LargerVariantDifference(False, NewState);
            if {(j < l) and }(j > 0) and ((idx < 0) or ((j > d) and (NewState = BtnState)) or ((NewState = bsLabel) and (BtnState = bsLarge))) then
            begin
              idx := i;
              d := j;
              BtnState := NewState;
            end;
          end;
        end;

        if (idx >= 0) then
        begin
          if (d < l) then
          begin
            d := TAdvToolBar(ATBList[idx]).SetLargerVariant(False, NewState);
            l := l - d;
          end
          else
          begin
            idx := -1;
          end;
        end;

        if (l > 0) then
        begin
          if (idx >= 0) then
          begin
            IncreaseToolBarSize;
          end;
        end;
      end;
    end
    else   // Compact ToolBar
    begin

    end;
  end;

  ATBList.Free;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.DecreaseToolBarSize;
var
  i, l, idx, d, j: Integer;
  ATBList: TDbgList;
  BtnState, NewState: TButtonSizeState;
begin
  if (csDesigning in ComponentState) then
    Exit;

  ATBList := TDbgList.Create;
  GetSequencialToolBarList(ATBList);

  if (ATBList.Count > 0) then
  begin
    l := Width - (TAdvToolBar(ATBList[ATBList.Count-1]).Left + TAdvToolBar(ATBList[ATBList.Count-1]).Width) - 2;
    if (l > 0) then  // InCompact ToolBar
    begin

    end
    else   // Compact ToolBar
    begin
      BtnState := bsLabel;
      NewState := bsGlyph;
      d := 0;
      idx := -1;
      l := abs(l);
      for i:= ATBList.Count-1 downto 0 do
      begin
        if ((TAdvToolBar(ATBList[i]).Visible) or (csDesigning in ComponentState)) and not (TAdvToolBar(ATBList[i]).Compact) and (TAdvToolBar(ATBList[i]).FPropertiesLoaded) then
        begin
          j := TAdvToolBar(ATBList[i]).SmallerVariantDifference(False, NewState);
          if (j > 0) and ((idx < 0) or (((j < d){ or (d < abs(l))}) and (NewState = BtnState)) or ((NewState = bsLabel) and (BtnState = bsGlyph))) then
          begin
            idx := i;
            d := j;
            BtnState := NewState;
          end;
        end;
      end;

      if (idx >= 0) then
      begin
        d := TAdvToolBar(ATBList[idx]).SetSmallerVariant(False, NewState);
        l := l - d;
      end;

      if (l > 0) then
      begin
        if (idx >= 0) then
        begin
          DecreaseToolBarSize;
        end
        else
        begin
          for i:= ATBList.Count-1 downto 0 do
          begin
            if ((TAdvToolBar(ATBList[i]).Visible) or (csDesigning in ComponentState)) and not (TAdvToolBar(ATBList[i]).Compact) and (TAdvToolBar(ATBList[i]).FPropertiesLoaded) then
            begin
              TAdvToolBar(ATBList[i]).SetCompact(True); // .Compact := True;
              TAdvToolBar(ATBList[i]).FCompactSmallest := True;
              DecreaseToolBarSize;
              Break;
            end;
          end;
        end;
      end
      else
      begin
        if (idx >= 0) then
        begin
          //UpdateAllToolBars;
        end
      end;
    end;
  end;

  ATBList.Free;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.UpdateAllToolBars;
var
  i, l, idx, d, j: Integer;
  ATBList: TDbgList;
  BtnState, NewState: TButtonSizeState;
  found: Boolean;
begin
  // Right most ToolBar
  {rtb := -1;
  l := -1;
  for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TAdvToolBar) and ((Controls[i].Visible) or (csDesigning in ComponentState)) then
    begin
      if (TAdvToolBar(Controls[i]).Left > l) then
      begin
        l := TAdvToolBar(Controls[i]).Left;
        rtb := i;
      end;
    end;
  end;
  }
  if (csDesigning in ComponentState) then
    Exit;

  ATBList := TDbgList.Create;
  GetSequencialToolBarList(ATBList);

  if (ATBList.Count > 0) then
  begin
    l := Width - (TAdvToolBar(ATBList[ATBList.Count-1]).Left + TAdvToolBar(ATBList[ATBList.Count-1]).Width) - 2;
    if (l > 0) then  // InCompact ToolBar
    begin
      found := False;
      for i:= 0 to ATBList.Count-1 do
      begin
        if ((TAdvToolBar(ATBList[i]).Visible) or (csDesigning in ComponentState)) and (TAdvToolBar(ATBList[i]).Compact and TAdvToolBar(ATBList[i]).CanUnCompact) then
        begin
          if (l >= (TAdvToolBar(ATBList[i]).GetInCompactWidth - TAdvToolBar(ATBList[i]).GetCompactWidth + ADVPAGE_OFFSET)) then
          begin
            TAdvToolBar(ATBList[i]).SetCompact(False); // .Compact := False;
            UpdateAllToolBars;
          end;
          found := True;
          Break;
        end;
      end;

      if not found then
      begin
        BtnState := bsLabel;
        NewState := bsLarge;
        d := 0;
        idx := -1;
        for i:= ATBList.Count-1 downto 0 do
        begin
          if ((TAdvToolBar(ATBList[i]).Visible) or (csDesigning in ComponentState)) and not (TAdvToolBar(ATBList[i]).Compact) and (TAdvToolBar(ATBList[i]).FPropertiesLoaded) then
          begin
            j := TAdvToolBar(ATBList[i]).LargerVariantDifference(False, NewState);
            if (j < l) and (j > 0) and ((idx < 0) or ((j > d) and (NewState = BtnState)) or ((NewState = bsLabel) and (BtnState = bsLarge))) then
            begin
              idx := i;
              d := j;
              BtnState := NewState;
            end;
          end;
        end;

        if (idx >= 0) then
        begin
          d := TAdvToolBar(ATBList[idx]).SetLargerVariant(False, NewState);
          l := l - d;
        end;

        if (l > 0) then
        begin
          if (idx >= 0) then
          begin
            UpdateAllToolBars;
          end;
        end;
      end;
    end
    else   // Compact ToolBar
    begin
      BtnState := bsLabel;
      NewState := bsGlyph;
      d := 0;
      idx := -1;
      l := abs(l);
      for i:= ATBList.Count-1 downto 0 do
      begin
        if ((TAdvToolBar(ATBList[i]).Visible) or (csDesigning in ComponentState)) and not (TAdvToolBar(ATBList[i]).Compact) and (TAdvToolBar(ATBList[i]).FPropertiesLoaded) then
        begin
          j := TAdvToolBar(ATBList[i]).SmallerVariantDifference(False, NewState);
          if (j > 0) and ((idx < 0) or (((j < d) or (d < abs(l))) and (NewState = BtnState)) or ((NewState = bsLabel) and (BtnState = bsGlyph))) then
          begin
            idx := i;
            d := j;
            BtnState := NewState;
          end;
        end;
      end;

      if (idx >= 0) then
      begin
        d := TAdvToolBar(ATBList[idx]).SetSmallerVariant(False, NewState);
        l := l - d;
      end;

      if (l > 0) then
      begin
        if (idx >= 0) then
        begin
          UpdateAllToolBars;
        end
        else
        begin
          for i:= ATBList.Count-1 downto 0 do
          begin
            if ((TAdvToolBar(ATBList[i]).Visible) or (csDesigning in ComponentState)) and not (TAdvToolBar(ATBList[i]).Compact) and (TAdvToolBar(ATBList[i]).FPropertiesLoaded) then
            begin
              TAdvToolBar(ATBList[i]).SetCompact(True); // .Compact := True;
              UpdateAllToolBars;
              Break;
            end;
          end;
        end;
      end
      else
      begin
        if (idx >= 0) then
        begin
          UpdateAllToolBars;
        end
      end;
    end;
  end;

  ATBList.Free;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.UpdateAdvToolBarsPosition;
var
  i, x, OffSet: Integer;
begin
  if {not (csDesigning in ComponentState) or }not FAutoPosition or FUpdatingATBPosition or (csLoading in ComponentState) then
    Exit;

  OffSet := 3;
  FUpdatingATBPosition := True;
  x := OffSet;
  {for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TAdvToolBar) and ((Controls[i].Visible) or (csDesigning in ComponentState)) then
    begin
      TAdvToolBar(Controls[i]).Left := X;
      TAdvToolBar(Controls[i]).Top := OffSet;
      TAdvToolBar(Controls[i]).Height := Self.Height - OffSet*2;

      X := X + TAdvToolBar(Controls[i]).Width + OffSet;
    end;
  end;}
  for i:= 0 to FAdvToolBars.Count -1 do
  begin
    if ((AdvToolBars[i].Visible) or (csDesigning in ComponentState)) then
    begin
      AdvToolBars[i].Left := X;
      AdvToolBars[i].Top := OffSet;
      AdvToolBars[i].Height := Self.Height - OffSet*2;
      
      if (Self.Parent is TMinimizedRibbonWindow) and Assigned(AdvToolBars[i].FCompactBtn) then
      begin
        AdvToolBars[i].FCompactBtn.Height := AdvToolBars[i].Height;
        if Assigned(AdvToolBars[i].FSelfClone) then
          AdvToolBars[i].FSelfClone.Height := AdvToolBars[i].Height;
      end;

      X := X + AdvToolBars[i].Width + OffSet;
    end;
  end;
  FUpdatingATBPosition := False;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetOfficeHint(const Value: TAdvHintInfo);
begin
  FOfficeHint.Assign(Value);
end;

//------------------------------------------------------------------------------

function TAdvPage.GetPageIndex: Integer;
begin
  if Assigned(FAdvToolBarPager) then
    Result := FAdvToolBarPager.IndexOfPage(Self)
  else
    Result := -1;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetPageIndex(const Value: Integer);
begin
  if Assigned(FAdvToolBarPager) and (Value >= 0) and (Value < FAdvToolBarPager.AdvPageCount) then
  begin
    FAdvToolBarPager.MoveAdvPage(FAdvToolBarPager.IndexOfPage(Self), Value);
    FAdvToolBarPager.Invalidate;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.HideShortCutHint;
begin
  if Assigned(FShortCutHint) and Assigned(FAdvToolBarPager) then
  begin
    FShortCutHint.Visible := false;
    FAdvToolBarPager.DestroyShortCutHintWin(FShortCutHint);
    //FShortCutHint.Free;
    FShortCutHint := nil;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.ShowShortCutHint;
var
  pt: TPoint;
  TabR: TRect;
begin
  if not Assigned(FAdvToolBarPager) or not TabEnabled or not TabVisible then
    Exit;

  if not Assigned(FShortCutHint) then
  begin
    FShortCutHint := FAdvToolBarPager.CreateShortCutHintWin; //TShortCutHintWindow.Create(Self);
    //FShortCutHint.Parent := Self;
  end;

  FShortCutHint.Visible := false;
  FShortCutHint.Caption := FShortCutHintText;

  FShortCutHint.Color := clWhite;
  FShortCutHint.ColorTo := FAdvToolBarPager.FCurrentToolBarStyler.GlowButtonAppearance.Color;


  TabR := FAdvToolBarPager.GetTabRect(Self);
  pt := FAdvToolBarPager.ClientToScreen(Point(TabR.Left, TabR.Top));
  //pt := ClientToScreen(Point(0,0));

  case ShortCutHintPos of
  shpLeft:
    begin
      FShortCutHint.Left := pt.X - (FShortCutHint.Width div 2);
      FShortCutHint.Top := pt.Y + ((TabR.bottom - TabR.Top){self.Height} - FShortCutHint.Height) div 2;
    end;
  shpTop:
    begin
      FShortCutHint.Left := pt.X + ((TabR.Right - TabR.Left){self.Width} - FShortCutHint.Width) div 2;
      FShortCutHint.Top := pt.Y - (FShortCutHint.Height div 2);
    end;
  shpRight:
    begin
      FShortCutHint.Left := pt.X + (TabR.Right - TabR.Left){self.Width} - (FShortCutHint.Width div 2);
      FShortCutHint.Top := pt.Y + ((TabR.bottom - TabR.Top){self.Height} - FShortCutHint.Height) div 2;
    end;
  shpBottom:
    begin
      FShortCutHint.Left := pt.X + ((TabR.Right - TabR.Left){self.Width} - FShortCutHint.Width) div 2;
      FShortCutHint.Top := pt.Y + (TabR.bottom - TabR.Top){self.Height} - (FShortCutHint.Height div 2);
    end;
  end;

  FShortCutHint.Visible := true;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.HideShortCutHintOfAllToolBars;
var
  i: Integer;
begin
  if (GetCapture = Handle) and CANCAPTURE then
    ReleaseCapture;

  for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TAdvToolBar) and (Controls[i].Visible) then
    begin
      TAdvToolBar(Controls[i]).HideShortCutHintOfButtons;
    end;
  end;
  FToolBarShortCutShowing := False;
  FShortCutChars := '';
end;

//------------------------------------------------------------------------------

procedure TAdvPage.ShowShortCutHintOfAllToolBars;
var
  i: Integer;
begin
  if not FToolBarShortCutShowing and CANCAPTURE then
  begin
    SetCapture(Handle);
  end;

  for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TAdvToolBar) and (Controls[i].Visible) and (Controls[i].Enabled) then
    begin
      TAdvToolBar(Controls[i]).ShowShortCutHintOfButtons;
    end;
  end;
  FToolBarShortCutShowing := True;
  FShortCutChars := '';
end;

//------------------------------------------------------------------------------

function TAdvPage.GetFirstToolBar(Visible: Boolean): TAdvToolBar;
var
  i: Integer;
begin
  Result := nil;
  {for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TAdvToolBar) and ((Controls[i].Visible and Visible) or not Visible) then
    begin
      Result := TAdvToolBar(Controls[i]);
      Break;
    end;
  end;}

  for i:= 0 to FAdvToolBars.Count -1 do
  begin
    if ((AdvToolBars[i].Visible and Visible) or not Visible) then
    begin
      Result := AdvToolBars[i];
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvPage.HasShortCut(aShortCut: String): Boolean;
var
  i, j: Integer;
begin
  Result := False;
  j := 0;
  for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TAdvToolBar) and Controls[i].Visible then
    begin
      Result := TAdvToolBar(Controls[i]).HasShortCut(aShortCut, j);
      if Result then
        Break;
    end;
  end;

  if not Result and (j = 0) then
  begin
    FToolBarShortCutShowing := False;
    Beep;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.ChangeLeftATBIndexTo(Value: Integer);
var
  ATBList: TDbgList;
  i, j, OffSet, vc, k: Integer;
  done: Boolean;
begin
  if (Value < 0) or (Value >= VisibleToolBarCount) or FUpdatingATBPosition then
    Exit;
    
  ATBList := TDbgList.Create;
  GetSequencialToolBarList(ATBList);
  OffSet := 3;
  j := 5;
  FUpdatingATBPosition := True;

  if (Value > FLeftATBIndex) then
  begin
    vc := ScrollPageATBVisibleCount(Value, True);
    for k := 0 to ATBList.Count -1 do
    begin
      i := ScrollPageATBVisibleCount(Value-1, True);
      if (i > vc) then
      begin
        Value := Value - 1;
        vc := i;
      end
      else
      begin
        Break;
      end;
    end;

    if (Value > FLeftATBIndex) then
    begin
      done := False;
      while not done do
      begin
        if ((Self.Width - OffSet) >= TAdvToolBar(ATBList.Items[ATBList.Count-1]).Left + TAdvToolBar(ATBList.Items[ATBList.Count-1]).Width + OffSet - j) then
        begin
          j := (TAdvToolBar(ATBList.Items[ATBList.Count-1]).Left + TAdvToolBar(ATBList.Items[ATBList.Count-1]).Width) - (Self.Width - OffSet);
          done := True;
        end;

        if (OffSet >= TAdvToolBar(ATBList.Items[Value]).Left - j) then
        begin
          j := (TAdvToolBar(ATBList.Items[Value]).Left - j) - OffSet;
          done := True;
        end;

        for i := 0 to ATBList.Count -1 do
        begin
          TAdvToolBar(ATBList.Items[i]).Left := TAdvToolBar(ATBList.Items[i]).Left - j;
        end;
      end;

      FLeftATBIndex := Value;
      UpdateScroller;
    end;
  end
  else if (Value < FLeftATBIndex) then
  begin
    Value := Max(0, Value);
    if (Value < FLeftATBIndex) then
    begin
      done := False;
      while not done do
      begin
        if (OffSet <= TAdvToolBar(ATBList.Items[0]).Left + OffSet + j) then
        begin
          j := OffSet - TAdvToolBar(ATBList.Items[0]).Left;
          done := True;
        end;

        if (OffSet <= TAdvToolBar(ATBList.Items[Value]).Left + OffSet + j) then
        begin
          j := OffSet - TAdvToolBar(ATBList.Items[Value]).Left;
          done := True;
        end;

        for i := 0 to ATBList.Count -1 do
        begin
          TAdvToolBar(ATBList.Items[i]).Left := TAdvToolBar(ATBList.Items[i]).Left + j;
        end;
      end;

      FLeftATBIndex := Value;
      UpdateScroller;
    end;
  end;

  FUpdatingATBPosition := False;
  ATBList.Free;
end;

//------------------------------------------------------------------------------

function TAdvPage.ScrollToolBars(Value: Integer): Integer;
var
  i, k: Integer;
begin
  Result := 0;
  if (Value > 0) then
  begin
    Result := Min(Value, FToolBarScroller.Max - FToolBarScroller.Position);
    if FToolBarScroller.CanGoForward and (Result > 0) then
    begin
      FToolBarScroller.Position := FToolBarScroller.Position + Result;
      k := FLeftATBIndex;
      for i := 1 to Result do
      begin
        k := k + ScrollPageATBVisibleCount(FLeftATBIndex, True);
        if (k >= VisibleToolBarCount) then
          Break;
      end;

      ChangeLeftATBIndexTo(k);
      InvalidateScrollBtns;
    end;
  end
  else if (Value < 0) then
  begin
    Result := -Min(abs(Value), FToolBarScroller.Position - FToolBarScroller.Min);
    if FToolBarScroller.CanGoBack and (Result < 0) and (FLeftATBIndex > 0) then
    begin
      FToolBarScroller.Position := FToolBarScroller.Position + Result;
      k := FLeftATBIndex;
      for i := 1 to abs(Result) do
      begin
        k := k - ScrollPageATBVisibleCount(FLeftATBIndex-1, False);
        if (k <= 0) then
          Break;
      end;

      ChangeLeftATBIndexTo(k);
      InvalidateScrollBtns;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.InitializeScroller;
begin
  FLeftATBIndex := 0;
  FToolBarScroller.Min := 0;
  FToolBarScroller.Max := 0;
  FToolBarScroller.Position := 0;
  UpdateScroller;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.InvalidateScrollBtns;
begin
  if Assigned(FLeftScrollBtn) and FLeftScrollBtn.Visible then
    FLeftScrollBtn.Invalidate;

  if Assigned(FRightScrollBtn) and FRightScrollBtn.Visible then
    FRightScrollBtn.Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.ScrollInView(ATBIndex: Integer);
var
  VisIndex: Integer;
begin
  if not FToolBarScroller.Visible or FScrolling or (ATBIndex < 0) or (ATBIndex >= FAdvToolBars.Count) then
    Exit;


  VisIndex := RealIndexToVisIndex(ATBIndex);
  if (VisIndex < FLeftATBIndex) then
  begin
    ScrollToolBars(-1);
  end
  else //if (VisIndex > FLeftATBIndex + FSubMenuVisibleItemCount) then
  begin
    ScrollToolBars(1);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.OnScrollLeftClick(Sender: TObject);
begin
  ScrollToolBars(-1);
end;

//------------------------------------------------------------------------------

procedure TAdvPage.OnScrollRightClick(Sender: TObject);
begin
  ScrollToolBars(1);
end;

//------------------------------------------------------------------------------

function TAdvPage.ALLATBSmallestVariant: Boolean;
var
  i: Integer;
begin
  Result := True;
  for i:= 0 to FAdvToolBars.Count-1 do
  begin
    if AdvToolBars[i].Visible and not AdvToolBars[i].IsSmallestVariant then
    begin
      Result := False;
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvPage.ScrollPageATBVisibleCount(AIndex: Integer; GoForward: Boolean): Integer;
var
  ATBList: TDbgList;
  i, x, OffSet: Integer;
begin
  Result := 0;
  ATBList := TDbgList.Create;
  GetSequencialToolBarList(ATBList);
  OffSet := 3;
  x := OffSet;
  if GoForward then
  begin
    if (AIndex >= 0) and (AIndex < ATBList.Count) then
    begin
      for i := AIndex to ATBList.Count -1 do
      begin
        if (TAdvToolBar(ATBList.Items[i]).Visible) then
        begin
          X := X + TAdvToolBar(ATBList.Items[i]).Width + OffSet;
          if (X - OffSet < Self.Width) then
          begin
            Result := Result + 1;
          end
          else
          begin
            Break;
          end;
        end;
      end;
    end;
  end
  else
  begin
    if (AIndex >= 0) and (AIndex < ATBList.Count) then
    begin
      for i := AIndex downto 0 do
      begin
        if (TAdvToolBar(ATBList.Items[i]).Visible) then
        begin
          X := X + TAdvToolBar(ATBList.Items[i]).Width + OffSet;
          if (X - OffSet < Self.Width) then
          begin
            Result := Result + 1;
          end
          else
          begin
            Break;
          end;
        end;
      end;
    end;
  end;
  ATBList.Free;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.UpdateScroller;
var
  i, j, vc, tc, k, t: Integer;
begin
  if (csDesigning in ComponentState) then
    Exit;

  //FPageATBVisibleCount := (GetRightFrameRect.Bottom - GetRightFrameRect.Top - FSubMenuCaptionHeight) div FSubMenuItemHeight; // available SubMenuItem space
  vc := Max(1, ScrollPageATBVisibleCount(0, True));
  tc := VisibleToolBarCount;

  if (tc > vc) and ALLATBSmallestVariant then
  begin
    //FToolBarScroller.Max := tc div vc;
    j := 0;
    k := 0;
    vc := 0;
    t := 0;
    for i:= 0 to FAdvToolBars.Count-1 do
    begin
      vc := Max(1, ScrollPageATBVisibleCount(vc + k, True));
      t := t + vc;
      if (t >= tc) then
        Break;
      Inc(vc);
      j := j + 1;
    end;
    FToolBarScroller.Max := j;
  end
  else
  begin
    FToolBarScroller.Max := 0;
  end;
  FToolBarScroller.Position := Min(FToolBarScroller.Position, FToolBarScroller.Max);

  if FToolBarScroller.CanGoBack then
  begin
    if (FLeftScrollBtn = nil) then
    begin
      FLeftScrollBtn := TAdvPageScrollButton.Create(Self);
      FLeftScrollBtn.Parent := Self;
      FLeftScrollBtn.Align := alLeft;
      FLeftScrollBtn.Width := SCROLLBTN_WIDTH;
      FLeftScrollBtn.Position := bpLeft;
      FLeftScrollBtn.ScrollArrow := saLeft;
      FLeftScrollBtn.OnClick := OnScrollLeftClick;
    end;
    FLeftScrollBtn.Visible := True;

    if Assigned(FAdvToolBarPager) and Assigned(FAdvToolBarPager.FCurrentToolBarStyler) then
      FLeftScrollBtn.Appearance.Assign(FAdvToolBarPager.FCurrentToolBarStyler.CompactGlowButtonAppearance);
  end
  else
  begin
    if Assigned(FLeftScrollBtn) then
      FLeftScrollBtn.Visible := False;
  end;

  if FToolBarScroller.CanGoForward then
  begin
    if (FRightScrollBtn = nil) then
    begin
      FRightScrollBtn := TAdvPageScrollButton.Create(Self);
      FRightScrollBtn.Parent := Self;
      FRightScrollBtn.Align := alRight;
      FRightScrollBtn.Width := SCROLLBTN_WIDTH;
      FRightScrollBtn.Position := bpRight;
      FRightScrollBtn.ScrollArrow := saRight;
      FRightScrollBtn.OnClick := OnScrollRightClick;
    end;
    FRightScrollBtn.Visible := True;

    if Assigned(FAdvToolBarPager) and Assigned(FAdvToolBarPager.FCurrentToolBarStyler) then
      FRightScrollBtn.Appearance.Assign(FAdvToolBarPager.FCurrentToolBarStyler.CompactGlowButtonAppearance);
  end
  else
  begin
    if Assigned(FRightScrollBtn) then
      FRightScrollBtn.Visible := False;
  end;
end;

//------------------------------------------------------------------------------

function TAdvPage.VisibleToolBarCount: Integer;
var
  i: Integer;
begin
  Result := 0;
  for i:= 0 to FAdvToolBars.Count -1 do
  begin
    if (AdvToolBars[i].Visible) then
    begin
      Inc(Result);
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvPage.RealIndexToVisIndex(ATBIndex: Integer): Integer;
var
  i: Integer;
begin
  Result := -1;
  if (ATBIndex < 0) or (ATBIndex >=  FAdvToolBars.Count) or not AdvToolBars[ATBIndex].Visible then
    Exit;

  Result := 0;
  for i := 0 to ATBIndex-1 do
  begin
    if AdvToolBars[i].Visible then
      Result := Result + 1;
  end;
end;

//------------------------------------------------------------------------------

function TAdvPage.VisIndexToRealIndex(ATBIndex: Integer): Integer;
var
  i, j: Integer;
begin
  Result := -1;
  if (ATBIndex < 0) or (ATBIndex >= FAdvToolBars.Count) then
    Exit;

  j := -1;
  for i := 0 to FAdvToolBars.Count-1 do
  begin
    if AdvToolBars[i].Visible then
    begin
      Inc(j);
    end;

    if (j = ATBIndex) then
    begin
      Result := i;
      Break;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.SetTabLeft(const Value: Integer);
begin
  FTabLeft := Value;
end;

//------------------------------------------------------------------------------

function TAdvPage.GetTabWidth: Integer;
begin
  Result := FTabClientWidth;
  if Assigned(FAdvToolBarPager) then
  begin
    if IsGroupTab then
      Result := Result + FAdvToolBarPager.FCurrentGroupTabLeftMargin + FAdvToolBarPager.FCurrentGroupTabRightMargin
    else
      Result := Result + FAdvToolBarPager.FCurrentTabLeftMargin + FAdvToolBarPager.FCurrentTabRightMargin;
  end;
end;

//------------------------------------------------------------------------------

function TAdvPage.IsGroupTab: Boolean;
begin
  Result := False;
  if Assigned(FAdvToolBarPager) then
  begin
    Result := (FAdvToolBarPager.GroupOfTab(FAdvToolBarPager.IndexOfPage(Self)) >= 0);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.InvalidateAllAdvToolBars;
var
  i: Integer;
begin
  if not Self.Visible then
    Exit;
    
  for i:= 0 to FAdvToolBars.Count -1 do
  begin
    AdvToolBars[i].Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;
  if FToolBarShortCutShowing then
  begin
    HideShortCutHintOfAllToolBars;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.PopulateClone;
var
  i: Integer;
begin
  if not Assigned(FSelfClone) then
    Exit;

  {$IFDEF DELPHI6_LVL}
  FSelfClone.FAdvToolBars.Assign(FAdvToolBars);
  {$ENDIF}
  {$IFNDEF DELPHI6_LVL}
  FSelfClone.FAdvToolBars.AssignList(FAdvToolBars);
  {$ENDIF}

  FCloning := True;
  for i := 0 to FAdvToolBars.Count - 1 do
  begin
    AdvToolBars[i].Parent := FSelfClone;
  end;
  FCloning := False;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.UnPopulateClone;
var
  i: Integer;
begin
  if not Assigned(FSelfClone) then
    Exit;

  FCloning := True;
  FSelfClone.FCloning := True;
  for i := 0 to FSelfClone.FAdvToolBars.Count - 1 do
  begin
    AdvToolBars[i].Parent := Self;
  end;
  FSelfClone.FCloning := False;
  FCloning := False;
end;

//------------------------------------------------------------------------------

function TAdvPage.CreateClone(ParntWin: TWinControl): TAdvPage;
var
  i: Integer;
begin
  Result := nil;
  if not Assigned(ParntWin) or not Assigned(AdvToolBarPager) then
    Exit;

  DestroyClone;
  FOldAutoPosition := Self.AutoPosition;
  Self.AutoPosition := False;

  FSelfClone := TAdvPage.Create(ParntWin);
  FSelfClone.Parent := ParntWin;
  FSelfClone.FSelfClone := Self;
  FSelfClone.FAdvToolBarPager := FAdvToolBarPager;
  Result := FSelfClone;

  FSelfClone.AutoPosition := False;
  FSelfClone.Caption := Self.Caption;
  FSelfClone.WideCaption := Self.WideCaption;
  //FSelfClone.ImageIndex;
  //FSelfClone.TabHint;
  //FSelfClone.TabVisible;
  //FSelfClone.TabEnabled;
  FSelfClone.ShowHint := Self.ShowHint;
  FSelfClone.OfficeHint.Assign(Self.OfficeHint);
  //FSelfClone.PageIndex;
  //property ShortCutHint;
  FSelfClone.ShortCutHintPos := Self.ShortCutHintPos;

  FSelfClone.OnMouseDown := Self.OnMouseDown;
  FSelfClone.OnMouseMove := Self.OnMouseMove;
  FSelfClone.OnMouseUp := Self.OnMouseUp;

  i := Self.AdvToolBarPager.FExpandedHeight;
  if (Self.AdvToolBarPager.FCaption.Visible) then
    i := i - Self.AdvToolBarPager.FCaption.Height;

  i := i - Self.AdvToolBarPager.TabSettings.Height - ADVPAGE_OFFSET-1;

  FSelfClone.Height := i;
  FSelfClone.Width := Self.Width;

  FSelfClone.FCloning := True;
  PopulateClone;
  FSelfClone.FCloning := False;
  FSelfClone.AutoPosition := True;
  FSelfClone.UpdateAdvToolBarsPosition;
end;

//------------------------------------------------------------------------------

procedure TAdvPage.DestroyClone;
begin
  UnPopulateClone;
  if Assigned(FSelfClone) then
  begin
    FSelfClone.Free; 
    FSelfClone := nil;
    Self.AutoPosition := FOldAutoPosition;

    Width := Width - 1;
    Width := Width + 1;
  end;
end;

//------------------------------------------------------------------------------

{ TAdvPageCaption }

constructor TAdvPageCaption.Create;
begin
  inherited;
  FVisible := True;
  FHeight := DEFAULT_PAGERCAPTIONHEIGHT;
  FCaption := '';
  FIndent := 100;
  FRightIndent := 0; 
  FMinWidth := 100; 
end;

//------------------------------------------------------------------------------

procedure TAdvPageCaption.Assign(Source: TPersistent);
begin
  if (Source is TAdvPageCaption) then
  begin
    FCaption := (Source as TAdvPageCaption).Caption;
    FHeight := (Source as TAdvPageCaption).Height;
    Visible := (Source as TAdvPageCaption).Visible;
    Indent := (Source as TAdvPageCaption).Indent;
    MinWidth := (Source as TAdvPageCaption).MinWidth;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TAdvPageCaption.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(self);
end;

//------------------------------------------------------------------------------

procedure TAdvPageCaption.SetCaption(const Value: TCaption);
begin
  if (FCaption <> Value) then
  begin
    FCaption := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPageCaption.SetHeight(const Value: Integer);
begin
  if (FHeight <> Value) then
  begin
    FHeight := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPageCaption.SetVisible(const Value: Boolean);
begin
  if (FVisible <> Value) then
  begin
    FVisible := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPageCaption.SetWideCaption(const Value: widestring);
begin
  if (FWideCaption <> Value) then
  begin
    FWideCaption := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPageCaption.SetIndent(const Value: Integer);
begin
  if (FIndent <> Value) then
  begin
    FIndent := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvPageCaption.SetMinWidth(const Value: Integer);
begin
  if (FMinWidth <> Value) then
  begin
    FMinWidth := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

{ TCustomTabAppearance }

constructor TCustomTabAppearance.Create;
begin
  inherited;
  FBorderColor := clBtnFace;
  FBorderColorHot := clBlue;
  FBorderColorSelectedHot := clNone;
  FBorderColorDown := clNone;
  FColor := clBtnFace;
  FColorTo := clWhite;
  FColorHot := clYellow;
  FColorHotTo := clNone;
  FColorSelectedTo := clBtnFace;
  FBorderColorDisabled := clNone;
  FBorderColorSelected := clBtnFace;
  FColorDisabled := clNone;
  FColorDisabledTo := clNone;
  FColorSelected := clWhite;
  FColorMirror := clWhite;
  FColorMirrorTo := clWhite;
  FColorMirrorHot := clNone;
  FColorMirrorHotTo := clNone;
  FGradientMirror := ggVertical;
  FGradientMirrorHot := ggVertical;
  FGradient := ggVertical;
  FGradientHot := ggVertical;
  FColorMirrorDisabledTo := clNone;
  FColorMirrorDisabled := clNone;
  FColorMirrorSelectedTo := clWhite;
  FColorMirrorSelected := clWhite;
  FGradientSelected := ggVertical;
  FGradientDisabled := ggVertical;
  FGradientMirrorSelected := ggVertical;
  FGradientMirrorDisabled := ggVertical;
  FTextColorDisabled := clWhite;
  FTextColorSelected := clBlue;
  FTextColor := clBlue;
  FTextColorHot := clBlue;
  FShadowColor := RGB(174, 199, 232);
  FHighLightColor := RGB(191, 250, 255);
  FHighLightColorSelected := RGB(248, 204, 99);
  FHighLightColorSelectedHot := RGB(255, 255, 189);
  FHighLightColorDown := RGB(208, 251, 255);
  FHighLightColorHot := RGB(237, 244, 253);
  FBackGround := TGradientBackground.Create;
  FBackGround.OnChange := OnBackGroundChanged;
  FFont := TFont.Create;
  if IsVista then
    FFont.Name := 'Segoe UI'
  else
    FFont.Name := 'Tahoma';

  FFont.Size := 8;
  FFont.Style := [];
  FSystemFont := true;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.Assign(Source: TPersistent);
begin
  if (Source is TCustomTabAppearance) then
  begin
    FBorderColor := (Source as TCustomTabAppearance).BorderColor;
    FBorderColorHot := (Source as TCustomTabAppearance).BorderColorHot;
    FBorderColorSelectedHot := (Source as TCustomTabAppearance).BorderColorSelectedHot;
    FBorderColorDown := (Source as TCustomTabAppearance).BorderColorDown;
    FColor := (Source as TCustomTabAppearance).Color;
    FColorTo := (Source as TCustomTabAppearance).ColorTo;
    FColorHot := (Source as TCustomTabAppearance).ColorHot;
    FColorHotTo := (Source as TCustomTabAppearance).ColorHotTo;
    FColorSelectedTo := (Source as TCustomTabAppearance).ColorSelectedTo;
    FBorderColorDisabled := (Source as TCustomTabAppearance).BorderColorDisabled;
    FBorderColorSelected := (Source as TCustomTabAppearance).BorderColorSelected;
    FColorDisabled := (Source as TCustomTabAppearance).ColorDisabled;
    FColorDisabledTo := (Source as TCustomTabAppearance).ColorDisabledTo;
    FColorSelected := (Source as TCustomTabAppearance).ColorSelected;
    FColorMirror := (Source as TCustomTabAppearance).ColorMirror;
    FColorMirrorTo := (Source as TCustomTabAppearance).ColorMirrorTo;
    FColorMirrorHot := (Source as TCustomTabAppearance).ColorMirrorHot;
    FColorMirrorHotTo := (Source as TCustomTabAppearance).ColorMirrorHotTo;
    FGradientMirror := (Source as TCustomTabAppearance).GradientMirror;
    FGradientMirrorHot := (Source as TCustomTabAppearance).GradientMirrorHot;
    FGradient := (Source as TCustomTabAppearance).Gradient;
    FGradientHot := (Source as TCustomTabAppearance).GradientHot;
    FColorMirrorDisabledTo := (Source as TCustomTabAppearance).ColorMirrorDisabledTo;
    FColorMirrorDisabled := (Source as TCustomTabAppearance).ColorMirrorDisabled;
    FColorMirrorSelectedTo := (Source as TCustomTabAppearance).ColorMirrorSelectedTo;
    FColorMirrorSelected := (Source as TCustomTabAppearance).ColorMirrorSelected;
    FGradientSelected := (Source as TCustomTabAppearance).GradientSelected;
    FGradientDisabled := (Source as TCustomTabAppearance).GradientDisabled;
    FGradientMirrorSelected := (Source as TCustomTabAppearance).GradientMirrorSelected;
    FGradientMirrorDisabled := (Source as TCustomTabAppearance).GradientMirrorDisabled;
    FTextColorDisabled := (Source as TCustomTabAppearance).TextColorDisabled;
    FTextColorSelected := (Source as TCustomTabAppearance).TextColorSelected;
    FShadowColor := (Source as TCustomTabAppearance).ShadowColor;
    FHighLightColor := (Source as TCustomTabAppearance).HighLightColor;
    FHighLightColorHot := (Source as TCustomTabAppearance).HighLightColorHot;
    FHighLightColorDown := (Source as TCustomTabAppearance).HighLightColorDown;
    FHighLightColorSelected := (Source as TCustomTabAppearance).HighLightColorSelected;
    FHighLightColorSelectedHot := (Source as TCustomTabAppearance).HighLightColorSelectedHot;
    Font.Assign((Source as TCustomTabAppearance).Font);
    TextColor := (Source as TCustomTabAppearance).TextColor;
    TextColorHot := (Source as TCustomTabAppearance).TextColorHot;
    BackGround.Assign((Source as TCustomTabAppearance).BackGround);
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

destructor TCustomTabAppearance.Destroy;
begin
  FBackGround.Free;
  FFont.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetBackGround(const Value: TGradientBackground);
begin
  FBackGround.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetBorderColor(const Value: TColor);
begin
  if (FBorderColor <> Value) then
  begin
    FBorderColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetBorderColorDisabled(const Value: TColor);
begin
  if (FBorderColorDisabled <> Value) then
  begin
    FBorderColorDisabled := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetBorderColorSelected(const Value: TColor);
begin
  if (FBorderColorSelected <> Value) then
  begin
    FBorderColorSelected := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetBorderColorSelectedHot(
  const Value: TColor);
begin
  if (FBorderColorSelectedHot <> Value) then
  begin
    FBorderColorSelectedHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColor(const Value: TColor);
begin
  if (FColor <> Value) then
  begin
    FColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorDisabled(const Value: TColor);
begin
  if (FColorDisabled <> Value) then
  begin
    FColorDisabled := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorDisabledTo(const Value: TColor);
begin
  if (FColorDisabledTo <> Value) then
  begin
    FColorDisabledTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorHot(const Value: TColor);
begin
  if (FColorHot <> Value) then
  begin
    FColorHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorHotTo(const Value: TColor);
begin
  if (FColorHotTo <> Value) then
  begin
    FColorHotTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorMirror(const Value: TColor);
begin
  if (FColorMirror <> Value) then
  begin
    FColorMirror := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorMirrorDisabled(const Value: TColor);
begin
  if (FColorMirrorDisabled <> Value) then
  begin
    FColorMirrorDisabled := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorMirrorDisabledTo(
  const Value: TColor);
begin
  if (FColorMirrorDisabledTo <> Value) then
  begin
    FColorMirrorDisabledTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorMirrorHot(const Value: TColor);
begin
  if (FColorMirrorHot <> Value) then
  begin
    FColorMirrorHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorMirrorHotTo(const Value: TColor);
begin
  if (FColorMirrorHotTo <> Value) then
  begin
    FColorMirrorHotTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorMirrorSelected(const Value: TColor);
begin
  if (FColorMirrorSelected <> Value) then
  begin
    FColorMirrorSelected := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorMirrorSelectedTo(
  const Value: TColor);
begin
  if (FColorMirrorSelectedTo <> Value) then
  begin
    FColorMirrorSelectedTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorMirrorTo(const Value: TColor);
begin
  if (FColorMirrorTo <> Value) then
  begin
    FColorMirrorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorSelected(const Value: TColor);
begin
  if (FColorSelected <> Value) then
  begin
    FColorSelected := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorSelectedTo(const Value: TColor);
begin
  if (FColorSelectedTo <> Value) then
  begin
    FColorSelectedTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetColorTo(const Value: TColor);
begin
  if (FColorTo <> Value) then
  begin
    FColorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetGradient(const Value: TGDIPGradient);
begin
  if (FGradient <> Value) then
  begin
    FGradient := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetGradientDisabled(
  const Value: TGDIPGradient);
begin
  if (FGradientDisabled <> Value) then
  begin
    FGradientDisabled := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetGradientHot(const Value: TGDIPGradient);
begin
  if (FGradientHot <> Value) then
  begin
    FGradientHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetGradientMirror(
  const Value: TGDIPGradient);
begin
  if (FGradientMirror <> Value) then
  begin
    FGradientMirror := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetGradientMirrorDisabled(
  const Value: TGDIPGradient);
begin
  if (FGradientMirrorDisabled <> Value) then
  begin
    FGradientMirrorDisabled := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetGradientMirrorHot(
  const Value: TGDIPGradient);
begin
  if (FGradientMirrorHot <> Value) then
  begin
    FGradientMirrorHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetGradientMirrorSelected(
  const Value: TGDIPGradient);
begin
  if (FGradientMirrorSelected <> Value) then
  begin
    FGradientMirrorSelected := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetGradientSelected(
  const Value: TGDIPGradient);
begin
  if (FGradientSelected <> Value) then
  begin
    FGradientSelected := Value;
    Changed;
  end;
end;

procedure TCustomTabAppearance.SetSystemFont(const Value: boolean);
begin
  if (FSystemFont <> value) then
  begin
    FSystemFont := value;

    if value then
    begin
      if IsVista then
        FFont.Name := 'Segoe UI'
      else
        FFont.Name := 'Tahoma';
    end;
    
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetTextColor(const Value: TColor);
begin
  if (FTextColor <> Value) then
  begin
    FTextColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetTextColorDisabled(const Value: TColor);
begin
  if (FTextColorDisabled <> Value) then
  begin
    FTextColorDisabled := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetTextColorHot(const Value: TColor);
begin
  if (FTextColorHot <> Value) then
  begin
    FTextColorHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetTextColorSelected(const Value: TColor);
begin
  if (FTextColorSelected <> Value) then
  begin
    FTextColorSelected := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.OnBackGroundChanged(Sender: TObject);
begin
  Changed;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetBorderColorDown(const Value: TColor);
begin
  if (FBorderColorDown <> Value) then
  begin
    FBorderColorDown := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCustomTabAppearance.SetFont(const Value: TFont);
begin
  FFont.Assign(Value);
end;

//------------------------------------------------------------------------------

{ TATBTabSettings }

constructor TATBTabSettings.Create;
begin
  inherited;
  FLeftMargin := 4;
  FRightMargin := 4;
  FHeight := DEFAULT_TABHEIGHT;
  FStartMargin := 60;
  FEndMargin := 0;
  FSpacing := 4;
  FMinSpacing := MIN_SPACING;
  FMinMargin := MIN_SPACING;
end;

//------------------------------------------------------------------------------

procedure TATBTabSettings.Assign(Source: TPersistent);
begin
  if (Source is TATBTabSettings) then
  begin
    LeftMargin := (Source as TATBTabSettings).LeftMargin;
    RightMargin := (Source as TATBTabSettings).RightMargin;
    Height := (Source as TATBTabSettings).Height;
    StartMargin := (Source as TATBTabSettings).StartMargin;
    EndMargin := (Source as TATBTabSettings).EndMargin;
  end  
  else
    inherited;
end;

//------------------------------------------------------------------------------

procedure TATBTabSettings.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

procedure TATBTabSettings.SetLeftMargin(const Value: Integer);
begin
  if (FLeftMargin <> Value) then
  begin
    FLeftMargin := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBTabSettings.SetRightMargin(const Value: Integer);
begin
  if (FRightMargin <> Value) then
  begin
    FRightMargin := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBTabSettings.SetHeight(const Value: Integer);
begin
  if (FHeight <> Value) then
  begin
    FHeight := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBTabSettings.SetStartMargin(const Value: Integer);
begin
  if (FStartMargin <> Value) then
  begin
    FStartMargin := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBTabSettings.SetEndMargin(const Value: Integer);
begin
  if (FEndMargin <> Value) then
  begin
    FEndMargin := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TATBTabSettings.SetSpacing(const Value: Integer);
begin
  if (FSpacing <> Value) then
  begin
    FSpacing := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

{ TATBTabScroller }

constructor TATBTabScroller.Create;
begin
  inherited;
  FMin := 0;
  FMax := 0;
  FPosition := 0;
  FVisible := False;
end;

//------------------------------------------------------------------------------

function TATBTabScroller.CanGoBack: Boolean;
begin
  Result := Position > Min;
end;

//------------------------------------------------------------------------------

function TATBTabScroller.CanGoForward: Boolean;
begin
  Result := Position < Max;
end;

//------------------------------------------------------------------------------

procedure TATBTabScroller.SetMax(const Value: integer);
begin
  if Value >= FMin then FMax := Value;
end;

//------------------------------------------------------------------------------

procedure TATBTabScroller.SetMin(const Value: integer);
begin
  if Value <= FMax then FMin := Value;
end;

//------------------------------------------------------------------------------

procedure TATBTabScroller.SetPosition(const Value: integer);
begin
  FPosition := Value;
end;

//------------------------------------------------------------------------------

procedure TATBTabScroller.SetVisible(const Value: Boolean);
begin
  FVisible := Value;
end;

//------------------------------------------------------------------------------

{ TVistaBackground }

constructor TVistaBackground.Create;
begin
  inherited;
  FSteps := 64;
  FColor := clWhite;
  FColorTo := clWhite;
  FColorMirror := clSilver;
  FColorMirrorTo := clWhite;
  FBorderColor := clGray;
  FGradient := ggVertical;
  FGradientMirror := ggVertical;
  FShadowColor := RGB(150, 170, 196);
  FHighLightColor := RGB(206, 249, 253);
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.Assign(Source: TPersistent);
begin
  if (Source is TVistaBackground) then
  begin
    FSteps := (Source as TVistaBackground).Steps;
    FColor := (Source as TVistaBackground).Color;
    FColorTo := (Source as TVistaBackground).ColorTo;
    FColorMirror := (Source as TVistaBackground).ColorMirror;
    FColorMirrorTo := (Source as TVistaBackground).ColorMirrorTo;
    FBorderColor := (Source as TVistaBackground).BorderColor;
    FShadowColor := (Source as TVistaBackground).ShadowColor;
    FHighLightColor := (Source as TVistaBackground).HighLightColor;
    Gradient := (Source as TVistaBackground).Gradient;
    GradientMirror := (Source as TVistaBackground).GradientMirror;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.SetColor(const Value: TColor);
begin
  if (FColor <> Value) then
  begin
    FColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.SetColorTo(const Value: TColor);
begin
  if (FColorTo  <> Value) then
  begin
    FColorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.SetBorderColor(const Value: TColor);
begin
  if (FBorderColor <> Value) then
  begin
    FBorderColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.SetColorMirror(const Value: TColor);
begin
  if (FColorMirror <> Value) then
  begin
    FColorMirror := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.SetColorMirrorTo(const Value: TColor);
begin
  if (FColorMirrorTo <> Value) then
  begin
    FColorMirrorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.SetGradient(const Value: TGDIPGradient);
begin
  if (FGradient <> Value) then
  begin
    FGradient := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.SetGradientMirror(const Value: TGDIPGradient);
begin
  if(FGradientMirror <> Value) then
  begin
    FGradientMirror := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TVistaBackground.SetSteps(const Value: Integer);
begin
  if (FSteps <> Value) then
  begin
    FSteps := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

{ TVistaTextBackGround }

procedure TVistaTextBackGround.Assign(Source: TPersistent);
begin
  inherited;
  if (Source is TVistaTextBackGround) then
  begin
    TextColor := (Source as TVistaTextBackGround).TextColor;
    FFont.Assign((Source as TVistaTextBackGround).Font);
  end;
end;

//------------------------------------------------------------------------------

constructor TVistaTextBackGround.Create;
begin
  inherited;
  FTextColor := clBlue;
  FFont := TFont.Create;

  if IsVista then
    FFont.Name := 'Segoe UI'
  else
    FFont.Name := 'Tahoma';
    
  FFont.Size := 8;
  FFont.Style := [];
  FSystemFont := true;
end;

//------------------------------------------------------------------------------

destructor TVistaTextBackGround.Destroy;
begin
  FFont.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TVistaTextBackGround.SetFont(const Value: TFont);
begin
  FFont.Assign(Value);
end;

procedure TVistaTextBackGround.SetSystemFont(const Value: boolean);
begin
  if (FSystemFont <> Value) then
  begin
    FSystemFont := value;

    if value then
    begin
      if IsVista then
        Font.Name := 'Segoe UI'
      else
        Font.Name := 'Tahoma'; 
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TVistaTextBackGround.SetTextColor(const Value: TColor);
begin
  if (FTextColor <> Value) then
  begin
    FTextColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------
(*
{ TPageGroupBackGround }

constructor TPageGroupBackGround.Create;
begin
  inherited;
  FCaptionAppearance := TCaptionAppearance.Create;
end;

//------------------------------------------------------------------------------

destructor TPageGroupBackGround.destroy;
begin
  FCaptionAppearance.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TPageGroupBackGround.Assign(Source: TPersistent);
begin
  inherited Assign(Source);
  if (Source is TPageGroupBackground) then
    FCaptionAppearance.Assign((Source as TPageGroupBackground).CaptionAppearance);
end;

//------------------------------------------------------------------------------

procedure TPageGroupBackGround.SetCaptionAppearance(
  const Value: TCaptionAppearance);
begin
  FCaptionAppearance.Assign(Value);
end;
*)
//------------------------------------------------------------------------------

{ TTabGroupItem }

procedure TTabGroupItem.Assign(Source: TPersistent);
begin
  if Source is TTabGroupItem then
  begin
    Caption := (Source as TTabGroupItem).Caption;
    ImageIndex := (Source as TTabGroupItem).ImageIndex;
    TabIndexStart := (Source as TTabGroupItem).TabIndexStart;
    TabIndexEnd := (Source as TTabGroupItem).TabIndexEnd;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

constructor TTabGroupItem.Create(Collection: TCollection);
begin
  inherited;
  Caption := '';
  FCaptionAlignment := taLeftJustify;
  ImageIndex := -1;
  TabIndexStart := -1;
  TabIndexEnd := -1;
  FDefaultAppearance := True;
  FGroupAppearance := TGroupAppearance.Create;
  FGroupAppearance.OnChange := OnGroupAppearanceChanged;
end;

//------------------------------------------------------------------------------

destructor TTabGroupItem.Destroy;
begin
  FGroupAppearance.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TTabGroupItem.OnGroupAppearanceChanged(Sender: TObject);
begin
  TTabGroups(Collection).UpdateChange;
end;

//------------------------------------------------------------------------------

procedure TTabGroupItem.SetCaption(const Value: TCaption);
begin
  if (FCaption <> Value) then
  begin
    FCaption := Value;
    TTabGroups(Collection).UpdateChange;
  end;
end;

//------------------------------------------------------------------------------

procedure TTabGroupItem.SetCaptionAlignment(const Value: TAlignment);
begin
  if (FCaptionAlignment <> Value) then
  begin
    FCaptionAlignment := Value;
    TTabGroups(Collection).UpdateChange;
  end;
end;

//------------------------------------------------------------------------------

procedure TTabGroupItem.SetDefaultAppearance(const Value: Boolean);
begin
  if (FDefaultAppearance <> Value) then
  begin
    FDefaultAppearance := Value;
    TTabGroups(Collection).UpdateChange;
  end;
end;

//------------------------------------------------------------------------------

procedure TTabGroupItem.SetGroupAppearance(const Value: TGroupAppearance);
begin
  FGroupAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TTabGroupItem.SetImageIndex(const Value: Integer);
begin
  if (FImageIndex <> Value) then
  begin
    FImageIndex := Value;
    TTabGroups(Collection).UpdateChange;
  end;
end;

//------------------------------------------------------------------------------

procedure TTabGroupItem.SetTabIndexEnd(const Value: Integer);
begin
  if (FTabIndexEnd <> Value) then
  begin
    FTabIndexEnd := Value;
    TTabGroups(Collection).UpdateChange;
  end;
end;

//------------------------------------------------------------------------------

procedure TTabGroupItem.SetTabIndexStart(const Value: Integer);
begin
  if (FTabIndexStart <> Value) then
  begin
    FTabIndexStart := Value;
    TTabGroups(Collection).UpdateChange;
  end;
end;

procedure TTabGroupItem.SetWideCaption(const Value: widestring);
begin
  if (FWideCaption <> Value) then
  begin
    FWideCaption := Value;
    TTabGroups(Collection).UpdateChange;    
  end;
end;

//------------------------------------------------------------------------------

{ TTabGroups }

function TTabGroups.Add: TTabGroupItem;
begin
  Result := TTabGroupItem(inherited Add);
end;

//------------------------------------------------------------------------------

constructor TTabGroups.Create(AOwner: TAdvToolBarPager);
begin
  inherited Create(TTabGroupItem);
  FOwner := AOwner;
end;

//------------------------------------------------------------------------------

function TTabGroups.GetItem(Index: Integer): TTabGroupItem;
begin
  Result := TTabGroupItem(inherited Items[Index]);
end;

//------------------------------------------------------------------------------

function TTabGroups.GetOwner: TPersistent;
begin
  Result := FOwner;
end;

//------------------------------------------------------------------------------

function TTabGroups.Insert(Index: Integer): TTabGroupItem;
begin
  Result := TTabGroupItem(inherited Insert(Index));
end;

//------------------------------------------------------------------------------

procedure TTabGroups.SetItem(Index: Integer; const Value: TTabGroupItem);
begin
  inherited Items[Index] := Value;
end;

//------------------------------------------------------------------------------

procedure TTabGroups.UpdateChange;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

{ TGroupAppearance }

constructor TGroupAppearance.Create;
begin
  inherited;
  FSteps := 64;
  FColor := clWhite;
  FColorTo := clWhite;
  FColorMirror := clSilver;
  FColorMirrorTo := clWhite;
  FBorderColor := RGB(172, 184, 163);
  FTextColor := clBlue;
  FGradient := ggVertical;
  FGradientMirror := ggVertical;
  FCaptionAppearance := TCaptionAppearance.Create;
  FCaptionAppearance.OnChange := OnCaptionAppearanceChanged;
  FPageAppearance := TVistaPageBackground.Create;
  FPageAppearance.OnChange := OnPageAppearanceChanged;
  FToolBarAppearance := TToolBarAppearance.Create;
  FToolBarAppearance.OnChange := OnToolBarAppearanceChanged;
  FTabAppearance := TCustomTabAppearance.Create;
  FTabAppearance.OnChange := OnTabAppearanceChanged;
  FFont := TFont.Create;
  
  if IsVista then
    FFont.Name := 'Segoe UI'
  else
    FFont.Name := 'Tahoma';
    
  FFont.Size := 8;
  FFont.Style := [];
  FSystemFont := true;
end;

//------------------------------------------------------------------------------

destructor TGroupAppearance.Destroy;
begin
  FCaptionAppearance.Free;
  FPageAppearance.Free;
  FToolBarAppearance.Free;
  FTabAppearance.Free;
  FFont.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.Assign(Source: TPersistent);
begin
  if (Source is TGroupAppearance) then
  begin
    FCaptionAppearance.Assign((Source as TGroupAppearance).CaptionAppearance);
    FPageAppearance.Assign((Source as TGroupAppearance).PageAppearance);
    FTabAppearance.Assign((Source as TGroupAppearance).TabAppearance);
    FSteps := (Source as TGroupAppearance).Steps;
    FColor := (Source as TGroupAppearance).Color;
    FColorTo := (Source as TGroupAppearance).ColorTo;
    FColorMirror := (Source as TGroupAppearance).ColorMirror;
    FColorMirrorTo := (Source as TGroupAppearance).ColorMirrorTo;
    FBorderColor := (Source as TGroupAppearance).BorderColor;
    FTextColor := (Source as TGroupAppearance).TextColor;
    Font.Assign((Source as TGroupAppearance).Font);
    Gradient := (Source as TGroupAppearance).Gradient;
    GradientMirror := (Source as TGroupAppearance).GradientMirror;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetBorderColor(const Value: TColor);
begin
  if (FBorderColor <> Value) then
  begin
    FBorderColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetColor(const Value: TColor);
begin
  if (FColor <> Value) then
  begin
    FColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetColorMirror(const Value: TColor);
begin
  if (FColorMirror <> Value) then
  begin
    FColorMirror := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetColorMirrorTo(const Value: TColor);
begin
  if (FColorMirrorTo <> Value) then
  begin
    FColorMirrorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetColorTo(const Value: TColor);
begin
  if (FColorTo  <> Value) then
  begin
    FColorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetGradient(const Value: TGDIPGradient);
begin
  if (FGradient <> Value) then
  begin
    FGradient := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetGradientMirror(const Value: TGDIPGradient);
begin
  if(FGradientMirror <> Value) then
  begin
    FGradientMirror := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetSteps(const Value: Integer);
begin
  if (FSteps <> Value) then
  begin
    FSteps := Value;
    Changed;
  end;
end;

procedure TGroupAppearance.SetSystemFont(const Value: boolean);
begin
  if (FSystemFont <> Value) then
  begin
    FSystemFont := Value;
    if value then
    begin
      if IsVista then
        FFont.Name := 'Segoe UI'
      else
        FFont.Name := 'Tahoma';
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetTextColor(const Value: TColor);
begin
  if (FTextColor <> Value) then
  begin
    FTextColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetCaptionAppearance(
  const Value: TCaptionAppearance);
begin
  FCaptionAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetPageAppearance(
  const Value: TVistaPageBackground);
begin
  FPageAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetToolBarAppearance(
  const Value: TToolBarAppearance);
begin
  FToolBarAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetTabAppearance(const Value: TCustomTabAppearance);
begin
  FTabAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.onCaptionAppearanceChanged(Sender: TObject);
begin
  Changed;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.onPageAppearanceChanged(Sender: TObject);
begin
  Changed;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.onTabAppearanceChanged(Sender: TObject);
begin
  Changed;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.onToolBarAppearanceChanged(Sender: TObject);
begin
  Changed;
end;

//------------------------------------------------------------------------------

procedure TGroupAppearance.SetFont(const Value: TFont);
begin
  FFont.Assign(Value);
end;

//------------------------------------------------------------------------------

{ TCaptionAppearance }

constructor TCaptionAppearance.Create;
begin
  inherited;
  FCaptionColor := RGB(128, 128, 128);
  FCaptionColorTo := clNone;
  FCaptionTextColor := clWhite;
  FCaptionBorderColor := clNone;
  FCaptionBorderColorHot := clNone;
  FCaptionColorHot := clNone;
  FCaptionColorHotTo := clNone;
  FCaptionTextColorHot := clWhite;
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.Assign(Source: TPersistent);
begin
  if (Source is TCaptionAppearance) then
  begin
    FCaptionColor := (Source as TCaptionAppearance).CaptionColor;
    FCaptionColorTo := (Source as TCaptionAppearance).CaptionColorTo;
    FCaptionTextColor := (Source as TCaptionAppearance).CaptionTextColor;
    FCaptionBorderColor := (Source as TCaptionAppearance).CaptionBorderColor;
    FCaptionBorderColorHot := (Source as TCaptionAppearance).CaptionBorderColorHot;
    FCaptionColorHot := (Source as TCaptionAppearance).CaptionColorHot;
    CaptionColorHotTo := (Source as TCaptionAppearance).CaptionColorHotTo;
    CaptionTextColorHot := (Source as TCaptionAppearance).CaptionTextColorHot;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.SetCaptionBorderColor(const Value: TColor);
begin
  if (FCaptionBorderColor <> Value) then
  begin
    FCaptionBorderColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.SetCaptionBorderColorHot(const Value: TColor);
begin
  if (FCaptionBorderColorHot <> Value) then
  begin
    FCaptionBorderColorHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.SetCaptionColor(const Value: TColor);
begin
  if (FCaptionColor <> Value) then
  begin
    FCaptionColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.SetCaptionColorHot(const Value: TColor);
begin
  if (FCaptionColorHot <> Value) then
  begin
    FCaptionColorHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.SetCaptionColorHotTo(const Value: TColor);
begin
  if (FCaptionColorHotTo <> Value) then
  begin
    FCaptionColorHotTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.SetCaptionColorTo(const Value: TColor);
begin
  if (FCaptionColorTo <> Value) then
  begin
    FCaptionColorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.SetCaptionTextColor(const Value: TColor);
begin
  if (FCaptionTextColor <> Value) then
  begin
    FCaptionTextColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TCaptionAppearance.SetCaptionTextColorHot(const Value: TColor);
begin
  if (FCaptionTextColorHot <> Value) then
  begin
    FCaptionTextColorHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

{ TToolBarAppearance }

constructor TToolBarAppearance.Create;
begin
  inherited;
  FColor := TGradientBackground.Create;
  FColorHot := TGradientBackground.Create;
  FColorHot.Color := clNone;
  FColorHot.ColorTo := clNone;
  FBorderColor := clNone;
  FBorderColorHot := clNone;
end;

//------------------------------------------------------------------------------

destructor TToolBarAppearance.Destroy;
begin
  FColor.Free;
  FColorHot.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TToolBarAppearance.Assign(Source: TPersistent);
begin
  if (Source is TToolBarAppearance) then
  begin
    FColor.Assign((Source as TToolBarAppearance).Color);
    FColorHot.Assign((Source as TToolBarAppearance).ColorHot);
    FBorderColor := (Source as TToolBarAppearance).BorderColor;
    FBorderColorHot := (Source as TToolBarAppearance).BorderColorHot;
  end
  else
    inherited Assign(Source);
end;

//------------------------------------------------------------------------------

procedure TToolBarAppearance.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

procedure TToolBarAppearance.SetBorderColor(const Value: TColor);
begin
  if (FBorderColor <> Value) then
  begin
    FBorderColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TToolBarAppearance.SetBorderColorHot(const Value: TColor);
begin
  if (FBorderColorHot <> Value) then
  begin
    FBorderColorHot := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TToolBarAppearance.SetColor(const Value: TGradientBackground);
begin
  FColor.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TToolBarAppearance.SetColorHot(const Value: TGradientBackground);
begin
  FColorHot.Assign(Value);
end;

//------------------------------------------------------------------------------

{ TAdvGlowMenuButton }

constructor TAdvGlowMenuButton.Create(AOwner: TComponent);
begin
  inherited;
  DropDownButton := true;
  Width := 32;
end;

function TAdvGlowMenuButton.IsMenuButton: Boolean;
begin
  Result := True;
end;

//------------------------------------------------------------------------------

{ TCompactWindow }

constructor TCompactWindow.Create(AOwner: TComponent);
begin
  inherited;
  FOwner := AOwner;
  FHideOnDeActivate := true;
  FHideTimer := TTimer.Create(self);
  FHideTimer.Interval := 1;
  FHideTimer.Enabled := false;
  FHideTimer.OnTimer := HideTimerOnTime;
end;

//------------------------------------------------------------------------------

constructor TCompactWindow.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
  inherited;
  FOwner := AOwner;
  FHideOnDeActivate := true;
  FHideTimer := TTimer.Create(self);
  FHideTimer.Interval := 1;
  FHideTimer.Enabled := false;
  FHideTimer.OnTimer := HideTimerOnTime;
end;

//------------------------------------------------------------------------------

procedure TCompactWindow.CreateParams(var Params: TCreateParams);
const
  CS_DROPSHADOW = $00020000;
begin
  inherited CreateParams(Params);
  // FF: D2005
  Params.Style := Params.Style or WS_POPUP;
  Params.Style := Params.Style - WS_CHILD;
  //Params.ExStyle := Params.ExStyle or WS_EX_NOPARENTNOTIFY;

  //Params.Style := Params.Style - WS_BORDER;
  {
  if (Win32Platform = VER_PLATFORM_WIN32_NT) and
     ((Win32MajorVersion > 5) or
      ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1))) then
    Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;

  Params.ExStyle := Params.ExStyle or WS_EX_TOPMOST; }
  if (Win32Platform = VER_PLATFORM_WIN32_NT) and
     ((Win32MajorVersion > 5) or
      ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1))) then
    Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;
end;

//------------------------------------------------------------------------------

destructor TCompactWindow.Destroy;
begin
  FHideTimer.Free;
  inherited;
end;

//------------------------------------------------------------------------------

function TCompactWindow.GetHideOnDeActivate: Boolean;
begin
  Result := CloseQuery and FHideOnDeActivate;
end;

//------------------------------------------------------------------------------

function TCompactWindow.GetParentWnd: HWnd;
var
  Last, P: HWnd;
begin
  P := GetParent((FOwner as TWinControl).Handle);
  Last := P;
  while P <> 0 do
  begin
    Last := P;
    P := GetParent(P);
  end;
  Result := Last;
end;

//------------------------------------------------------------------------------

procedure TCompactWindow.DoHide;
begin
  inherited;

  DropDownButton.Down := false;

  if Assigned(AdvToolBar) then
  begin
    AdvToolBar.OnCompactWindowHide(nil);
  end;
end;

//------------------------------------------------------------------------------

procedure TCompactWindow.HideTimerOnTime(Sender: TObject);
begin
  Hide;
  FHideTimer.Enabled := false;
end;

//------------------------------------------------------------------------------

procedure TCompactWindow.Paint;
var
  R: TRect;
begin
  inherited;
  R := ClientRect;
  R := Rect(R.Left - 4, R.Top - 4, R.Right + 4, R.Bottom + 4);
  Canvas.Brush.Color := Color;
  Canvas.Pen.Color := Color;
  Canvas.Rectangle(R);
end;

//------------------------------------------------------------------------------

procedure TCompactWindow.SetWindowSize;
begin
  if Assigned(AdvToolBar) then
  begin
    Height := AdvToolBar.Height + 2;
    Width := AdvToolBar.Width + 2;
    AdvToolBar.Left := 1;
    AdvToolBar.Top := 1;
    Color := AdvToolBar.FCurrentToolBarStyler.Color.Color;
  end;
end;

//------------------------------------------------------------------------------

procedure TCompactWindow.SetCornersRounded;
var
  rgn: THandle;
  R: TRect;
begin
  R := ClientRect;
  rgn := CreateRoundRectRgn(0,0,R.Right-R.Left,R.Bottom-R.Top, 4, 4);
  if rgn > 0 then
  begin
    try
      SetWindowRgn(Handle,rgn,true);
    finally
      DeleteObject(rgn);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TCompactWindow.WMActivate(var Message: TWMActivate);
begin

  if not Visible then
  begin
    if Assigned(AdvToolBar) then
      if Assigned(AdvToolBar.FSelfClone) and (AdvToolBar.FSelfClone.Visible) then
      begin
        AdvToolBar.FSelfClone.SetFocus;
      end;
    Exit;
  end;

  if Message.Active = integer(False) then
  begin
    if HideOnDeActivate and Visible then
    begin
      if Assigned(AdvToolBar) and Assigned(AdvToolBar.FSelfClone) and (AdvToolBar.FSelfClone.Visible) and AdvToolBar.AnyDroppedDownButton then
      begin
        // Do not close for GlowButtons when DroppedDown
      end
      else
        FHideTimer.Enabled := true;
    end;
  end
  else if Assigned(AdvToolBar) then
  begin
    if Self.Visible then
    begin
      if AdvToolBar.Visible then
        AdvToolBar.SetFocus;
      SendMessage(getParentWnd, WM_NCACTIVATE, 1, 0);
    end;

  end;
end;

//------------------------------------------------------------------------------

procedure TCompactWindow.WMNCHitTest(var Message: TWMNCHitTest);
var
  pt: TPoint;
begin
  // Make the hint sizable
  pt := ScreenToClient(Point(Message.XPos, Message.YPos));

  if (pt.X > Width - 10) and (pt.Y > Height - 10) then
    message.Result := HTBOTTOMRIGHT
end;

//------------------------------------------------------------------------------

{ TAdvPageScrollButton }

constructor TAdvPageScrollButton.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FTransparent := False;
  FAppearance := TGlowButtonAppearance.Create;
  FAppearance.OnChange := AppearanceChanged;
  FButtonPosition := bpStandalone;

  SetBounds(0, 0, 23, 22);
  ControlStyle := [csCaptureMouse, csDoubleClicks];
  ParentFont := True;

  // make sure to use a Truetype font
  Font.Name := 'Tahoma';
  ShowHint := False;
end;

//------------------------------------------------------------------------------

destructor TAdvPageScrollButton.Destroy;
begin
  FAppearance.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.CMDialogChar(var Message: TCMDialogChar);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.CMEnabledChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.CMFontChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.CMMouseEnter(var Message: TMessage);
begin
  inherited;
  if (csDesigning in ComponentState) or FMouseEnter then
    Exit;

  FMouseEnter := True;
  if Enabled then
  begin
    Invalidate;
  end;

  if Assigned(FOnMouseEnter) then
     FOnMouseEnter(Self);
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.CMMouseLeave(var Message: TMessage);
begin
  inherited;

  if (csDesigning in ComponentState) or not FMouseEnter then
    exit;

  FMouseEnter := false;

  if Enabled then
    Invalidate;

  if Assigned(FOnMouseLeave) then
     FOnMouseLeave(Self);
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.CMSysColorChange(var Message: TMessage);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.CMTextChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.Loaded;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

  if (Button <> mbLeft) or not Enabled or (csDesigning in ComponentState) then
    Exit;

  FMouseDown := true;
  if Enabled then
    Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.MouseMove(Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;

  if (csDesigning in ComponentState) then
    Exit;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.MouseUp(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

  if (csDesigning in ComponentState) then
    exit;

  Invalidate;

  FMouseDown := false;
  if Enabled then
    Click;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.Notification(AComponent: TComponent;
  AOperation: TOperation);
begin
  inherited;

  if not (csDestroying in ComponentState) and (AOperation = opRemove) then
  begin
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.WMLButtonDblClk(var Message: TWMLButtonDown);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.Paint;
var
  GradColor: TColor;
  GradColorTo: TColor;
  GradColorMirror: TColor;
  GradColorMirrorTo: TColor;
  PenColor: TColor;
  GradB, GradU: TGDIPGradient;
  Rgn1, Rgn2: HRGN;
  R: TRect;
  i, x, y: Integer;
  p: TPoint;
  BD: TButtonDisplay;
  sz: TSize;
begin
  if FTransparent and not FMouseEnter then
  begin
    // TRANSPARENCY CODE

    R := ClientRect;
    rgn1 :=  CreateRectRgn(R.Left, R.Top, R.Right, R.Bottom);
    SelectClipRgn(Canvas.Handle, rgn1);

    i := SaveDC(Canvas.Handle);
    p := ClientOrigin;
    Windows.ScreenToClient(Parent.Handle, p);
    p.x := -p.x;
    p.y := -p.y;
    MoveWindowOrg(Canvas.Handle, p.x, p.y);

    SendMessage(Parent.Handle, WM_ERASEBKGND, Canvas.Handle, 0);
    // transparency ?
    SendMessage(Parent.Handle, WM_PAINT, Canvas.Handle, 0);

    if (Parent is TWinCtrl) then
     (Parent as TWinCtrl).PaintCtrls(Canvas.Handle, nil);

    RestoreDC(Canvas.Handle, i);

    SelectClipRgn(Canvas.Handle, 0);
    DeleteObject(rgn1);
  end;

  with Appearance do
  begin
    if (not Enabled) then
    begin
      if (1>0) {Transparent} then
      begin
        GradColor := ColorDisabled;
        GradColorTo := ColorDisabledTo;
        GradColorMirror := ColorMirrorDisabled;
        GradColorMirrorTo := ColorMirrorDisabledTo;
        PenColor := BorderColorDisabled;
        GradU := GradientDisabled;
        GradB := GradientMirrorDisabled;
      end
      else
      begin
      end;
    end
    else if FMouseDown then
    begin
      GradColor := ColorDown;
      GradColorTo := ColorDownTo;
      GradColorMirror := ColorMirrorDown;
      GradColorMirrorTo := ColorMirrorDownTo;
      PenColor := BorderColorDown;
      GradU := GradientDown;
      GradB := GradientMirrorDown;
    end
    else if (False {checked}) then
    begin
      GradColor := ColorChecked;
      GradColorTo := ColorCheckedTo;
      GradColorMirror := ColorMirrorChecked;
      GradColorMirrorTo := ColorMirrorCheckedTo;
      PenColor := BorderColorChecked;
      GradU := GradientChecked;
      GradB := GradientMirrorChecked;
    end
    else //if State = absUp then
    begin
      if FMouseEnter then
      begin
        GradColor := ColorHot;
        GradColorTo := ColorHotTo;
        GradColorMirror := ColorMirrorHot;
        GradColorMirrorTo := ColorMirrorHotTo;
        PenColor := BorderColorHot;
        GradU := GradientHot;
        GradB := GradientMirrorHot;
      end
      else // Normal draw
      begin
        if (1>0) {Transparent} then
        begin
          GradColor := Color;
          GradColorTo := ColorTo;
          GradColorMirror := ColorMirror;
          GradColorMirrorTo := ColorMirrorTo;
          PenColor := BorderColor;
          GradU := Gradient;
          GradB := GradientMirror;
        end
        else
        begin
        end;
      end;
    end;

    {if (FMouseInControl or FMouseDown) and DropDownButton then
    begin
      if FInButton then
        BD := bdDropDown
      else
        BD := bdButton;
    end
    else }
      BD := bdNone;

    // do not use special border color for non standalone buttons in mouse hover/down state or checked buttons
    if (Position <> bpStandalone) and FMouseDown then
    begin
      PenColor := BorderColor;
    end;

    if (not Enabled) then
    begin
      GradColor := ColorDisabled;
      GradColorTo := ColorDisabledTo;
      GradColorMirror := ColorMirrorDisabled;
      GradColorMirrorTo := ColorMirrorDisabledTo;
      PenColor := BorderColorDisabled;
      GradU := GradientDisabled;
      GradB := GradientMirrorDisabled;
    end;

    //DrawVistaGradient(bmp.Canvas, ClientRect, GradColor, GradColorTo, GradColorMirror, GradColorMirrorTo,
      //PenColor, GradU, GradB, '', Canvas.Font, Enabled, False, aaNone, True);

    sz := DrawVistaButton(Canvas,ClientRect,GradColor, GradColorTo, GradColorMirror, GradColorMirrorTo,
      PenColor, GradU, GradB, '', '', True{FDefaultCaptionDrawing}, Font, nil, -1, True, blGlyphLeft, False{FDropDownButton},
      False, Enabled, False, dpRight{DropDownPosition}, nil, aaNone, True{FDefaultPicDrawing}, nil, BD, Transparent and not (FMouseEnter or (FMouseDown)), FMouseEnter, Position, False{DropDownSplit}, True, False{FOverlappedText}, False{FWordWrap},
      False, True{FRounded}, False{FDropDownDirection}, 2{FSpacing}, StringTrimmingNone{FTrimming});

    //Canvas.CopyMode := cmSrcCopy;
    //Canvas.CopyRect(ClientRect, bmp.Canvas, ClientRect);

    x := Self.Width div 2;
    y := Self.Height div 2;
    Canvas.Pen.Color := BlendColor(clBlack, PenColor, 50);
    case ScrollArrow of
      saLeft:
      begin
        Canvas.Pixels[x-1, y] := Canvas.Pen.Color;
        Canvas.MoveTo(x, y-1);
        Canvas.LineTo(x, y+2);
        Canvas.MoveTo(x+1, y-2);
        Canvas.LineTo(x+1, y+3);
      end;
      saRight:
      begin
        Canvas.MoveTo(x-1, y-2);
        Canvas.LineTo(x-1, y+3);
        Canvas.MoveTo(x, y-1);
        Canvas.LineTo(x, y+2);
        Canvas.Pixels[x+1, y] := Canvas.Pen.Color;
      end;
    end;

    if not Assigned(Parent) then
      Exit;

    // transparent border pixels

    if not FTransparent or FMouseEnter then
    begin
      R := ClientRect;

      if Position <> bpMiddle then
      begin
        if (Position in [bpStandalone, bpLeft]) then
        begin
          rgn1 := CreateRectRgn(0, 0, 1, 1);
        end
        else
        begin
          rgn1 := CreateRectRgn(R.Right - 1, 0, R.Right, 1);
        end;

        if (Position in [bpStandalone]) then
        begin
          rgn2 := CreateRectRgn(R.Right - 1, 0, R.Right, 1);
          CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
          DeleteObject(rgn2);
        end;

        if (Position in [bpStandalone, bpLeft]) then
        begin
          rgn2 := CreateRectRgn(0, R.Bottom - 1, 1, R.Bottom);
          CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
          DeleteObject(rgn2);
        end;

        if (Position in [bpStandalone, bpRight]) then
        begin
          rgn2 := CreateRectRgn(R.Right - 1, R.Bottom - 1, R.Right, R.Bottom);
          CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
          DeleteObject(rgn2);
        end;

        SelectClipRgn(Canvas.Handle, rgn1);

        i := SaveDC(Canvas.Handle);
        p := ClientOrigin;
        Windows.ScreenToClient(Parent.Handle, p);
        p.x := -p.x;
        p.y := -p.y;
        MoveWindowOrg(Canvas.Handle, p.x, p.y);

        SendMessage(Parent.Handle, WM_ERASEBKGND, Canvas.Handle, 0);

        // transparency ?
        SendMessage(Parent.Handle, WM_PAINT, Canvas.Handle, 0);
        if (Parent is TWinCtrl) then
          (Parent as TWinCtrl).PaintCtrls(Canvas.Handle, nil);
        RestoreDC(Canvas.Handle, i);

        SelectClipRgn(Canvas.Handle, 0);
        DeleteObject(rgn1);
      end;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.SetBounds(ALeft, ATop, AWidth,
  AHeight: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------
procedure TAdvPageScrollButton.SetParent(AParent: TWinControl);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.Click;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.CMHintShow(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.SetAppearance(
  const Value: TGlowButtonAppearance);
begin
  FAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.AppearanceChanged(Sender: TObject);
begin
  invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.SetTransparent(const Value: Boolean);
begin
  FTransparent := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.SetButtonPosition(const Value: TButtonPosition);
begin
  FButtonPosition := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.WMEraseBkGnd(var Message: TWMEraseBkGnd);
begin
  Message.Result := 1;
  inherited;
  Exit;
end;

//------------------------------------------------------------------------------

procedure TAdvPageScrollButton.SetScrollArrow(const Value: TScrollArrow);
begin
  FScrollArrow := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

{ TAdvCustomQuickAccessToolBar }

constructor TAdvCustomQuickAccessToolBar.Create(AOwner: TComponent);
begin
  inherited;
  ControlStyle := ControlStyle + [csAcceptsControls] - [csOpaque];
  FFullSize := False;
  FShowCustomizeOption := False;
  FCtrlList := TDbgList.Create;
  FHiddenCtrlList := TDbgList.Create;
  FInternalUpdatingControlPos := False;
  FCustomizeButton := nil;
  FScrollButton := nil;
  FOverflowWindow := nil;
  FOverflowWindowPanel := nil;
  FImages := nil;
  FDisabledImages := nil;
  FButtonWidth := 14;
  FButtonGap := 2;
  FUpdateCount := 0;
  DoubleBuffered := True;
end;

//------------------------------------------------------------------------------

destructor TAdvCustomQuickAccessToolBar.Destroy;
begin
  FCtrlList.Free;
  FHiddenCtrlList.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.Loaded;
begin
  inherited;
  UpdateControlList;
  UpdateSize;
  UpdateControlsPos;
  UpdateControlsVisiblity;
  UpdateAllGlowButtons;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.AlignControls(AControl: TControl;
  var ARect: TRect);
begin
  inherited;

  if not FInternalUpdatingControlPos then
  begin
    UpdateControlList;
    UpdateSize;
    UpdateControlsPos;
    UpdateControlsVisiblity;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.CMControlChange(
  var Message: TCMControlChange);
begin
  inherited;

  with Message do
  begin
    {// FF: D2005
    if (Control is TOptionSelectorWindow) or (Control is TCompactWindow) then
      Exit;

    if not FInternalControlUpdation then
    begin
      if Inserting then
        InsertControl(Control)
      else
        RemoveControl(Control);
    end; }

    if not FInternalUpdatingControlPos and (Control <> FOverflowWindow) and (Control <> FOverflowWindowPanel) then
    begin
      if (Control is TAdvCustomToolBarButton) then
      begin
        TAdvCustomToolBarButton(Control).FOffSet := 1;
      end;
      UpdateControlList;
      UpdateSize;
      UpdateControlsPos;
      UpdateControlsVisiblity;
    end;
  end;

  if Message.Inserting and not (csLoading in ComponentState) then
  begin

  end;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.UpdateControlsPos(SizeUpdate: Boolean = False);
var
  i, X, h: Integer;
  R: TRect;
begin
  if FInternalUpdatingControlPos or (csLoading in ComponentState) or (FUpdateCount > 0) then
    Exit;

  R := GetMyClientRect;
  X := R.Left;
  h := R.Bottom - R.Top;
  FInternalUpdatingControlPos := True;
  for i:= 0 to FCtrlList.Count -1 do
  begin
    TControl(FCtrlList.Items[i]).Left := X;
    X := X + TControl(FCtrlList.Items[i]).Width;
    if (FHiddenCtrlList.IndexOf(FCtrlList.Items[i]) < 0) then
    begin
      TControl(FCtrlList.Items[i]).Top := R.Top + (h - TControl(FCtrlList.Items[i]).Height) div 2;
    end
    else
    begin
      TControl(FCtrlList.Items[i]).Top := -TControl(FCtrlList.Items[i]).Height - 2;
    end;
  end;

  for i:= 0 to FHiddenCtrlList.Count-1 do
  begin
    if (TControl(FHiddenCtrlList.Items[i]).Parent = Self) then
    begin
      TControl(FHiddenCtrlList.Items[i]).Top := -TControl(FHiddenCtrlList.Items[i]).Height - 2;
    end;
  end;

  if Assigned(FCustomizeButton) and (FCustomizeButton.Visible) and (FHiddenCtrlList.Count = 0) then
  begin
    FCustomizeButton.Top := R.Top;
    FCustomizeButton.Height := R.Bottom-R.Top;
    if FullSize then
      FCustomizeButton.Left := X //Width - FCustomizeButton.Width - 3
    else
      FCustomizeButton.Left := GetCustomizeBtnRect.Left; // Width - FCustomizeButton.Width;
  end;

  if Assigned(FScrollButton) and FScrollButton.Visible and (FHiddenCtrlList.Count > 0) then
  begin
    FScrollButton.Top := R.Top;
    FScrollButton.Height := R.Bottom-R.Top;
    if FullSize then
      FScrollButton.Left := x //Width - FScrollButton.Width - 3
    else
      FScrollButton.Left := GetCustomizeBtnRect.Left; // Width - FScrollButton.Width;
  end;

  FInternalUpdatingControlPos := False;

  if SizeUpdate then
  begin
    UpdateSize;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.UpdateSize;
var
  R: TRect;
  i: Integer;
begin
  if FInternalUpdatingSize then
    Exit;
    
  if (Parent is TAdvToolBarPager) then
  begin
    if FullSize then
    begin
      FInternalUpdatingSize := True;
      R := TAdvToolBarPager(Parent).MaxQATRect;
      Self.Height := R.Bottom - R.Top;
      Self.Width := Max(R.Right - R.Left, MinWidth);
      Self.Left := R.Left;
      Self.Top := R.Top;
      FInternalUpdatingSize := False;
    end
    else
    begin
      if TAdvToolBarPager(Parent).Caption.Visible then
      begin
        FInternalUpdatingSize := True;
        R := TAdvToolBarPager(Parent).MaxQATRect;
        Self.Height := R.Bottom - R.Top;
        i := Min(R.Right - R.Left, MaxWidth);
        Self.Width := Max(i, MinWidth);
        Self.Left := R.Left;
        Self.Top := R.Top;
        FInternalUpdatingSize := False;
      end
      else
      begin
        // set Visible := False;
      end;
    end;
  end;
end;
    
//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.UpdateControlsVisiblity;
var
  i, d, j, k, x: Integer;
  R: TRect;
  OldValue: Boolean;
begin
  if not (Parent is TAdvToolBarPager) or (FUpdateCount > 0) or FInternalUpdatingSize or FInternalUpdatingControlPos or (csLoading in ComponentState) then
    Exit;

  R := GetMyClientRect;
  j := -1;
  {i:= 0;
  while (i <= FCtrlList.Count -1) do
  begin
    if (TControl(FCtrlList.Items[i]).Left + TControl(FCtrlList.Items[i]).Width > R.Right) then
    begin
      if not ShowCustomizeOption and (j < 0) then
      begin
        if (FHiddenCtrlList.Count = 0) then
        begin
          ShowScrollButton := True;
          R.Right := R.Right - SCROLLBTN_WIDTH - FButtonGap;
          j := i;
          i := -1;
        end;
      end
      else
      begin
        j := i;
        Break;
      end;
    end;
    Inc(i);
  end;}
  for i:= 0 to FCtrlList.Count -1 do
  begin
    if (TControl(FCtrlList.Items[i]).Left + TControl(FCtrlList.Items[i]).Width > R.Right) then
    begin
      j := i;
      Break;
    end;
  end;

  if (j >= 0) then  // hide controls
  begin
    OldValue := FInternalUpdatingControlPos;
    FInternalUpdatingControlPos := True;
    
    if not ShowScrollButton then
    begin
      ShowScrollButton := True;
    end;
    
    for i:= FCtrlList.Count-1 downto j do
    begin  // hide here
      if (FHiddenCtrlList.Count = 0) then
      begin
        FHiddenCtrlList.Add(FCtrlList.Items[i]);
      end
      else
      begin
        FHiddenCtrlList.Insert(0, FCtrlList.Items[i]);
      end;
    end;

    if Assigned(FCustomizeButton) and FCustomizeButton.Visible and (FCustomizeButton.Parent = Self) then
    begin
      FCustomizeButton.Visible := False;
    end;
    FInternalUpdatingControlPos := OldValue;
    UpdateControlList;
  end
  else  // unhide controls
  begin
    if (FHiddenCtrlList.Count > 0) then
    begin
      if (FCtrlList.Count > 0) then
      begin
        x := TControl(FCtrlList.Items[FCtrlList.Count-1]).Left + TControl(FCtrlList.Items[FCtrlList.Count-1]).Width;
        d := R.Right - (TControl(FCtrlList.Items[FCtrlList.Count-1]).Left + TControl(FCtrlList.Items[FCtrlList.Count-1]).Width);
      end
      else
      begin
        x := R.Left;
        d := R.Right - R.Left;
      end;
      k := FHiddenCtrlList.Count;
      i := 0;
      OldValue := FInternalUpdatingControlPos;
      FInternalUpdatingControlPos := True;
      while (i < k) and (d > 0) do
      begin
        if (TControl(FHiddenCtrlList.Items[0]).Width <= d) then
        begin   // unhide here
          if (TControl(FHiddenCtrlList.Items[0]).parent <> Self) then
          begin
            TControl(FHiddenCtrlList.Items[0]).parent := Self;
            TControl(FHiddenCtrlList.Items[0]).Left := X;
            X := X + TControl(FHiddenCtrlList.Items[0]).Width;
          end;
          d := d - TControl(FHiddenCtrlList.Items[0]).Width;
          FHiddenCtrlList.Delete(0);
        end
        else
        begin
          Break;
        end;
        Inc(i);
      end;

      if (FHiddenCtrlList.Count = 0) then
      begin
        if ShowScrollButton then
          ShowScrollButton := False;
          
        if ShowCustomizeOption then
        begin
          if not Assigned(FCustomizeButton) or (FCustomizeButton.Parent <> Self) or (not FCustomizeButton.Visible) then
          begin
            FShowCustomizeOption := False;
            ShowCustomizeOption := True;
          end;
        end;
      end;
      FInternalUpdatingControlPos := OldValue;
      UpdateControlList;
    end;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.CanShrink: Integer;
begin
  Result := Max(0, Self.Width - MinWidth);
  if FullSize then
  begin
    Result := 0;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.CanExpand: Integer;
begin
  Result := 0;
  if not FullSize then
  begin
    Result := Max(0, Width - MaxWidth);
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.MaxWidth: Integer;
var
  i: Integer;
begin
  Result := 0;
  for i:= 0 to ControlCount-1 do
  begin
    if (Controls[i].Visible or (csDesigning in ComponentState)) and (Controls[i] <> FCustomizeButton) and (Controls[i] <> FScrollButton)
       and (Controls[i] <> FOverflowWindow) and (Controls[i] <> FOverflowWindowPanel) and (FHiddenCtrlList.IndexOf(Controls[i]) < 0) then
    begin
      Result := Result + TControl(Controls[i]).Width;
    end;
  end;

  for i:= 0 to FHiddenCtrlList.Count-1 do
  begin
    if (FHiddenCtrlList[i] <> FCustomizeButton) and (FHiddenCtrlList[i] <> FScrollButton)
       and (FHiddenCtrlList[i] <> FOverflowWindow) and (FHiddenCtrlList[i] <> FOverflowWindowPanel) then
    begin
      Result := Result + TControl(FHiddenCtrlList[i]).Width;
    end;
  end;

  {
  if (FHiddenCtrlList.Count > 0) then
  begin
    Result := Result + SCROLLBTN_WIDTH;
  end
  else
  begin
    if ShowCustomizeOption then
      Result := Result + SCROLLBTN_WIDTH;
  end; }
  Result := Result + GetLeftMargin + GetRightMargin + FButtonWidth + FButtonGap;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.UpdateControlList;
begin
  FCtrlList.Clear;
  GetSequentialControlList(FCtrlList);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.GetSequentialControlList(
  aList: TDbgList);
var
  i, j: Integer;
  Added: Boolean;
begin
  if not Assigned(aList) then
    Exit;

  for i:= 0 to ControlCount -1 do
  begin
    if (Controls[i] is TControl) and ((Controls[i].Visible) or (csDesigning in ComponentState)) then
    begin
      Added := False;
      for j:= 0 to aList.Count-1 do
      begin
        if (TControl(aList[j]).Left > Controls[i].Left) then
        begin
          if (Controls[i] <> FScrollButton) and (Controls[i] <> FCustomizeButton)
             and (FHiddenCtrlList.IndexOf(Controls[i]) < 0) and (Controls[i] <> FOverflowWindow) and (Controls[i] <> FOverflowWindowPanel) then
          begin
            aList.Insert(j, Controls[i]);
          end;
          Added := True;
          Break;
        end;
      end;

      if not Added and (FHiddenCtrlList.IndexOf(Controls[i]) < 0) and (Controls[i] <> FScrollButton) and (Controls[i] <> FCustomizeButton)
         and (Controls[i] <> FOverflowWindow) and (Controls[i] <> FOverflowWindowPanel) then
        aList.Add(Controls[i]);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.CMMouseEnter(var Msg: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.CMMouseLeave(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.MouseMove(Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.MouseUp(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  inherited;

  if not (csDestroying in ComponentState) and (Operation = opRemove) then
  begin
    if (AComponent = FImages) then
    begin
      Images := nil;
      Invalidate;
    end;

    if (AComponent = FDisabledImages) then
    begin
      DisabledImages := nil;
      Invalidate;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure DrawBevelGradient(Canvas: TCanvas; FromColor, ToColor: TColor; Steps: Integer; R: TRect; Direction: Boolean);
var
  R2: TRect;
begin
  if Direction then
  begin
  end
  else
  begin
    R2 := R;
    R2.Top := R.Top + (R.Bottom - R.Top) div 2;
    R.Bottom := R2.Top;
    DrawGradient(Canvas, FromColor, ToColor, Steps, R, Direction);
    DrawGradient(Canvas, ToColor, FromColor, Steps, R2, Direction);
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.Paint;
var
  R, R1, R2: TRect;
  Appearance: TQATAppearance;
  i, w, h, j: Integer;
  P: TPoint;
  Clr: TColor;
  bmp, bmp1, bmp2: TBitmap;
  graphics : TGPGraphics;
  gppen : tgppen;
  rectf: TGPRectF;
  GpRgn, GpRgn2: TGPRegion;
  Path: TGPGraphicsPath;
  linGrBrush: TGPLinearGradientBrush;
begin
  //inherited;
  if not (Self.Parent is TAdvToolBarPager) or (FUpdateCount > 0) then
    Exit;

  Appearance := TAdvToolBarPager(Self.Parent).FCurrentToolBarStyler.QATAppearance;

  if not FullSize then
  begin
    // TRANSPARENCY CODE

    R := ClientRect;
    bmp := TBitmap.Create;
    bmp.Width := R.Right - R.Left;
    bmp.Height := R.Bottom - R.Top;

    bmp1 := TBitmap.Create;
    bmp1.Width := Left + (R.Right - R.Left);
    bmp1.Height := Top + (R.Bottom - R.Top);

    i := SaveDC(bmp1.Canvas.Handle);
    p := ClientOrigin;
    Windows.ScreenToClient(Parent.Handle, p);
    p.x := -p.x;
    p.y := -p.y;
    MoveWindowOrg(bmp1.Canvas.Handle, p.x, p.y);

    SendMessage(Parent.Handle, WM_ERASEBKGND, bmp1.Canvas.Handle, 0);
    // transparency ?
    SendMessage(Parent.Handle, WM_PAINT, bmp1.Canvas.Handle, 0);

    if (Parent is TWinCtrl) then
     (Parent as TWinCtrl).PaintCtrls(bmp1.Canvas.Handle, nil);

    RestoreDC(bmp1.Canvas.Handle, i);

    bmp.Canvas.Draw(-Left, -Top, bmp1);

    //----- Round Right
    R := GetDrawingRect;

    i := self.Height div 3;

    R := GetDrawingRect;
    R.Bottom := R.Bottom - 1;

    with Appearance do
    begin
      bmp2 := TBitmap.Create;
      bmp2.Width := R.Right - R.Left;
      bmp2.Height := (R.Bottom - R.Top) + 6;
      //DrawBevelGradient(bmp2.Canvas, Color, ColorTo, 80, Rect(R.Left, R.Top, R.Right, bmp2.Height), False);
      //bmp.Canvas.Draw(0, 0, bmp2);

      graphics := TGPGraphics.Create(bmp.Canvas.Handle);
      graphics.SetSmoothingMode(SmoothingModeAntiAlias);

      //--- GDIP clipping
      //R1 := Rect(R.Left, R.Top-1, R.Right - (Self.Height + 6), R.Bottom+1);
      R1 := Rect(R.Left, R.Top-1, R.Right - (Self.Height div 2), R.Bottom+1);
      rectf := MakeRect(R1.Left,R1.Top,R1.Right,R1.Bottom);
      GpRgn := TGPRegion.Create(rectf);

      // Right Round
      path := TGPGraphicsPath.Create;
      path.AddArc(R.Right - (Self.Height + 6), R.Top-2, Self.Height + 4, Self.Height-1, 30, 360);
      path.CloseFigure;
      GpRgn2 := TGPRegion.Create(Path);
      GpRgn.Union(GpRgn2);
      path.Free;
      GpRgn2.Free;

      // Left Curve
      j := 1;
      if TAdvToolBarPager(Self.Parent).FCurrentToolBarStyler.QATSharpCurve then  // FF: bsOffice2007Obsidian
        j := 2;

      path := TGPGraphicsPath.Create;
      path.AddArc(R.Left - (Height - i-2), R.Top, Height + j, Height + i + 3, 20, 360);
      path.CloseFigure;
      GpRgn.Exclude(Path);
      path.Free;

      graphics.SetClip(GpRgn, CombineModeReplace);
      //---

      w := (R.Right - R.Left);
      h := (R.Bottom - R.Top);

      //-- Draw gradient
      linGrBrush := TGPLinearGradientBrush.Create(MakeRect(R1.Left,R1.Top,w, h),ColorToARGB(Color),ColorToARGB(ColorTo), LinearGradientModeVertical);
      graphics.FillRectangle(linGrBrush, R1.Left +1, R1.Top + 1, w - 1, h - 1);
      linGrBrush.Free;
      bmp2.Canvas.Draw(0, 0, bmp);
      //--

      gppen := TGPPen.Create(ColorToARGB(Appearance.BorderColor),1);

      //DrawGDIPArc(graphics, gppen, R.Right - 31, R.Top-2, 28, 24, 30, 360);
      DrawGDIPArc(graphics, gppen, R.Right - (Self.Height + 6), R.Top-2, Self.Height + 3, Self.Height-1, 30, 360);
      //DrawGDIPArc(graphics, gppen, R.Left - 18, R.Top, 27, 30, 20, 360);
      i := self.Height div 3;
      DrawGDIPArc(graphics, gppen, R.Left - (Height - i-2), R.Top, Height + 2, Height + i + 4, 20, 360);

      R2 := Rect(GetLeftMargin - 1, R.Top, R.Right - (Self.Height div 2), R.Bottom);
      bmp.Canvas.CopyMode := cmSrcCopy;
      bmp.Canvas.CopyRect(R2, bmp2.Canvas, R2{Rect(R.Right-35, R.Top, R.Right-25, R.Bottom)});

      //DrawGDIPLine(graphics, gppen, R.Left, R.Top, w - 10, 0);
      //DrawGDIPLine(graphics, gppen, R.Left - (Height - i - 2) + (Height + 2), R.Bottom - 1, w - 18, 0);

      gppen.Free;

      gppen := TGPPen.Create(ColorToARGB(BlendColor(TAdvToolBarPager(Self.Parent).FCurrentToolBarStyler.PagerCaption.Color, Appearance.BorderColor, 60)),1);
      DrawGDIPLine(graphics, gppen, R.Left, R.Top - 1, w - 10, 0);
      gppen.Free;

      gppen := TGPPen.Create(ColorToARGB(BlendColor(TAdvToolBarPager(Self.Parent).FCurrentToolBarStyler.PagerCaption.ColorMirror, Appearance.BorderColor, 40)),1);
      DrawGDIPLine(graphics, gppen,R.Left - (Height - i - 2) + (Height + 2), R.Bottom, w - 20, 0);
      gppen.Free;

      Canvas.Draw(0, 0, bmp);

      bmp.Free;
      bmp1.Free;
      bmp2.Free;

      GpRgn.Free;
      graphics.Free;
    end;
  end
  else  // FullSize
  begin
    R := GetDrawingRect;
    Clr := Appearance.FullSizeColor;
    Canvas.Brush.Color := Clr;
    Canvas.Pen.Color := Appearance.BorderColor;
    if (Appearance.FullSizeColorTo <> clNone) then
    begin
      DrawGradient(Canvas, Appearance.FullSizeColor, Appearance.FullSizeColorTo, 80, R, False);
      Canvas.Brush.Style := bsClear;
      Canvas.Pen.Color := Appearance.FullSizeBorderColor;
      Canvas.MoveTo(R.Left+1, R.Top);
      Canvas.LineTo(R.Right-1, R.Top);
      Canvas.MoveTo(R.Right-1, R.Top+1);
      Canvas.LineTo(R.Right-1, R.Bottom-2);
      Canvas.MoveTo(R.Left+1, R.Bottom-2);
      Canvas.LineTo(R.Right-1, R.Bottom-2);
      Canvas.MoveTo(R.Left, R.Top+1);
      Canvas.LineTo(R.Left, R.Bottom-2);

      Canvas.Pen.Color := BlendColor(clWhite, Appearance.FullSizeColor, 50);
      Canvas.MoveTo(R.Left+1, R.Top+1);
      Canvas.LineTo(R.Right-1, R.Top+1);
      Canvas.MoveTo(R.Right, R.Top);
      Canvas.LineTo(R.Right, R.Bottom-1);
      Canvas.MoveTo(R.Left+1, R.Bottom-1);
      Canvas.LineTo(R.Right, R.Bottom-1);
      Canvas.MoveTo(R.Left+1, R.Top+1);
      Canvas.LineTo(R.Left+1, R.Bottom-2);
    end
    else
    begin
      Canvas.Rectangle(R);
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.SetBounds(ALeft, ATop, AWidth,
  AHeight: Integer);
begin
  inherited;
  UpdateSize;
  UpdateControlsVisiblity;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.SetCustomizeHint(const Value: string);
begin
  FCustomizeHint := Value;
  if Assigned(FCustomizeButton) then
    FCustomizeButton.Hint := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.SetParent(AParent: TWinControl);
begin
  if Assigned(AParent) and not (AParent is TAdvToolBarPager) then
    raise exception.Create('Invalid Parent');
    
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.Update;
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.UpdateMe(PropID: integer);
begin
  if (PropID in [0, 10, 11, 12]) then
  begin
    Invalidate;
  end;

  if (PropID in [0, 2, 7]) then
  begin
    UpdateAllGlowButtons;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.WMEraseBkGnd(var Msg: TMessage);
begin
  Msg.Result := 1;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.SetFullSize(const Value: Boolean);
begin
  if (FFullSize <> Value) then
  begin
    FFullSize := Value;
    UpdateControlList;
    UpdateSize;
    UpdateControlsPos;
    UpdateControlsVisiblity;
    UpdateControlsPos;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.SetShowCustomizeOption(
  const Value: Boolean);
begin
  if (FShowCustomizeOption <> Value) then
  begin
    FShowCustomizeOption := Value;
    if FShowCustomizeOption then
    begin
      if (FCustomizeButton = nil) then
      begin
        FCustomizeButton := TAdvVistaButton.Create(Self);
        FCustomizeButton.Parent := Self;
        FCustomizeButton.ArrowStyle := asWithLine;
        FCustomizeButton.ScrollArrow := saBottom;
        FCustomizeButton.Height := Self.Height;
        FCustomizeButton.Width := FButtonWidth;
        FCustomizeButton.OnClick := OnCustomizeButtonClick;
        FCustomizeButton.Hint := FCustomizeHint;
      end
      else
      begin
        FCustomizeButton.Visible := False;
        FCustomizeButton.Height := Self.Height;
        FCustomizeButton.Width := FButtonWidth;
      end;

      if (FCustomizeButton.Parent <> Self) then
      begin
        FCustomizeButton.Parent := Self;
      end;

      if Assigned(CurrentToolBarStyler) then
      begin
        FCustomizeButton.Appearance.Assign(CurrentToolBarStyler.GlowButtonAppearance);
      end;
      FCustomizeButton.Visible := FShowCustomizeOption;
    end
    else
    begin
      if (FCustomizeButton <> nil) then
      begin
        FCustomizeButton.Visible := False;
        FCustomizeButton.Width := 0;
        FCustomizeButton.Height := 0;
      end;
    end;
    UpdateSize;
    UpdateControlsPos;
    UpdateControlsVisiblity;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.OnCustomizeButtonClick(
  Sender: TObject);
var
  pt, spt: TPoint;
begin
  if Assigned(OnCustomizeClick) then
    OnCustomizeClick(Self);

  if Assigned(DropDownPopupMenu) and Assigned(FCustomizeButton) then
  begin
    pt := Point(FCustomizeButton.Left, FCustomizeButton.Top + FCustomizeButton.Height);
    spt := ClientToScreen(pt);
    FCustomizeButton.Down := True;
    DropDownPopupMenu.Popup(spt.X, spt.Y);
    FCustomizeButton.Down := False;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.GetMyClientRect: TRect;
begin
  Result := GetDrawingRect;
  Result.Left := GetLeftMargin;
  Result.Right := Result.Right - GetRightMargin;
  Result.Top := Result.Top;// + 1;
  Result.Bottom := Result.Bottom - 1;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.GetDrawingRect: TRect;
begin
  Result := ClientRect;
  if not FullSize then
  begin
    Result.Top := Result.Top + 3;

    //if ((FHiddenCtrlList.Count > 0) or (ShowCustomizeOption)) then
    begin
      Result.Right := Result.Right - FButtonWidth - FButtonGap;
    end;
  end;

  //Result.Bottom := Result.Bottom - 1;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.MinWidth: Integer;
begin
  Result := DEFAULT_MINLENGTH;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.TotalCtrlsWidth: Integer;
var
  i: Integer;
begin
  Result := 0;
  for i:= 0 to FCtrlList.Count-1 do
  begin
    Result := Result + TControl(FCtrlList).Width;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.GetLeftMargin: Integer;
begin
  if FullSize then
  begin
    Result := 4;
  end
  else
  begin
    //Result := 13;
    Result := (Self.Height div 2) + 2;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.GetRightMargin: Integer;
begin
  if FullSize then
  begin
    Result := 4;
  end
  else
  begin
    Result := 12;
    {if ShowCustomizeOption or (FHiddenCtrlList.Count > 0) then
    begin
      Result := Result + SCROLLBTN_WIDTH;
    end;}
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.InitializeOverflowWindow;
var
  i: Integer;
begin
  if not (csDesigning in ComponentState) then
  begin
    if not Assigned(FOverflowWindow) then
    begin
      FOverflowWindow := TOptionSelectorWindow.CreateNew(self);
      FOverflowWindow.Parent := self;   // FF: D2005
      FOverflowWindow.BorderIcons := [];
      FOverflowWindow.BorderStyle := bsNone;
      FOverflowWindow.Ctl3D := false;
      FOverflowWindow.FormStyle := fsStayOnTop;
      FOverflowWindow.Visible := False;
      FOverflowWindow.Width := 10;
      FOverflowWindow.Height := 10;
      FOverflowWindow.AutoScroll := False;
      FOverflowWindow.BorderWidth := 0;
      FOverflowWindow.OnHide := OnOverflowWindowHide;
      FOverflowWindow.AdvToolBar := nil;
    end;

    if not Assigned(FOverflowWindowPanel) then
    begin
      FOverflowWindowPanel := TControlSelectorPanel.Create(FOverflowWindow);
      FOverflowWindowPanel.Parent := FOverflowWindow;
    end;

    FOverflowWindowPanel.ShowAddAndRemoveBtn := False;
    {if Assigned(self.OptionMenu) then
      if (self.OptionMenu is TAdvPopupMenu) then
        TAdvPopupMenu(OptionMenu).MenuStyler := FCurrentToolBarStyler.CurrentAdvMenuStyler;}
        
    FOverflowWindowPanel.OptionsMenu := nil; //self.OptionMenu;
    FOverflowWindowPanel.TextAutoOptionMenu := ''; //self.TextAutoOptionMenu;
    FOverflowWindowPanel.TextOptionMenu := ''; //self.TextOptionMenu;

    FOverflowWindowPanel.Customizer := nil;
    FOverflowWindowPanel.AdvToolBar := nil;

    {if Assigned(FMenu) then
    begin
      FOptionWindowPanel.ItemColorHot := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.HoverColor;
      FOptionWindowPanel.ItemColorHotTo := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.HoverColorTo;
      FOptionWindowPanel.ItemColorDown := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.SelectedColor;
      FOptionWindowPanel.ItemColorDownTo := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.SelectedColorTo;
      FOptionWindowPanel.ItemTextColor := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.Font.Color;
      FOptionWindowPanel.ItemTextColorHot := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.HoverTextColor;
      FOptionWindowPanel.ItemTextColorDown := FCurrentToolBarStyler.CurrentAdvMenuStyler.RootItem.SelectedTextColor;
    end
    else
    begin
      FOptionWindowPanel.ItemColorHot := FCurrentToolBarStyler.ButtonAppearance.ColorHot;
      FOptionWindowPanel.ItemColorHotTo := FCurrentToolBarStyler.ButtonAppearance.ColorHotTo;
      FOptionWindowPanel.ItemColorDown := FCurrentToolBarStyler.ButtonAppearance.ColorDown;
      FOptionWindowPanel.ItemColorDownTo := FCurrentToolBarStyler.ButtonAppearance.ColorDownTo;
      FOptionWindowPanel.ItemTextColor := FCurrentToolBarStyler.ButtonAppearance.CaptionTextColor;
      FOptionWindowPanel.ItemTextColorHot := FCurrentToolBarStyler.ButtonAppearance.CaptionTextColorHot;
      FOptionWindowPanel.ItemTextColorDown := FCurrentToolBarStyler.ButtonAppearance.CaptionTextColorDown;
    end;}
    if Assigned(CurrentToolBarStyler) then
    begin
      FOverflowWindowPanel.ItemColorHot := CurrentToolBarStyler.ButtonAppearance.ColorHot;
      FOverflowWindowPanel.ItemColorHotTo := CurrentToolBarStyler.ButtonAppearance.ColorHotTo;
      FOverflowWindowPanel.ItemColorDown := CurrentToolBarStyler.ButtonAppearance.ColorDown;
      FOverflowWindowPanel.ItemColorDownTo := CurrentToolBarStyler.ButtonAppearance.ColorDownTo;
      FOverflowWindowPanel.ItemTextColor := CurrentToolBarStyler.ButtonAppearance.CaptionTextColor;
      FOverflowWindowPanel.ItemTextColorHot := CurrentToolBarStyler.ButtonAppearance.CaptionTextColorHot;
      FOverflowWindowPanel.ItemTextColorDown := CurrentToolBarStyler.ButtonAppearance.CaptionTextColorDown;
      FOverflowWindowPanel.WindowBorderColor := CurrentToolBarStyler.QATAppearance.FullSizeBorderColor;
      FOverflowWindowPanel.Color := CurrentToolBarStyler.TabAppearance.BackGround.Color;
      FOverflowWindowPanel.ColorTo := CurrentToolBarStyler.TabAppearance.BackGround.Color;
    end;

    FOverflowWindow.OptionsPanel := FOverflowWindowPanel;
    FOverflowWindowPanel.ControlList.Clear;

    // Assigning Hidden Controls
    FInternalUpdatingControlPos := True;
    for i:= 0 to FHiddenCtrlList.Count - 1 do
    begin
      FOverflowWindowPanel.AddControl(TControl(FHiddenCtrlList[i]));
    end;

    if ShowCustomizeOption and Assigned(FCustomizeButton) then
    begin
      FOverflowWindowPanel.AddControl(FCustomizeButton);
      FCustomizeButton.Visible := True;
    end;

    FInternalUpdatingControlPos := False;
    FOverflowWindowPanel.ArrangeControls;

    FOverflowWindow.SetWindowSize;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.ShowOverflowWindow(X, Y: Integer; ForcePoint: Boolean=True);
var
  pt, spt: TPoint;
  R: TRect;
  {$IFDEF DELPHI9_LVL}
  w,h: Integer;
  {$ENDIF}
begin
  InitializeOverflowWindow;
  if not ForcePoint then
  begin
    pt := Point(Left + Width - 12, Top + Height + 1);
    spt := Parent.ClientToScreen(pt);

  {$IFNDEF TMSDOTNET}
    SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
  {$ENDIF}
  {$IFDEF TMSDOTNET}
    SystemParametersInfo(SPI_GETWORKAREA, 0, R, 0);
  {$ENDIF}

    if R.Bottom < (spt.Y + FOverflowWindow.Height + 2) then
      spt.Y := spt.Y - ((spt.Y + FOverflowWindow.Height + 2) - R.Bottom);

    {$IFDEF DELPHI6_LVL}
    R.Right := Screen.MonitorFromPoint(spt).Width;
    {$ELSE}
    R.Right := Screen.Width;
    {$ENDIF}

    if (R.Right < spt.X + FOverflowWindow.Width) then
    begin
      spt.X := spt.X - ((spt.X + FOverflowWindow.Width) - R.Right);
    end;
    X := spt.X;
    Y := spt.Y;
  end;

  if not FOverflowWindowPanel.IsEmpty then
  begin
    {$IFDEF DELPHI9_LVL}
    w := FOverflowWindow.Width;
    h := FOverflowWindow.Height;
    FOverflowWindow.Width := 0;
    FOverflowWindow.Height := 0;
    FOverflowWindow.Visible := True;
    {$ENDIF}

    FOverflowWindow.Left := X;
    FOverflowWindow.Top := Y;
    FOverflowWindow.Visible := True;

    {$IFDEF DELPHI9_LVL}
    FOverflowWindow.Width := w;
    FOverflowWindow.Height := h;
    {$ENDIF}
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.HideOverflowWindow;
begin
  if Assigned(FOverflowWindow) and FOverflowWindow.visible then
  begin
    FOverflowWindow.visible := False;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.OnOverflowWindowHide(Sender: TObject);
begin
  if Assigned(FScrollButton) then
    FScrollButton.Down := False;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.GetCustomAdvToolBarStyler: TCustomAdvToolBarStyler;
begin
  Result := nil;
  if (Parent is TAdvToolBarPager) then
    Result := TAdvToolBarPager(Parent).FCurrentToolBarStyler;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.SetDisabledImages(
  const Value: TCustomImageList);
var
  i: Integer;
begin
  if Value <> FDisabledImages then
  begin
    FDisabledImages := Value;

    for i := 0 to FCtrlList.Count - 1 do
    begin
      if TControl(FCtrlList[i]) is TAdvCustomToolBarControl then
        TAdvCustomToolBarControl(FCtrlList[i]).AdjustSize;
    end;

    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.SetImages(
  const Value: TCustomImageList);
var
  i: integer;
  OldImages: TCustomImageList;
begin
  if Value <> FImages then
  begin
    OldImages := FImages;
    FImages := Value;

    if Assigned(OldImages) then
    begin
      if Assigned(FImages) then
      begin
        Height := Height + (FImages.Height - OldImages.Height)
      end
      else
      begin
        Height := Height - OldImages.Height
      end;
    end;

    FInternalUpdatingControlPos := True;
    for i := 0 to FCtrlList.Count - 1 do
    begin
      if TControl(FCtrlList[i]) is TAdvCustomToolBarControl then
        TAdvCustomToolBarControl(FCtrlList[i]).AdjustSize;
    end;
    FInternalUpdatingControlPos := False;

    UpdateControlsPos(True);

    if Assigned(OldImages) then
    begin
      for i := 0 to FCtrlList.Count - 1 do
      begin
        if TControl(FCtrlList[i]) is TAdvCustomToolBarControl then
          TAdvCustomToolBarControl(FCtrlList[i]).AdjustSize;
        if TControl(FCtrlList[i]) is TAdvCustomToolBarButton then
          TAdvCustomToolBarButton(FCtrlList[i]).GenerateShade;
      end;
    end;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.GetShowScrollButton: Boolean;
begin
  Result := Assigned(FScrollButton) and FScrollButton.Visible;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.SetShowScrollButton(
  const Value: Boolean);
begin
  if (Value <> ShowScrollButton) then
  begin
    if Value then
    begin
      if (FScrollButton = nil) then
      begin
        FScrollButton := TAdvVistaButton.Create(Self);
        FScrollButton.Parent := Self;
        FScrollButton.ArrowStyle := asDouble;
        FScrollButton.ScrollArrow := saRight;
        FScrollButton.Height := Self.Height;
        FScrollButton.Width := FButtonWidth;
        FScrollButton.OnClick := OnScrollButtonClick;
        FScrollButton.OnMouseDown := OnScrollButtonDown;
      end;

      FScrollButton.Left := GetCustomizeBtnRect.Left;
      FScrollButton.Top := GetCustomizeBtnRect.Top;
      if Assigned(CurrentToolBarStyler) then
      begin
        FScrollButton.Appearance.Assign(CurrentToolBarStyler.GlowButtonAppearance);
      end;
      FScrollButton.Visible := Value;
    end
    else
    begin
      if Assigned(FScrollButton) then
      begin
        FScrollButton.Visible := False;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.OnScrollButtonClick(Sender: TObject);
begin
  //ShowOverflowWindow(0, 0, False);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.OnScrollButtonDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if Assigned(FScrollButton) then
    FScrollButton.Down := True;
  ShowOverflowWindow(0, 0, False);
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.GetCustomizeBtnRect: TRect;
begin
  Result := Rect(Width - FButtonWidth, 1, Width, Height);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.UpdateAllGlowButtons;
var
  I: Integer;
  tmsif: ITMSStyle;
  ToolBarStyler: TCustomAdvToolBarStyler;
begin
  ToolBarStyler := CurrentToolBarStyler;
  if Assigned(ToolBarStyler) then
  begin
    for i := 0 to ControlCount - 1 do
    begin
      if (TControl(Controls[i]) is TAdvCustomGlowButton) then
      begin
        TAdvGlowButton(Controls[i]).Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
      end;

      if (TControl(Controls[i]) is TAdvGlowMenuButton) then
          TAdvGlowMenuButton(Controls[i]).Appearance.Assign(ToolBarStyler.GlowButtonAppearance);

{$IFNDEF TMS_STD}
      if (TControl(Controls[i]) is TDBAdvGlowButton) then
          TDBAdvGlowButton(Controls[i]).Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
{$ENDIF}

      if (ToolBarStyler.GetInterface(ITMSStyle, tmsif)) and (ToolBarStyler.TMSStyle <> tsCustom) then
      begin
        if (TControl(Controls[i]).GetInterface(ITMSStyle, tmsif)) then
           tmsif.SetComponentStyle(ToolBarStyler.TMSStyle);
      end;
    end;

    for i := 0 to FHiddenCtrlList.Count - 1 do
    begin
      if (TControl(FHiddenCtrlList[i]) is TAdvCustomGlowButton) then
      begin
        TAdvGlowButton(FHiddenCtrlList[i]).Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
      end;

      if (TControl(FHiddenCtrlList[i]) is TAdvGlowMenuButton) then
          TAdvGlowMenuButton(FHiddenCtrlList[i]).Appearance.Assign(ToolBarStyler.GlowButtonAppearance);

{$IFNDEF TMS_STD}
      if (TControl(FHiddenCtrlList[i]) is TDBAdvGlowButton) then
          TDBAdvGlowButton(FHiddenCtrlList[i]).Appearance.Assign(ToolBarStyler.GlowButtonAppearance);
{$ENDIF}

      if (ToolBarStyler.GetInterface(ITMSStyle, tmsif)) and (ToolBarStyler.TMSStyle <> tsCustom) then
      begin
        if (TControl(FHiddenCtrlList[i]).GetInterface(ITMSStyle, tmsif)) then
           tmsif.SetComponentStyle(ToolBarStyler.TMSStyle);
      end;
    end;


    if Assigned(FCustomizeButton) then
      FCustomizeButton.Appearance.Assign(ToolBarStyler.GlowButtonAppearance);

  end;


end;


//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.AddToolBarControl(AControl: TControl);
begin
  if Assigned(AControl) and (AControl.Parent <> self) then
  begin
    AControl.Parent := Self;
    AControl.Left := Self.Width;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.BeginUpdate;
begin
  if not Visible then
    Exit;
    
  Inc(FUpdateCount);
  SendMessage(Handle,WM_SETREDRAW, integer(False),0);
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.EndUpdate;
begin
  if not Visible then
    Exit;

  if FUpdateCount > 0 then Dec(FUpdateCount);
  if FUpdateCount = 0 then
  begin
    SendMessage(Handle,WM_SETREDRAW,integer(True),0);
    InvalidateRect(Handle, Nil, False);
    //NCPaintProc;
    UpdateControlList;
    UpdateSize;
    UpdateControlsPos;
    UpdateControlsVisiblity;
  end;
end;

//------------------------------------------------------------------------------

function TAdvCustomQuickAccessToolBar.HasShortCut(aShortCut: String;
  var VisibleHintCount: Integer): Boolean;
var
  i: Integer;
  sub: String;
begin
  Result := False;
  for i:= 0 to FCtrlList.Count-1 do
  begin
    if (TControl(FCtrlList[i]) is TAdvCustomGlowButton) then
    begin
      if (UpperCase(TAdvCustomGlowButton(FCtrlList[i]).ShortCutHint) = UpperCase(aShortCut)) then
      begin
        if (TAdvCustomGlowButton(FCtrlList[i]).Enabled) and TAdvCustomGlowButton(FCtrlList[i]).Visible then
        begin
          TAdvCustomGlowButton(FCtrlList[i]).SetFocus;
          TAdvCustomGlowButton(FCtrlList[i]).Repaint;
          TProCustomGlowButton(FCtrlList[i]).InternalClick;
        end;
        Result := True;
        Break;
      end
      else if (Length(TAdvCustomGlowButton(FCtrlList[i]).ShortCutHint) > 0) then
      begin
        sub := Copy(TAdvCustomGlowButton(FCtrlList[i]).ShortCutHint, 1, Length(aShortCut));
        if (UpperCase(sub) <> UpperCase(aShortCut)) then
        begin
          TAdvCustomGlowButton(FCtrlList[i]).HideShortCutHint;
        end
        else
        begin
          Inc(VisibleHintCount);
        end;
      end;
    end;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.HideShortCutHintOfButtons;
var
  i: Integer;
begin
  for i := 0 to FCtrlList.Count - 1 do
  begin
    if (TControl(FCtrlList[i]) is TAdvCustomGlowButton) then
      TAdvCustomGlowButton(FCtrlList[i]).HideShortCutHint;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvCustomQuickAccessToolBar.ShowShortCutHintOfButtons;
var
  i: Integer;
begin
  for i := 0 to FCtrlList.Count - 1 do
  begin
    if (TControl(FCtrlList[i]) is TAdvCustomGlowButton) and (TControl(FCtrlList[i]).Enabled) and (TControl(FCtrlList[i]).Visible) and (TControl(FCtrlList[i]).Parent = Self) then
      TAdvCustomGlowButton(FCtrlList[i]).ShowShortCutHint;
  end;
end;

//------------------------------------------------------------------------------

{ TAdvVistaButton }

constructor TAdvVistaButton.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FTransparent := False;
  FAppearance := TGlowButtonAppearance.Create;
  FAppearance.OnChange := AppearanceChanged;
  FButtonPosition := bpStandalone;

  SetBounds(0, 0, 23, 22);
  ControlStyle := [csCaptureMouse, csDoubleClicks];
  ParentFont := True;

  // make sure to use a Truetype font
  Font.Name := 'Tahoma';
  ShowHint := False;
end;

//------------------------------------------------------------------------------

destructor TAdvVistaButton.Destroy;
begin
  FAppearance.Free;
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.CMDialogChar(var Message: TCMDialogChar);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.CMEnabledChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.CMFontChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.CMMouseEnter(var Message: TMessage);
begin
  inherited;
  if (csDesigning in ComponentState) or FMouseEnter then
    Exit;

  FMouseEnter := True;
  if Enabled and not Down then
  begin
    Invalidate;
  end;

  if Assigned(FOnMouseEnter) then
     FOnMouseEnter(Self);
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.CMMouseLeave(var Message: TMessage);
begin
  inherited;

  if (csDesigning in ComponentState) or not FMouseEnter then
    exit;

  FMouseEnter := false;

  if Enabled and not Down then
    Invalidate;

  if Assigned(FOnMouseLeave) then
     FOnMouseLeave(Self);
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.CMSysColorChange(var Message: TMessage);
begin
  inherited;

end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.CMTextChanged(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.Loaded;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.MouseDown(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

  if (Button <> mbLeft) or not Enabled or (csDesigning in ComponentState) then
    Exit;

  FMouseDown := true;
  if Enabled then
    Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.MouseMove(Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;

  if (csDesigning in ComponentState) then
    Exit;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.MouseUp(Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  inherited;

  if (csDesigning in ComponentState) then
    exit;

  Invalidate;

  FMouseDown := false;
  if Enabled then
    Click;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.Notification(AComponent: TComponent;
  AOperation: TOperation);
begin
  inherited;

  if not (csDestroying in ComponentState) and (AOperation = opRemove) then
  begin
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.WMLButtonDblClk(var Message: TWMLButtonDown);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.Paint;
                               
  procedure DrawFlatDoubleArrows(R: TRect);
  begin
    with Canvas do
    begin
      //  |_
      //  |
      Pen.Color := clBlack;
      moveto(R.Right - 6, R.Top + 5);
      LineTo(R.Right - 6, R.Top + 8);
      moveto(R.Right - 6, R.Top + 6);
      LineTo(R.Right - 4, R.Top + 6);
      //  |_
      //  |
      moveto(R.Right - 10, R.Top + 5);
      LineTo(R.Right - 10, R.Top + 8);
      moveto(R.Right - 10, R.Top + 6);
      LineTo(R.Right - 8, R.Top + 6);

      //  |-
      Pen.Color := clWhite;
      moveto(R.Right - 5, R.Top + 7);
      LineTo(R.Right - 5, R.Top + 9);
      moveto(R.Right - 5, R.Top + 7);
      LineTo(R.Right - 3, R.Top + 7);
      //  |-
      moveto(R.Right - 9, R.Top + 7);
      LineTo(R.Right - 9, R.Top + 9);
      moveto(R.Right - 9, R.Top + 7);
      LineTo(R.Right - 7, R.Top + 7);
    end;
  end;

  procedure DrawFlatOptionsIndicator(R: TRect);
  begin
    with Canvas do
    begin
      Pen.Color := clBlack;
      moveto(R.Right - 9, R.Bottom - 9);
      LineTo(R.Right - 4, R.Bottom - 9);

      moveto(R.Right - 9, R.Bottom - 7);
      LineTo(R.Right - 4, R.Bottom - 7);
      moveto(R.Right - 8, R.Bottom - 6);
      LineTo(R.Right - 5, R.Bottom - 6);
      Pixels[R.Right - 7, R.Bottom - 5] := clBlack;
    end;
  end;

var
  GradColor: TColor;
  GradColorTo: TColor;
  GradColorMirror: TColor;
  GradColorMirrorTo: TColor;
  PenColor: TColor;
  GradB, GradU: TGDIPGradient;
  Rgn1, Rgn2: HRGN;
  R, R2: TRect;
  i, x, y: Integer;
  p: TPoint;
  BD: TButtonDisplay;
  sz: TSize;
  DoDraw: Boolean;
begin
  with Appearance do
  begin
    DoDraw := True;
    if (not Enabled) then
    begin
      if (1>0) {Transparent} then
      begin
        GradColor := ColorDisabled;
        GradColorTo := ColorDisabledTo;
        GradColorMirror := ColorMirrorDisabled;
        GradColorMirrorTo := ColorMirrorDisabledTo;
        PenColor := BorderColorDisabled;
        GradU := GradientDisabled;
        GradB := GradientMirrorDisabled;
      end
      else
      begin
      end;
    end
    else if FMouseDown or Down then
    begin
      GradColor := ColorDown;
      GradColorTo := ColorDownTo;
      GradColorMirror := ColorMirrorDown;
      GradColorMirrorTo := ColorMirrorDownTo;
      PenColor := BorderColorDown;
      GradU := GradientDown;
      GradB := GradientMirrorDown;
    end
    else if (False {checked}) then
    begin
      GradColor := ColorChecked;
      GradColorTo := ColorCheckedTo;
      GradColorMirror := ColorMirrorChecked;
      GradColorMirrorTo := ColorMirrorCheckedTo;
      PenColor := BorderColorChecked;
      GradU := GradientChecked;
      GradB := GradientMirrorChecked;
    end
    else //if State = absUp then
    begin
      if FMouseEnter then
      begin
        GradColor := ColorHot;
        GradColorTo := ColorHotTo;
        GradColorMirror := ColorMirrorHot;
        GradColorMirrorTo := ColorMirrorHotTo;
        PenColor := BorderColorHot;
        GradU := GradientHot;
        GradB := GradientMirrorHot;
      end
      else // Normal draw
      begin
        if (1>0) {Transparent} then
        begin
          GradColor := Color;
          GradColorTo := ColorTo;
          GradColorMirror := ColorMirror;
          GradColorMirrorTo := ColorMirrorTo;
          PenColor := BorderColor;
          GradU := Gradient;
          GradB := GradientMirror;
          DoDraw := False;
        end
        else
        begin
        end;
      end;
    end;

    {if (FMouseInControl or FMouseDown) and DropDownButton then
    begin
      if FInButton then
        BD := bdDropDown
      else
        BD := bdButton;
    end
    else }
      BD := bdNone;

    // do not use special border color for non standalone buttons in mouse hover/down state or checked buttons
    if (Position <> bpStandalone) and FMouseDown then
    begin
      PenColor := BorderColor;
    end;

    if (not Enabled) then
    begin
      GradColor := ColorDisabled;
      GradColorTo := ColorDisabledTo;
      GradColorMirror := ColorMirrorDisabled;
      GradColorMirrorTo := ColorMirrorDisabledTo;
      PenColor := BorderColorDisabled;
      GradU := GradientDisabled;
      GradB := GradientMirrorDisabled;
    end;

    //DrawVistaGradient(bmp.Canvas, ClientRect, GradColor, GradColorTo, GradColorMirror, GradColorMirrorTo,
      //PenColor, GradU, GradB, '', Canvas.Font, Enabled, False, aaNone, True);

    if DoDraw then
    begin
      sz := DrawVistaButton(Canvas,ClientRect,GradColor, GradColorTo, GradColorMirror, GradColorMirrorTo,
      PenColor, GradU, GradB, '', '', True{FDefaultCaptionDrawing}, Font, nil, -1, True, blGlyphLeft, False{FDropDownButton},
      False, Enabled, False, dpRight{DropDownPosition}, nil, aaNone, True{FDefaultPicDrawing}, nil, BD, Transparent and not (FMouseEnter or (FMouseDown)), FMouseEnter, Position, False{DropDownSplit}, True, False{FOverlappedText}, False{FWordWrap},
      False, True{FRounded}, False{FDropDownDirection}, 2{FSpacing}, StringTrimmingNone{FTrimming});
    end;

    //Canvas.CopyMode := cmSrcCopy;
    //Canvas.CopyRect(ClientRect, bmp.Canvas, ClientRect);

    x := Self.Width div 2;
    y := Self.Height div 2;
    Canvas.Pen.Color := BlendColor(clBlack, PenColor, 50);
    case ScrollArrow of
      saLeft:
      begin
        Canvas.Pixels[x-1, y] := Canvas.Pen.Color;
        Canvas.MoveTo(x, y-1);
        Canvas.LineTo(x, y+2);
        Canvas.MoveTo(x+1, y-2);
        Canvas.LineTo(x+1, y+3);
      end;
      saRight:
      begin
        case ArrowStyle of
          asSingle:
          begin
          Canvas.MoveTo(x-1, y-2);
          Canvas.LineTo(x-1, y+3);
          Canvas.MoveTo(x, y-1);
          Canvas.LineTo(x, y+2);
          Canvas.Pixels[x+1, y] := Canvas.Pen.Color;
          end;
          asDouble:
          begin
            R2 := ClientRect;
            R2.Top := R2.Top + 6;
            R2.Left := R2.Left + 1;
            DrawFlatDoubleArrows(R2);
          end;
        end;  
      end;
      saTop:
      begin
      end;
      saBottom:
      begin
        R2 := ClientRect;
        R2.Bottom := R2.Bottom - 4;
        R2.Left := R2.Left + 1;
        DrawFlatOptionsIndicator(R2);
      end;
    end;

    if not Assigned(Parent) then
      Exit;

    // transparent border pixels
                                             // TODO: consider false
    if (not FTransparent or FMouseEnter) and False then
    begin
      R := ClientRect;

      if Position <> bpMiddle then
      begin
        if (Position in [bpStandalone, bpLeft]) then
        begin
          rgn1 := CreateRectRgn(0, 0, 1, 1);
        end
        else
        begin
          rgn1 := CreateRectRgn(R.Right - 1, 0, R.Right, 1);
        end;

        if (Position in [bpStandalone]) then
        begin
          rgn2 := CreateRectRgn(R.Right - 1, 0, R.Right, 1);
          CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
          DeleteObject(rgn2);
        end;

        if (Position in [bpStandalone, bpLeft]) then
        begin
          rgn2 := CreateRectRgn(0, R.Bottom - 1, 1, R.Bottom);
          CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
          DeleteObject(rgn2);
        end;

        if (Position in [bpStandalone, bpRight]) then
        begin
          rgn2 := CreateRectRgn(R.Right - 1, R.Bottom - 1, R.Right, R.Bottom);
          CombineRgn(rgn1, rgn1, rgn2, RGN_OR);
          DeleteObject(rgn2);
        end;

        SelectClipRgn(Canvas.Handle, rgn1);

        i := SaveDC(Canvas.Handle);
        p := ClientOrigin;
        Windows.ScreenToClient(Parent.Handle, p);
        p.x := -p.x;
        p.y := -p.y;
        MoveWindowOrg(Canvas.Handle, p.x, p.y);

        SendMessage(Parent.Handle, WM_ERASEBKGND, Canvas.Handle, 0);

        // transparency ?
        SendMessage(Parent.Handle, WM_PAINT, Canvas.Handle, 0);
        if (Parent is TWinCtrl) then
          (Parent as TWinCtrl).PaintCtrls(Canvas.Handle, nil);
        RestoreDC(Canvas.Handle, i);

        SelectClipRgn(Canvas.Handle, 0);
        DeleteObject(rgn1);
      end;
    end;
  end;

end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.SetBounds(ALeft, ATop, AWidth,
  AHeight: Integer);
begin
  inherited;

end;

//------------------------------------------------------------------------------
procedure TAdvVistaButton.SetParent(AParent: TWinControl);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.Click;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.CMHintShow(var Message: TMessage);
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.SetAppearance(
  const Value: TGlowButtonAppearance);
begin
  FAppearance.Assign(Value);
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.AppearanceChanged(Sender: TObject);
begin
  invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.SetTransparent(const Value: Boolean);
begin
  FTransparent := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.SetButtonPosition(const Value: TButtonPosition);
begin
  FButtonPosition := Value;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.WMEraseBkGnd(var Message: TWMEraseBkGnd);
begin
  Message.Result := 1;
  inherited;
  Exit;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.SetScrollArrow(const Value: TScrollArrow);
begin
  FScrollArrow := Value;
  Invalidate;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.SetArrowStyle(const Value: TArrowStyle);
begin
  if (FArrowStyle <> Value) then
  begin
    FArrowStyle := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvVistaButton.SetDown(const Value: Boolean);
begin
  if (FDown <> Value) then
  begin
    FDown := Value;
    Invalidate;
  end;
end;

//------------------------------------------------------------------------------

{ TQATAppearance }

procedure TQATAppearance.Assign(Source: TPersistent);
begin
  if (Source is TQATAppearance) then
  begin
    FBorderColor := TQATAppearance(Source).BorderColor;
    FColor := TQATAppearance(Source).Color;
    FColorTo := TQATAppearance(Source).ColorTo;
    FFullSizeBorderColor := TQATAppearance(Source).FullSizeBorderColor;
    FFullSizeColor := TQATAppearance(Source).FullSizeColor;
    FullSizeColorTo := TQATAppearance(Source).FullSizeColorTo;
  end
  else
  begin
    inherited;
  end;
end;

//------------------------------------------------------------------------------

constructor TQATAppearance.Create;
begin
  inherited;
  FSteps := 64;
  FColor := clWhite;
  FColorTo := clSilver;
  FBorderColor := clGray;
  FFullSizeColor := $00E3B28D;
  FullSizeColorTo := $00E3B28D;
  FFullSizeColor := RGB(129, 159, 197);
end;

//------------------------------------------------------------------------------

destructor TQATAppearance.Destroy;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TQATAppearance.Changed;
begin
  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//------------------------------------------------------------------------------

procedure TQATAppearance.SetBorderColor(const Value: TColor);
begin
  if (FBorderColor <> Value) then
  begin
    FBorderColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TQATAppearance.SetColor(const Value: TColor);
begin
  if (FColor <> Value) then
  begin
    FColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TQATAppearance.SetColorTo(const Value: TColor);
begin
  if (FColorTo <> Value) then
  begin
    FColorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TQATAppearance.SetFullSizeBorderColor(const Value: TColor);
begin
  if (FFullSizeBorderColor <> Value) then
  begin
    FFullSizeBorderColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TQATAppearance.SetFullSizeColor(const Value: TColor);
begin
  if (FFullSizeColor <> Value) then
  begin
    FFullSizeColor := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TQATAppearance.SetFullSizeColorTo(const Value: TColor);
begin
  if (FFullSizeColorTo <> Value) then
  begin
    FFullSizeColorTo := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

procedure TQATAppearance.SetSteps(const Value: Integer);
begin
  if (FSteps <> Value) then
  begin
    FSteps := Value;
    Changed;
  end;
end;

//------------------------------------------------------------------------------

function IsAnyChildCtrlHasFocus(WinCtrl: TWinControl): Boolean;
var
  i: Integer;
  h: Hwnd;
  //a: array[0..255] of char;
begin
  Result := False;
  if not Assigned(WinCtrl) then
    Exit;

  h := GetFocus;
  i := 1;
  while (h <> 0) do
  begin
    if (h = WinCtrl.Handle) then
    begin
      Result := True;
      Break;
    end;
    h := GetParent(h);
    inc(i);
    if (i > 80) then
      Break;
  end;

  {GetClassName(GetFocus, a, 255);
  if (a <> '') then
  showmessage(a);
  }
  {Result := WinCtrl.Focused;
  if not Result then
  begin
    for i := 0 to WinCtrl.ControlCount - 1 do
    begin
      if (WinCtrl.Controls[i] is TWinControl) then
        Result := IsAnyChildCtrlHasFocus(TWinControl(WinCtrl.Controls[i]));
    end;
  end;}
end;

//------------------------------------------------------------------------------

{ TMinimizedRibbonWindow }

constructor TMinimizedRibbonWindow.Create(AOwner: TComponent);
begin
  inherited;
  FOwner := AOwner;
  FHideOnDeActivate := true;
  FHideTimer := TTimer.Create(self);
  FHideTimer.Interval := 1;
  FHideTimer.Enabled := false;
  FHideTimer.OnTimer := HideTimerOnTime;
  FAdvToolBarPager := nil;
  FAdvPage := nil;
  Width := 0;
  Height := 0;
end;

//------------------------------------------------------------------------------

constructor TMinimizedRibbonWindow.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
  inherited;
  FOwner := AOwner;
  FHideOnDeActivate := true;
  FHideTimer := TTimer.Create(self);
  FHideTimer.Interval := 1;
  FHideTimer.Enabled := false;
  FHideTimer.OnTimer := HideTimerOnTime;
  FAdvToolBarPager := nil;
  FAdvPage := nil;
  Width := 0;
  Height := 0;
end;

//------------------------------------------------------------------------------

procedure TMinimizedRibbonWindow.CreateParams(var Params: TCreateParams);
const
  CS_DROPSHADOW = $00020000;
begin
  inherited CreateParams(Params);
  // FF: D2005
  Params.Style := Params.Style or WS_POPUP;
  Params.Style := Params.Style - WS_CHILD;
  //Params.ExStyle := Params.ExStyle or WS_EX_NOPARENTNOTIFY;

  //Params.Style := Params.Style - WS_BORDER;
  {
  if (Win32Platform = VER_PLATFORM_WIN32_NT) and
     ((Win32MajorVersion > 5) or
      ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1))) then
    Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;

  Params.ExStyle := Params.ExStyle or WS_EX_TOPMOST; }
  if (Win32Platform = VER_PLATFORM_WIN32_NT) and
     ((Win32MajorVersion > 5) or
      ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1))) then
    Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;
end;

//------------------------------------------------------------------------------

destructor TMinimizedRibbonWindow.Destroy;
begin
  FHideTimer.Free;
  inherited;
end;

//------------------------------------------------------------------------------

function TMinimizedRibbonWindow.GetHideOnDeActivate: Boolean;
begin
  Result := CloseQuery and FHideOnDeActivate;
end;

//------------------------------------------------------------------------------

function TMinimizedRibbonWindow.GetParentWnd: HWnd;
var
  Last, P: HWnd;
begin
  P := GetParent((FOwner as TWinControl).Handle);
  Last := P;
  while P <> 0 do
  begin
    Last := P;
    P := GetParent(P);
  end;
  Result := Last;
end;

//------------------------------------------------------------------------------

procedure TMinimizedRibbonWindow.DoHide;
begin
  inherited;
end;

//------------------------------------------------------------------------------

procedure TMinimizedRibbonWindow.HideTimerOnTime(Sender: TObject);
begin
  Hide;
  FHideTimer.Enabled := false;
  if Assigned(AdvToolBarPager) then
     AdvToolBarPager.DestroyFloatingRibbon;
end;

//------------------------------------------------------------------------------

procedure TMinimizedRibbonWindow.Paint;
var
  R: TRect;
begin
  inherited;
  R := ClientRect;
  R := Rect(R.Left - 4, R.Top - 4, R.Right + 4, R.Bottom + 4);
  Canvas.Brush.Color := Color;
  Canvas.Pen.Color := Color;
  Canvas.Rectangle(R);
end;

//------------------------------------------------------------------------------

procedure TMinimizedRibbonWindow.SetWindowSize;
begin
  if Assigned(AdvToolBarPager) and Assigned(AdvPage) then
  begin
    Height := AdvPage.Height + 3;
    Width := AdvPage.Width + 3;
    AdvPage.Left := 2;
    AdvPage.Top := 0;
  end;
end;

//------------------------------------------------------------------------------

procedure TMinimizedRibbonWindow.WMActivate(var Message: TWMActivate);
var
  //rgn: THandle;
  //R: TRect;
  ATB: TAdvToolBar;
begin

  if not Visible then
  begin
    {if Assigned(AdvToolBar) then
      if Assigned(AdvToolBar.FSelfClone) and (AdvToolBar.FSelfClone.Visible) then
      begin
        AdvToolBar.FSelfClone.SetFocus;
      end; }
    Exit;
  end;

  if Message.Active = integer(False) then
  begin
    if HideOnDeActivate and Visible then
    begin
      {if Assigned(AdvToolBarPager) and (AdvToolBarPager.Visible) then
      begin
        // Do not close for GlowButtons when DroppedDown
      end
      else}
      if not (Assigned(AdvToolBarPager) and (GetFocus = AdvToolBarPager.Handle)) {and not IsAnyChildCtrlHasFocus(Self)} then
        FHideTimer.Enabled := true;
    end;
  end
  else if Assigned(AdvPage) then
  begin
    if Self.Visible then
    begin
      //AdvPage.SetFocus;
      //SendMessage(getParentWnd, WM_NCACTIVATE, 1, 0);
      ATB := AdvPage.GetFirstToolBar(True);
      if Assigned(ATB) then
        ATB.SetFocus;
    end;

    {R := ClientRect;
    rgn := CreateRoundRectRgn(0, 0, R.Right-R.Left, R.Bottom-R.Top, 4, 4);
    if rgn > 0 then
    begin
      try
        SetWindowRgn(Handle,rgn,true);
      finally
        DeleteObject(rgn);
      end;
    end;}
  end;
end;

//------------------------------------------------------------------------------

procedure TMinimizedRibbonWindow.WMNCHitTest(var Message: TWMNCHitTest);
{var
  pt: TPoint;}
begin
  inherited;
  {
  // Make the hint sizable
  pt := ScreenToClient(Point(Message.XPos, Message.YPos));

  if (pt.X > Width - 10) and (pt.Y > Height - 10) then
    message.Result := HTBOTTOMRIGHT}
end;

//------------------------------------------------------------------------------

{ TAdvToolBarForm }

procedure TAdvToolBarForm.AdjustClientRect(var Rect: TRect);
begin
  inherited AdjustClientRect(Rect);

  if not IsVista then
  begin
    Rect.Left := Rect.Left + 1;
    Rect.Top := Rect.Top + 1;
    Rect.Right := Rect.Right - 2;
    Rect.Bottom := Rect.Bottom - 2;
  end;
end;

//------------------------------------------------------------------------------

function TAdvToolBarForm.GetClientRect: TRect;
begin
  Result := inherited GetClientRect;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarForm.CreateParams(var Params: TCreateParams);
const
  CS_DROPSHADOW = $00020000;

begin
  inherited CreateParams(Params);

  BorderStyle := bsSingle;

  Params.Style := Params.Style and not WS_CAPTION or WS_POPUP or WS_SYSMENU;
//  if IsVista then
//    Params.Style := Params.Style - WS_THICKFRAME;

  if not (csDesigning in ComponentState) then
  begin
    if (Win32Platform = VER_PLATFORM_WIN32_NT) and
       ((Win32MajorVersion > 5) or
        ((Win32MajorVersion = 5) and (Win32MinorVersion >= 1))) then
      Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarForm.Paint;
var
  i: integer;
  clr: TColor;
begin
  inherited;

  clr := clGray;

  for i := 0 to ControlCount - 1 do
  begin
    if Controls[i] is TAdvToolBarPager then
    begin
      with Controls[i] as TAdvToolBarPager do
      begin
        clr := FCurrentToolBarStyler.CaptionAppearance.CaptionTextColor;
      end;
    end;

    if clr = clWhite then
      clr := clBlack;

  end;

  Canvas.Brush.Style := bsClear;
  Canvas.Pen.Color := clr;
  Canvas.Pen.Width := 1;
  Canvas.RoundRect(0,0,Width - 7, Height -7,18,18);
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarForm.WMGetMinMaxInfo(var Msg: TMessage);
var
  info: ^TMinMaxInfo;
  rc: TRect;
  mi: TMonitorInfo;
  dx, dy: integer;
begin
  inherited;

  if not (csDesigning in ComponentState) then
  begin
    FillChar(mi, SizeOf(mi), 0); mi.cbSize := SizeOf(mi);
    if GetMonitorInfo(MonitorFromWindow(Handle, MONITOR_DEFAULTTONEAREST), @mi) then
    begin
      dx := 0;
      dy := 0;
      rc := mi.rcWork;
      info := pointer(Msg.LParam);

      // compensate for clipregion
      if not IsVista then
      begin
        dx := 3;
        dy := 3;
      end;

      info^.ptMaxPosition.X := mi.rcWork.Left-mi.rcMonitor.Left - dx;
      info^.ptMaxPosition.Y := mi.rcWork.Top-mi.rcMonitor.Top - dy;
      info^.ptMaxSize.X := rc.Right - rc.Left + 2 * dx;
      info^.ptMaxSize.Y := rc.Bottom - rc.Top + 2 * dy;
    end;
    {
    SystemParametersInfo(SPI_GETWORKAREA, 0, @rc, 0);
    info := pointer(Msg.LParam);
    info^.ptMaxPosition.X := rc.Left - 1;
    info^.ptMaxPosition.Y := rc.Top - 1;
    info^.ptMaxSize.x := GetSystemMetrics(SM_CXMAXIMIZED) - GetSystemMetrics(SM_CXSIZEFRAME) * 2 + 4;
    info^.ptMaxSize.y := GetSystemMetrics(SM_CYMAXIMIZED) - GetSystemMetrics(SM_CYSIZEFRAME) * 2 + 4;
    }
  end;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarForm.WMNCHitTest(var Message: TWMNCHitTest);
var
  pt: TPoint;
begin
  inherited;

  if not (csDesigning in ComponentState) and (WindowState = wsNormal) then
  begin
    pt := ScreenToClient(Point(message.Xpos, message.YPos));

    //outputdebugstring(pchar(inttostr(pt.x)+':'+inttostr(pt.y)+':'+inttostr(width)+':'+inttostr(height)));
    inherited;
    //Message.Result := HTCAPTION;

    if (pt.Y < 3) then
      Message.Result := HTTOP;

    if (pt.X < 3) then
      Message.Result := HTLEFT;

    if (pt.X > Width - 12) then
      Message.Result := HTRIGHT;

    if (pt.Y > Height - 12) then
      Message.Result := HTBOTTOM;

    if (pt.X > Width - 20) and (pt.Y > Height - 20)  then
    begin
      Message.Result := HTBOTTOMRIGHT;
    end;

    if (pt.X < 20) and (pt.Y < 20)  then
      Message.Result := HTTOPLEFT;

    if (pt.X > Width - 20) and (pt.Y < 20)  then
    begin
      Message.Result := HTTOPRIGHT;
    end;

    if (pt.X < 20) and (pt.Y > Height - 20)  then
      Message.Result := HTBOTTOMLEFT;

  end
  else
    inherited;
end;

//------------------------------------------------------------------------------

procedure TAdvToolBarForm.WMSize(var Message: TWMSize);
var
  hrgn: thandle;
  i: integer;

begin
  // Hide Pager if its Form's width < 300 otherwise unhide
  if not (csDesigning in ComponentState) then
  begin
    for i := 0 to ControlCount - 1 do
    begin
      if Controls[i] is TAdvToolBarPager then
      begin
        if (Self.Width < 300) and (not TAdvToolBarPager(Controls[i]).HideState) then
          TAdvToolBarPager(Controls[i]).HideState := True
        else if (Self.Width > 300) and (TAdvToolBarPager(Controls[i]).HideState) then
          TAdvToolBarPager(Controls[i]).HideState := False;

        break;
      end;  
    end;
  end;

  if not (csDesigning in ComponentState) and not IsVista then
  begin
    //adjust toolbar pager properties
    for i := 0 to ControlCount - 1 do
      if Controls[i] is TAdvToolBarPager then
        with Controls[i] as TAdvToolBarPager do
        begin
          CanMove := Message.SizeType = SIZE_RESTORED;
          break;
        end;
    //set window clipping region

  //  if (Message.SizeType = SIZE_RESTORED) then
      hrgn := CreateRoundRectRgn(3,3,Width - 3,Height - 3,18,18);
  //  else
  //    hrgn := 0;
    SetWindowRgn(handle, hrgn, Visible);
    //Invalidate;
  end;
  inherited;
end;



{$IFDEF FREEWARE}
function Scramble(s:string): string;
var
  r:string;
  i: integer;
  c: char;
  b: byte;
begin
  r := '';
  for i := 1 to length(s) do
  begin
    b := ord(s[i]);
    b := (b and $E0) + ((b and $1F) xor 5);
    c := chr(b);
    r := r + c;
  end;
  Result := r;
end;
{$ENDIF}

initialization
{$IFDEF FREEWARE}
   if  (FindWindow(PChar(Scramble('QDuuilfdqljk')), nil) = 0) OR
       (FindWindow(PChar(Scramble('QDuuGplia`w')), nil) = 0) then
   begin
     MessageBox(0,PChar(Scramble('Duuilfdqljk%pv`v%qwldi%s`wvljk%jc%QHV%vjcqrdw`%fjhujk`kqv+')+#13#10+Scramble('Fjkqdfq%QHV%vjcqrdw`%mqqu?**rrr+qhvvjcqrdw`+fjh%cjw%sdila%ilf`kvlkb+')),PChar(Scramble('Rdwklkb')),MB_OK);
   end;
{$ENDIF}

  WM_TBCOMPACTWINHIDE := RegisterWindowMessage('TBCompactWinHide');

end.
