//+------------------------------------------------------------------+
//|                                           GotobiCalendar(drag).mq5|
//|  Monthly calendar of the Gotobi days, drawn on the chart.        |
//|  Drag it by the header bar. The - button minimizes, + maximizes, |
//|  and the red x button removes it from the chart.                 |
//|  Gotobi days are black. < and > show the previous or next month. |
//|  Information only: it does not trade.                            |
//+------------------------------------------------------------------+
#property copyright "Creyes EA"
#property link      "https://www.mql5.com/en/users/creyes_88"
#property version   "1.22"
#property description "Monthly calendar of the Gotobi days, drawn on the chart. Draggable, minimizable and closable."
#property indicator_chart_window
#property indicator_plots 0

//+------------------------------------------------------------------+
//| Gotobi day logic (formerly GotobiDays.mqh, merged here)          |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Date at 00:00 (time of day removed)                              |
//+------------------------------------------------------------------+
datetime GotobiDateOnly(const datetime t)
  {
   MqlDateTime s;
   TimeToStruct(t, s);
   s.hour = 0;
   s.min = 0;
   s.sec = 0;
   return StructToTime(s);
  }

//+------------------------------------------------------------------+
//| True if the date is in the holiday list (time of day ignored)    |
//+------------------------------------------------------------------+
bool GotobiIsHoliday(const datetime t, const datetime &holidays[])
  {
   datetime d = GotobiDateOnly(t);
   for(int i = 0; i < ArraySize(holidays); i++)
      if(GotobiDateOnly(holidays[i]) == d)
         return true;
   return false;
  }

//+------------------------------------------------------------------+
//| True for Monday to Friday when the date is not a holiday         |
//+------------------------------------------------------------------+
bool GotobiIsBusinessDay(const datetime t, const datetime &holidays[])
  {
   MqlDateTime s;
   TimeToStruct(t, s);
   if(s.day_of_week == 0 || s.day_of_week == 6)
      return false;
   return !GotobiIsHoliday(t, holidays);
  }

//+------------------------------------------------------------------+
//| Last calendar day of the month of t (at 00:00)                   |
//+------------------------------------------------------------------+
datetime GotobiLastDayOfMonth(const datetime t)
  {
   MqlDateTime s;
   TimeToStruct(t, s);
   s.day = 1;
   s.hour = 0;
   s.min = 0;
   s.sec = 0;
   if(++s.mon > 12)
     {
      s.mon = 1;
      s.year++;
     }
   return StructToTime(s) - 86400;   // day 1 of next month minus one day
  }

//+------------------------------------------------------------------+
//| Move back to the previous business day if needed                 |
//+------------------------------------------------------------------+
datetime GotobiAdjust(datetime d, const datetime &holidays[])
  {
   d = GotobiDateOnly(d);
   int guard = 0;
   while(!GotobiIsBusinessDay(d, holidays) && guard++ < 15)
      d -= 86400;
   return d;
  }

//+------------------------------------------------------------------+
//| The Gotobi days of the month of t, already adjusted (ascending)  |
//+------------------------------------------------------------------+
int GotobiDaysOfMonth(const datetime t, const datetime &holidays[], datetime &out[])
  {
   MqlDateTime s;
   TimeToStruct(t, s);
//--- nominal days; the sixth Gotobi day is the last day of the month
   int nominal[5] = {5, 10, 15, 20, 25};
   ArrayResize(out, 0);
   for(int i = 0; i < 6; i++)
     {
      datetime d;
      if(i < 5)
        {
         MqlDateTime n = s;
         n.day = nominal[i];
         n.hour = 0;
         n.min = 0;
         n.sec = 0;
         d = StructToTime(n);
        }
      else
         d = GotobiLastDayOfMonth(t);
      d = GotobiAdjust(d, holidays);
      int k = ArraySize(out);
      if(k > 0 && out[k - 1] == d)
         continue;   // two nominal days moved onto the same business day
      ArrayResize(out, k + 1);
      out[k] = d;
     }
   return ArraySize(out);
  }

//+------------------------------------------------------------------+
//| Is the date of t a Gotobi day?                                   |
//+------------------------------------------------------------------+
bool IsGotobiDay(const datetime t, const datetime &holidays[])
  {
   datetime days[];
   GotobiDaysOfMonth(t, holidays, days);
   datetime d = GotobiDateOnly(t);
   for(int i = 0; i < ArraySize(days); i++)
      if(days[i] == d)
         return true;
   return false;
  }

//+------------------------------------------------------------------+
//| First Gotobi day on or after the date of from (0 if none)        |
//+------------------------------------------------------------------+
datetime NextGotobiDay(const datetime from, const datetime &holidays[])
  {
   datetime d = GotobiDateOnly(from);
   for(int i = 0; i < 70; i++, d += 86400)
      if(IsGotobiDay(d, holidays))
         return d;
   return 0;
  }

input string InpHolidays     = "";                 // Holidays to skip, format YYYY.MM.DD separated by ; (optional)
input int    InpX            = 10;                 // Start distance from left edge (pixels)
input int    InpY            = 30;                 // Start distance from top edge (pixels)
input int    InpCellW        = 32;                 // Day box width (pixels)
input int    InpCellH        = 19;                 // Day box height (pixels)
input color  InpBgColor      = clrWhite;           // Background color
input color  InpTextColor    = clrBlack;           // Normal text color
input color  InpGotobiColor  = clrBlack;           // Gotobi day box color
input color  InpWeekendColor = clrGray;            // Weekend text color
input color  InpBorderColor  = clrGray;            // Day box border color
input color  InpHeaderColor  = clrDarkSlateGray;   // Header bar color
input bool   InpDraggable    = true;               // Draggable by the header bar
input string UniqueID        = "GCALDB";           // Indicator unique ID

const string gPrefix   = "GCAL_";                  // calendar objects (moved together when dragged)
const string gBtnMin   = "GCALBTN_MIN";            // minimize button
const string gBtnMax   = "GCALBTN_MAX";            // maximize button
const string gBtnClose = "GCALBTN_CLOSE";          // close button
const string gBtnPrev  = "GCALBTN_PREV";           // previous month button
const string gBtnNext  = "GCALBTN_NEXT";           // next month button
const int    HDR_H     = 22;                       // header bar height
const int    BTN_SZ    = 16;                       // header button size
const int    PAD       = 12;                       // inner padding
const int    GAP       = 6;                        // gap between day boxes

datetime gHolidays[];
int      gMonthKey = -1;
datetime gViewT = 0;                              // first day (00:00) of the month shown
bool     gFollow = true;                          // true: follow the current month automatically
int      gNeedW = 0;                              // header width needed (set by DrawCalendar)
int      gTitleW = 0;                             // title text width (set by DrawCalendar)
int      gOffX = 0;                               // left offset of the day grid inside the panel
int      gBodyH = 0;                               // body height (0 while minimized)
int      gX = 10, gY = 30;                         // panel top-left corner (pixels)
bool     gMinimized = false;

bool gDragging = false, gDidDrag = false, gMouseRefHeld = false, gOrigMouseScroll = true;
int  gDragMouseX = 0, gDragMouseY = 0, gDragStartX = 0, gDragStartY = 0;
int  gPrevMouseState = 0;

//+------------------------------------------------------------------+
//| Read the holidays input into an array of dates                   |
//+------------------------------------------------------------------+
int LoadHolidays(datetime &holidays[])
  {
   ArrayResize(holidays, 0);
   string parts[];
   int n = StringSplit(InpHolidays, ';', parts);
   for(int i = 0; i < n; i++)
     {
      StringTrimLeft(parts[i]);
      StringTrimRight(parts[i]);
      if(parts[i] == "")
         continue;
      datetime d = StringToTime(parts[i]);
      if(d == 0)
         continue;
      int k = ArraySize(holidays);
      ArrayResize(holidays, k + 1);
      holidays[k] = d;
     }
   return ArraySize(holidays);
  }

//+------------------------------------------------------------------+
//| Helpers for text                                                 |
//+------------------------------------------------------------------+
string MonthName(const int m)
  {
   string names[] = {"January", "February", "March", "April", "May", "June",
                     "July", "August", "September", "October", "November", "December"};
   return names[m - 1];
  }

int GridW()
  {
   return 7 * InpCellW + 6 * GAP + 2 * PAD;
  }

int PanelW()
  {
   return MathMax(GridW(), gNeedW);
  }

// Width of a title in the header font (9 pt bold)
int TitleWidth(const string text)
  {
   TextSetFont("Arial Bold", -90);
   uint w = 0, h = 0;
   TextGetSize(text, w, h);
   return (int)w;
  }

int PanelH()
  {
   return HDR_H + gBodyH;
  }

//+------------------------------------------------------------------+
//| Drawing helpers                                                  |
//+------------------------------------------------------------------+
void MakeRect(const string name, const int x, const int y, const int w, const int h,
              const color fill, const color border)
  {
   ObjectCreate(0, name, OBJ_RECTANGLE_LABEL, 0, 0, 0);
   ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, name, OBJPROP_XSIZE, w);
   ObjectSetInteger(0, name, OBJPROP_YSIZE, h);
   ObjectSetInteger(0, name, OBJPROP_BGCOLOR, fill);
   ObjectSetInteger(0, name, OBJPROP_COLOR, border);
   ObjectSetInteger(0, name, OBJPROP_BORDER_TYPE, BORDER_FLAT);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, name, OBJPROP_BACK, false);
  }

void MakeText(const string name, const int x, const int y, const string text, const color clr,
              const int size, const bool bold, const ENUM_ANCHOR_POINT anchor)
  {
   ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
   ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, anchor);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetString(0, name, OBJPROP_FONT, bold ? "Arial Bold" : "Arial");
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, size);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetString(0, name, OBJPROP_TEXT, text);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, name, OBJPROP_BACK, false);
  }

// Header button (OBJ_BUTTON), positioned later by PlaceButtons()
void CreateButton(const string name, const string text, const string tip, const color bg)
  {
   ObjectDelete(0, name);
   ObjectCreate(0, name, OBJ_BUTTON, 0, 0, 0);
   ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, name, OBJPROP_XSIZE, BTN_SZ);
   ObjectSetInteger(0, name, OBJPROP_YSIZE, BTN_SZ);
   ObjectSetInteger(0, name, OBJPROP_BGCOLOR, bg);
   ObjectSetInteger(0, name, OBJPROP_BORDER_COLOR, bg);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clrWhite);
   ObjectSetString(0, name, OBJPROP_FONT, "Arial Bold");
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 8);
   ObjectSetString(0, name, OBJPROP_TEXT, text);
   ObjectSetString(0, name, OBJPROP_TOOLTIP, tip);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_STATE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
   ObjectSetInteger(0, name, OBJPROP_BACK, false);
  }

void CreateButtons()
  {
   CreateButton(gBtnMin, "-", "Minimize", clrDimGray);
   CreateButton(gBtnMax, "+", "Maximize", clrDimGray);
   CreateButton(gBtnClose, "x", "Close", clrRed);
   CreateButton(gBtnPrev, "<", "Previous month", clrDimGray);
   CreateButton(gBtnNext, ">", "Next month", clrDimGray);
  }

// Keep the three header buttons at the right end of the header bar
void PlaceButtons()
  {
   int closeX = gX + PanelW() - BTN_SZ - 4;
   int maxX = closeX - BTN_SZ - 3;
   int minX = maxX - BTN_SZ - 3;
   int y = gY + (HDR_H - BTN_SZ) / 2;
   ObjectSetInteger(0, gBtnClose, OBJPROP_XDISTANCE, closeX);
   ObjectSetInteger(0, gBtnClose, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, gBtnMax, OBJPROP_XDISTANCE, maxX);
   ObjectSetInteger(0, gBtnMax, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, gBtnMin, OBJPROP_XDISTANCE, minX);
   ObjectSetInteger(0, gBtnMin, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, gBtnPrev, OBJPROP_XDISTANCE, gX + 6);
   ObjectSetInteger(0, gBtnPrev, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, gBtnNext, OBJPROP_XDISTANCE, gX + 26 + gTitleW + 4);
   ObjectSetInteger(0, gBtnNext, OBJPROP_YDISTANCE, y);
  }

// Shift every calendar object by (dx, dy) without redrawing
void MoveCalendar(const int dx, const int dy)
  {
   int total = ObjectsTotal(0, -1, -1);
   for(int i = 0; i < total; i++)
     {
      string name = ObjectName(0, i, -1, -1);
      if(StringFind(name, gPrefix) != 0)
         continue;
      ObjectSetInteger(0, name, OBJPROP_XDISTANCE, ObjectGetInteger(0, name, OBJPROP_XDISTANCE) + dx);
      ObjectSetInteger(0, name, OBJPROP_YDISTANCE, ObjectGetInteger(0, name, OBJPROP_YDISTANCE) + dy);
     }
   PlaceButtons();
  }

//+------------------------------------------------------------------+
//| Draw the panel of the current month at (gX, gY)                  |
//+------------------------------------------------------------------+
void DrawCalendar()
  {
   ObjectsDeleteAll(0, gPrefix);

   datetime now = gViewT;             // first day of the month shown
   MqlDateTime s;
   TimeToStruct(now, s);

   // Gotobi days of this month
   datetime gotobi[];
   GotobiDaysOfMonth(now, gHolidays, gotobi);

   // weekday of the 1st, Sunday = column 0
   MqlDateTime f = s;
   f.day = 1;
   f.hour = 0;
   f.min = 0;
   f.sec = 0;
   MqlDateTime fs;
   TimeToStruct(StructToTime(f), fs);
   int offset = fs.day_of_week;        // 0 = Sunday
   MqlDateTime ls;
   TimeToStruct(GotobiLastDayOfMonth(now), ls);
   int days = ls.day;
   int rows = (offset + days + 6) / 7;

   // layout (pixels, relative to the body top)
   const int W = InpCellW, H = InpCellH;
   const int hdrY = 4;                // weekday labels: space above
   const int gridY = hdrY + 16;       // day boxes: space below the labels
   const int gridBottom = gridY + rows * H + (rows - 1) * GAP;
   const int bodyH = gridBottom + PAD;

   // header: [<] title [>] ... [-][+][x], widened if the title needs more room
   string title = StringFormat("%s %d", MonthName(s.mon), s.year);
   gTitleW = TitleWidth(title);
   gNeedW = gTitleW + 116;
   gOffX = (PanelW() - GridW()) / 2; // center the day grid under the header
   int panelW = PanelW();
   int bodyY = gY + HDR_H;
   gBodyH = gMinimized ? 0 : bodyH;

   // header bar (always visible) with the month title
   MakeRect(gPrefix + "HDR", gX, gY, panelW, HDR_H, gDragging ? clrSteelBlue : InpHeaderColor, InpHeaderColor);
   MakeText(gPrefix + "TITLE", gX + 26, gY + HDR_H / 2, title, clrWhite, 9, true, ANCHOR_LEFT);

   if(!gMinimized)
     {
      // background
      MakeRect(gPrefix + "BG", gX, bodyY, panelW, bodyH, InpBgColor, InpBgColor);

      // weekday headers
      string wd[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
      for(int c = 0; c < 7; c++)
        {
         int cx = gX + gOffX + PAD + c * (W + GAP);
         MakeText(gPrefix + "HDR" + IntegerToString(c), cx + W / 2, bodyY + hdrY, wd[c],
                  InpTextColor, 8, true, ANCHOR_UPPER);
        }

      // day boxes
      for(int d = 1; d <= days; d++)
        {
         int idx = offset + d - 1;
         int col = idx % 7;
         int row = idx / 7;
         int cx = gX + gOffX + PAD + col * (W + GAP);
         int cy = bodyY + gridY + row * (H + GAP);

         MqlDateTime dd = s;
         dd.day = d;
         dd.hour = 0;
         dd.min = 0;
         dd.sec = 0;
         datetime dt = StructToTime(dd);

         bool isG = false;
         for(int i = 0; i < ArraySize(gotobi); i++)
            if(gotobi[i] == dt)
              {
               isG = true;
               break;
              }

         string name = gPrefix + "D" + IntegerToString(d);
         string txt = IntegerToString(d);
         if(isG)
           {
            MakeRect(name + "R", cx, cy, W, H, InpGotobiColor, InpGotobiColor);
            MakeText(name, cx + W / 2, cy + H / 2, txt, clrWhite, 8, true, ANCHOR_CENTER);
           }
         else
           {
            MakeRect(name + "R", cx, cy, W, H, InpBgColor, InpBorderColor);
            color tc = (col == 0 || col == 6) ? InpWeekendColor : InpTextColor;
            MakeText(name, cx + W / 2, cy + H / 2, txt, tc, 8, true, ANCHOR_CENTER);
           }
        }
     }

   CreateButtons();                   // re-create so the buttons draw above the panel
   PlaceButtons();
   ChartRedraw(0);
  }

//+------------------------------------------------------------------+
//| Redraw only when the month changes                               |
//+------------------------------------------------------------------+
// First day (00:00) of year y, month m
datetime MonthStart(const int y, const int m)
  {
   MqlDateTime s;
   ZeroMemory(s);
   s.year = y;
   s.mon = m;
   s.day = 1;
   return StructToTime(s);
  }

// Show the month delta months away (-1 previous, +1 next)
void ShiftMonth(const int delta)
  {
   MqlDateTime s;
   TimeToStruct(gViewT, s);
   int idx = s.year * 12 + (s.mon - 1) + delta;
   int vy = idx / 12;
   int vm = idx % 12 + 1;
   MqlDateTime c;
   TimeToStruct(TimeCurrent(), c);
   gFollow = (c.year == vy && c.mon == vm);   // back on the current month: follow it again
   gMonthKey = vy * 100 + vm;
   gViewT = MonthStart(vy, vm);
   DrawCalendar();
  }

void Refresh()
  {
   if(!gFollow)
      return;                         // the user is browsing another month
   MqlDateTime s;
   TimeToStruct(TimeCurrent(), s);
   int key = s.year * 100 + s.mon;
   if(key != gMonthKey)
     {
      gMonthKey = key;
      gViewT = MonthStart(s.year, s.mon);
      DrawCalendar();
     }
  }

//+------------------------------------------------------------------+
//| Drag support                                                     |
//+------------------------------------------------------------------+
// Saved position and minimized state, keyed by chart and UniqueID
string PosGvPrefix()
  {
   return StringFormat("GCALDRAG_%I64d_%s_", ChartID(), UniqueID);
  }

void SavePanelPosition()
  {
   string p = PosGvPrefix();
   GlobalVariableSet(p + "X", gX);
   GlobalVariableSet(p + "Y", gY);
   GlobalVariableSet(p + "InitX", InpX);
   GlobalVariableSet(p + "InitY", InpY);
   GlobalVariableSet(p + "Min", gMinimized ? 1 : 0);
  }

void ClearPanelPosition()
  {
   string p = PosGvPrefix();
   GlobalVariableDel(p + "X");
   GlobalVariableDel(p + "Y");
   GlobalVariableDel(p + "InitX");
   GlobalVariableDel(p + "InitY");
   GlobalVariableDel(p + "Min");
  }

void LoadPanelPosition()
  {
   gX = InpX;
   gY = InpY;
   gMinimized = false;
   if(!InpDraggable)
      return;
   string p = PosGvPrefix();
   if(GlobalVariableCheck(p + "X") && GlobalVariableCheck(p + "Y") &&
      GlobalVariableCheck(p + "InitX") && GlobalVariableCheck(p + "InitY") &&
      (int)GlobalVariableGet(p + "InitX") == InpX && (int)GlobalVariableGet(p + "InitY") == InpY)
     {
      gX = (int)GlobalVariableGet(p + "X");
      gY = (int)GlobalVariableGet(p + "Y");
      gMinimized = (GlobalVariableCheck(p + "Min") && GlobalVariableGet(p + "Min") != 0);
     }
  }

// Move the panel to (nx, ny), kept inside the chart area
void DragTo(const int nx, const int ny)
  {
   int ox = gX, oy = gY;
   int cw = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
   int ch = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);
   gX = MathMax(0, MathMin(nx, cw - PanelW()));
   gY = MathMax(0, MathMin(ny, ch - PanelH()));
   MoveCalendar(gX - ox, gY - oy);
  }

// Shared mouse-move reference count (same key as RSI(drag_board))
string MouseMoveRefKey()
  {
   return StringFormat("MT5_DRAG_MM_REF_%I64d", ChartID());
  }

int CountAllChartIndicators()
  {
   int total = 0;
   int windows = (int)ChartGetInteger(0, CHART_WINDOWS_TOTAL);
   for(int w = 0; w < windows; w++)
      total += ChartIndicatorsTotal(0, w);
   return total;
  }

void AcquireMouseMoveRef()
  {
   if(!InpDraggable || gMouseRefHeld) return;
   ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, true);
   string refKey = MouseMoveRefKey();
   int curRef = GlobalVariableCheck(refKey) ? MathMax(0, (int)GlobalVariableGet(refKey)) : 0;
   GlobalVariableSet(refKey, (double)(curRef + 1));
   GlobalVariableTemp(refKey);
   gMouseRefHeld = true;
  }

void ReleaseMouseMoveRef(const int reason)
  {
   if(!gMouseRefHeld) return;
   gMouseRefHeld = false;
   string refKey = MouseMoveRefKey();
   int nextRef = GlobalVariableCheck(refKey) ? MathMax(0, (int)GlobalVariableGet(refKey) - 1) : 0;
   if(nextRef > 0)
     {
      GlobalVariableSet(refKey, (double)nextRef);
      GlobalVariableTemp(refKey);
     }
   else
     {
      GlobalVariableDel(refKey);
      if(reason == REASON_REMOVE && CountAllChartIndicators() <= 1)
         ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, false);
     }
  }

void EnsureMouseMoveEnabled()
  {
   if(!InpDraggable) return;
   string refKey = MouseMoveRefKey();
   if(GlobalVariableCheck(refKey) && (int)GlobalVariableGet(refKey) > 0)
      ChartSetInteger(0, CHART_EVENT_MOUSE_MOVE, true);
  }

// Drag the panel by its header bar; a press that moves is not a button click
void HandleDragMouse(const int mouseX, const int mouseY, const int mouseState)
  {
   bool leftDown = ((mouseState & 1) != 0);
   bool prevDown = ((gPrevMouseState & 1) != 0);
   gPrevMouseState = mouseState;

   bool overHeader = (mouseX >= gX && mouseX < gX + PanelW() && mouseY >= gY && mouseY < gY + HDR_H);

   if(!prevDown && leftDown && overHeader)
     {
      gDragging = true;
      gDidDrag = false;
      gDragMouseX = mouseX;
      gDragMouseY = mouseY;
      gDragStartX = gX;
      gDragStartY = gY;
      gOrigMouseScroll = (bool)ChartGetInteger(0, CHART_MOUSE_SCROLL);
      ChartSetInteger(0, CHART_MOUSE_SCROLL, false);
      ObjectSetInteger(0, gPrefix + "HDR", OBJPROP_BGCOLOR, clrSteelBlue);
      ChartRedraw(0);
     }
   else if(gDragging && leftDown)
     {
      int dx = mouseX - gDragMouseX;
      int dy = mouseY - gDragMouseY;
      if(MathAbs(dx) > 2 || MathAbs(dy) > 2)
         gDidDrag = true;
      DragTo(gDragStartX + dx, gDragStartY + dy);
      ChartRedraw(0);
     }
   else if(gDragging && !leftDown)
     {
      gDragging = false;
      ChartSetInteger(0, CHART_MOUSE_SCROLL, gOrigMouseScroll);
      ObjectSetInteger(0, gPrefix + "HDR", OBJPROP_BGCOLOR, InpHeaderColor);
      SavePanelPosition();
      ChartRedraw(0);
     }
  }

// Remove this indicator from the chart (runs OnDeinit with REASON_REMOVE)
void RemoveSelf()
  {
   ChartIndicatorDelete(0, 0, UniqueID);
  }

//+------------------------------------------------------------------+
//| Indicator events                                                 |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorSetString(INDICATOR_SHORTNAME, UniqueID);
   LoadHolidays(gHolidays);
   LoadPanelPosition();
   CreateButtons();
   AcquireMouseMoveRef();
   gMonthKey = -1;
   Refresh();
   DragTo(gX, gY);                    // keep the saved position on screen
   EventSetTimer(2);
   return INIT_SUCCEEDED;
  }

void OnDeinit(const int reason)
  {
   EventKillTimer();
   ReleaseMouseMoveRef(reason);
   if(gDragging)
     {
      gDragging = false;
      ChartSetInteger(0, CHART_MOUSE_SCROLL, gOrigMouseScroll);
     }
   ObjectDelete(0, gBtnMin);
   ObjectDelete(0, gBtnMax);
   ObjectDelete(0, gBtnClose);
   ObjectDelete(0, gBtnPrev);
   ObjectDelete(0, gBtnNext);
   ObjectsDeleteAll(0, gPrefix);
   if(reason == REASON_REMOVE)
      ClearPanelPosition();
   ChartRedraw(0);
  }

void OnTimer()
  {
   Refresh();
   if(InpDraggable) EnsureMouseMoveEnabled();
  }

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
  {
   if(id == CHARTEVENT_MOUSE_MOVE)
     {
      if(InpDraggable)
         HandleDragMouse((int)lparam, (int)dparam, (int)StringToInteger(sparam));
      return;
     }
   if(id != CHARTEVENT_OBJECT_CLICK)
      return;

   if(sparam == gBtnClose)
     {
      ObjectSetInteger(0, gBtnClose, OBJPROP_STATE, false);
      if(!gDidDrag)
         RemoveSelf();
      return;
     }

   if(sparam == gBtnPrev || sparam == gBtnNext)
     {
      ObjectSetInteger(0, sparam, OBJPROP_STATE, false);
      if(gDidDrag)
        {
         gDidDrag = false;
         return;
        }
      ShiftMonth(sparam == gBtnPrev ? -1 : 1);
      return;
     }

   if(sparam == gBtnMin || sparam == gBtnMax)
     {
      ObjectSetInteger(0, sparam, OBJPROP_STATE, false);
      if(gDidDrag)
        {
         gDidDrag = false;
         return;
        }
      bool wantMin = (sparam == gBtnMin);
      if(gMinimized == wantMin)
         return;                       // already in that state
      gMinimized = wantMin;
      DrawCalendar();
      SavePanelPosition();
      ChartRedraw(0);
     }
  }

int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[],
                const double &open[], const double &high[], const double &low[],
                const double &close[], const long &tick_volume[], const long &volume[],
                const int &spread[])
  {
   Refresh();
   return rates_total;
  }
//+------------------------------------------------------------------+
