;+
; PROJECT
;           SOLARB EIS
;
; NAME
;           EIS_TIMELINE_PLOT_GUI__DEFINE
;
; PURPOSE
;           eis_timeline_plot_gui class definition.
;
; NOTES
;           This routine displays the timeline plan as a graphic.
;
; CATEGORY
;           EIS timeline planning
;
; WRITTEN
;           John A Rainne RAL
;
; VERSION
;           v0.1 JAR 7-Jan-2007
;               Added a parameter "replot" that is set to 1 when image_tool
;               sends back pointing info to the PT. If this is found here,
;               then I redraw the timeline plot (and reset "replot=0")
;           v0.2 JAR 26-Mar-2007
;               Added check for recursive/default studies - plot them as blue!
;           v0.3 JAR 18-Apr-2007
;               Included provision for plotting day & ngt periods. However,
;               this hasn't been implemented yet.
;           v0.4 JAR 24-Apr-2007
;               Modified plotting of SAA, HLA and NGT events.
;           v0.5 JAR 15-Jun-2007
;               Removed all CPT displaying code. This is as a consequence
;               of having all_event type time text-boxes in CPT gui.
;           v0.6 JAR 23-11-2007
;               Now reading J-Side files after reading database (see
;               eis_mk_plan_gui::readPlanFromDatabase) - instead of doing
;               it here on the fly every time.
;           v0.7 JAR 28-Nov-2007
;               Catch cursor as it enters plot window (using drawID
;               widget's TRACKING_EVENTS keyword) and re-draw plot axes
;               on a temporary pixmap - this maintains the coordinate
;               systems (remember those 'orrible things image_tool
;               used to do with my lovely plot!)
;          v0.8 JAR 17-Dec-2007
;              Refresh DR GUI after selecting a timeline entry
;          v0.9 JAR 6-Feb-2008
;              There are occasions on which the J-Side re-point file doesn't
;              actually contain any ORe lines. In which case I now check
;              which members of the *rpev array are structures
;              (ie N_TAGS > 0).
;          v1.0 JAR 27-Mar-2008
;              1. Added facility to display EIS Event-triggered studies in
;                 "ENG & R/T" row
;              2. Added context menu functionality if CPT GUI is invoked.
;                 Use can now set CPT start and stop times using this menu
;          v1.1 JAR 19-May-2008
;              Added context events list to allow user to select start, stop
;              and new times of multiple item MOVE.
;          v1.2 JAR 23-May-2008
;              Removed all those buttons from the bottom of the plot.
;              Added these as tabs to a new INTERNAL GUI.
;          v1.3 JAR 28-May-2008
;               Blank the pointing draw area when selecting another entry.
;          v1.4 JAR 25-Jun-2008
;               Added arrow to show selected time range of CPT, MOVE,
;               COPY, DELETE and METADATA guis
;          v1.5 JAR 17-Sep-2008
;               Check oRE_array is NOT zero (check using N_TAGS) before
;               concatenating it to the existing array.
;          v1.6 JAR 19-Jan-2008
;               Added functionality to include Data Volume Total
;          v1.7 JAR 5-May-2009
;               Plot XTW events instead of NGT (from obev files)
;          v1.8 JAR 16-Jun-2009
;               Label key as "XTW" instead of "HLA"
;          v1.9 JAR 29-Oct-2009
;               When clicking on the Orbit Events line, check start and
;               stop times of coincident SAA and Eclipse events. If
;               clicking on a free period, then print its start and stop
;               times.
;          v2.0 JAR/DHB 18-Nov-2009
;               Changed 0 to i to trap no-upload re-point file being the
;               first re-point file
;          v2.1 JAR 18-Jun-2010
;               Plot hunter timeline entry duration as total of hunter and
;               response studies (worst case scenario) - in top row
;          v2.2 JAR 21-Jun-2010
;               1. Added functionality whereby clicking on the "Orbit
;                  Events" row will calculate and print free and busy
;                  periods
;               2. Added functionality whereby clicking on the "Pointing
;                  Events" row will calculate and print pointing info for
;                  that time
;          v2.3 JAR 22-Jun-2010
;               Added number of time-tagged studies to timeline plot
;          v2.4 JAR 07-Sep-2011
;               Check value returned from eis_get_raster_pointing is a
;               structure. If not then bail out with a message.
;          v2.5 07-Nov-2011 JAR
;               Add code to calculate Data Volume on the fly - and report it
;               to TL plot
;          v2.6 JAR 29-Aug-2014
;               Added label to display SOT offsets. Also a button which
;               invokes the Preferences Tool to allow the values to be
;               updated. Assuming success, the new values are updated in the
;               widgets.
;
;-
;------------------------------------------------------------------------------;
FUNCTION eis_timeline_plot_gui::Init , parentClass

Self.parentClass  = parentClass
Self.group_leader = parentClass->tlbID()
;-------------------create the main base---------------------------------------;
pt_version = eis_get_pt_version_number()
widTitle = 'EIS Plan Timeline' + pt_version
TLB_EVENT                   = {eis_timeline_plot_gui_Event}
TLB_EVENT.eis_timeline_plot_gui = Self
TLB_EVENT.Type              = "TLB"
Self.tlbID                  = WIDGET_BASE(                                  $
                                    TITLE       = widTitle,                 $
                                    /TLB_SIZE_EVENTS ,                      $
                                    COLUMN      = 1,                        $
                                    ;/FLOATING      ,                        $
                                    GROUP_LEADER = Self.group_leader ,      $
                                    UValue      = TLB_EVENT,                $
                                    yOffset     = 460)

;-------------------create the GUI------------------------------;
Self->createGUI

RETURN, 1

END
;______________________________________________________________________________
;
;______________________________________________________________________________
PRO eis_timeline_plot_gui::createGUI

; ______________________________________________________________________
;
; Timeline Display Base
;
; ______________________________________________________________________
tl_displayBase              = WIDGET_BASE(Self.tlbID ,                      $
                                    ROW         = 1 , frame = 1 )

Event_Pro = 'eis_timeline_plot_gui_EV'


aLable                      = WIDGET_LABEL(tl_displayBase ,                 $
                                    value       = 'Display Start (UT): ')



PREV_EVENT                  = {eis_timeline_plot_gui_Event}
PREV_EVENT.eis_timeline_plot_gui = Self
PREV_EVENT.Type             = "DISPLAY_PREV"
aButton                     = WIDGET_BUTTON(tl_displayBase,                 $
                                    value       = ' < '     ,              $
                                    Event_Pro   = Event_Pro,                $
                                    uValue      = PREV_EVENT)



;
; Display Start - by default, start of day
;
Self.parentClass->getProperty , tl_graphics = tl_graphics
Self.datetime_gui = OBJ_NEW("eis_datetime_gui"              ,               $
                             Self                           ,               $
                             tl_displayBase                 ,               $
                             tl_graphics.axes.x_axis_day_tai,     $
                             xSize = 26)




NEXT_EVENT                  = {eis_timeline_plot_gui_Event}
NEXT_EVENT.eis_timeline_plot_gui = Self
NEXT_EVENT.Type             = "DISPLAY_NEXT"
aButton                     = WIDGET_BUTTON(tl_displayBase,                 $
                                    value       = ' > '     ,              $
                                    Event_Pro   = Event_Pro,                $
                                    uValue      = NEXT_EVENT)

;
; Display Duration
;
TL_DURATION_EVENT           = {eis_timeline_plot_gui_Event}
TL_DURATION_EVENT.eis_timeline_plot_gui = Self
TL_DURATION_EVENT.Type      = "TL_DURATION"
value =['1 hour','2 hours','3 hours','6 hours','12 hours','1 day',          $
        '1.5 days','2 days' ,'3 days','4 days','5 days','6 days','7 days']
Self.tl_durationID          = WIDGET_DROPLIST(tl_displayBase ,              $
                                    value       = value ,                   $
                                    title       = 'Duration:' ,             $
                                    Event_Pro   = Event_Pro     ,           $
                                    uValue      = TL_DURATION_EVENT)

WIDGET_CONTROL , Self.tl_durationID , set_droplist_select = 5


RESET_EVENT                 = {eis_timeline_plot_gui_Event}
RESET_EVENT.eis_timeline_plot_gui = Self
RESET_EVENT.Type            = "DISPLAY_RESET"
aButton                     = WIDGET_BUTTON(tl_displayBase,                 $
                                    value       = ' Go to Today '    ,     $
                                    Event_Pro   = Event_Pro,                $
                                    uValue      = RESET_EVENT)

REFRESH_EVENT               = {eis_timeline_plot_gui_Event}
REFRESH_EVENT.eis_timeline_plot_gui = Self
REFRESH_EVENT.Type          = "REFRESH"
aButton                     = WIDGET_BUTTON(tl_displayBase,                 $
                                    value       = ' Refresh Plot '   ,           $
                                    Event_Pro   = Event_Pro,                $
                                    uValue      = REFRESH_EVENT)
; ______________________________________________________________________
;
; Draw Area base
;
; ______________________________________________________________________

Self.xySize = [800,300]
Draw_Event                  = {eis_timeline_plot_gui_Event}
Draw_Event.eis_timeline_plot_gui     = Self
Draw_Event.Type             = "DRAW"
Self.drawID                 = WIDGET_DRAW(Self.tlbID  ,                     $
                                XSize       = Self.xySize[0],               $
                                YSize       = Self.xySize[1],               $
                                FRAME       = 1,                            $
                                /BUTTON_EVENTS,                             $
                                /TRACKING_EVENTS,                           $
                                /MOTION_EVENTS     ,                        $
                                uvalue      = DRAW_EVENT )


WINDOW , /FREE , /PIXMAP , xSize = Self.xySize[0] , ySize = Self.xySize[1]
Self.ref_pixID = !D.window
WINDOW , /FREE , /PIXMAP , xSize = Self.xySize[0] , ySize = Self.xySize[1]
Self.cac_pixId = !D.window

; ______________________________________________________________________
;
; Quit Button
;
; ______________________________________________________________________

;TEST_EVENT                  = {eis_timeline_plot_gui_Event}
;TEST_EVENT.eis_timeline_plot_gui = Self
;TEST_EVENT.Type             = "DISPLAY_TEST"
;TESTbutton                  = WIDGET_BUTTON(tl_displayBase,                 $
;                                    value       = 'Test',                $
;                                    Event_Pro   = Event_Pro  ,              $
;                                    uValue      = TEST_EVENT)

QUIT_EVENT                  = {eis_timeline_plot_gui_Event}
QUIT_EVENT.eis_timeline_plot_gui = Self
QUIT_EVENT.Type             = "QUIT"
quitbutton                  = WIDGET_BUTTON(tl_displayBase,                 $
                                    value       = ' Quit ',                $
                                    Event_Pro   = Event_Pro  ,              $
                                    uValue      = QUIT_EVENT)


; ______________________________________________________________________
;
; Info Base
;
; ______________________________________________________________________
infoBase                   = WIDGET_BASE(Self.tlbID ,                      $
                                   ROW         = 1                   ,     $
                                   FRAME       = 1 )

;
; Cursor Time
;
aLabelID                   = WIDGET_LABEL(infoBase                   ,     $
                                   value       = 'Cursor Time:')

value = ANYTIM2UTC(tl_graphics.axes.x_axis_day_tai,/STIME,/TRUNCATE)
Self.coordsLabelID         = WIDGET_LABEL(infoBase                   ,     $
                                   value       = value               ,     $
                                   /SUNKEN_FRAME                     ,     $
                                   xSize       = 140                 ,     $
                                   /ALIGN_LEFT)

;
; Data Volume
;
aLabelID                   = WIDGET_LABEL(infoBase                   ,     $
                                   value       = '  Data Volume (mBits):')

value = '0.'
Self.dvolLabelID           = WIDGET_LABEL(infoBase                   ,     $
                                   value       = value               ,     $
                                   /SUNKEN_FRAME                     ,     $
                                   xSize       = 50                  ,     $
                                   /ALIGN_LEFT)

;
; SOT Offset
;
value = '  SOT Offset:'
aLabelID                   = WIDGET_LABEL(infoBase                   ,     $
                                   value       = value)
Self.parentClass->getProperty , sot_offset = sot_offset

value = STRING(format='(D6.1,A1,D6.1)', $
                      sot_offset[0],',',sot_offset[1])
value = STRCOMPRESS(value,/REMOVE_ALL)
Self.sot_offsetLabelID     = WIDGET_LABEL(infoBase                   ,     $
                                   value       = value               ,     $
                                   /SUNKEN_FRAME                     ,     $
                                   xSize       = 70                  ,     $
                                   /ALIGN_LEFT)

SOTO_EVENT                 = {eis_timeline_plot_gui_Event}
SOTO_EVENT.eis_timeline_plot_gui = Self
SOTO_EVENT.Type            = "SOT_OFFSET"
sot_offsetButtonID         = WIDGET_BUTTON(infoBase                    ,   $
                                    value       = 'Modify...'          ,   $
                                    Event_Pro   = Event_Pro            ,   $
                                    uValue      = SOTO_EVENT)

END
;______________________________________________________________________________
;
;______________________________________________________________________________
PRO eis_timeline_plot_gui_Cleanup , wid

WIDGET_CONTROL , wid , get_uvalue = eis_timeline_plot_gui_Event
OBJ_DESTROY    , eis_timeline_plot_gui_Event.eis_timeline_plot_gui

END
;______________________________________________________________________________
; Cleanup
;______________________________________________________________________________
PRO eis_timeline_plot_gui::CleanUp

print,'Shutting down Timeline Plot'
OBJ_DESTROY , Self.datetime_gui
; WDELETE     , Self.cac_pixId
; print,'    - deleted cac_pix'
; WDELETE     , Self.ref_pixID
; print,'    - deleted ref_pix'
;print,'Shutting down Timeline Plot'

END
;______________________________________________________________________________
;
;______________________________________________________________________________
PRO eis_timeline_plot_gui::setProperty, autoScaleStr  = autoScaleStr

IF (N_ELEMENTS(autoScaleStr) GT 0) THEN BEGIN
    stop
ENDIF

End
;______________________________________________________________________________
;
;______________________________________________________________________________
PRO eis_timeline_plot_gui::GetProperty, tlbID   = tlbID

tlbID = Self.tlbID

End
;______________________________________________________________________________
; Return widget id
;______________________________________________________________________________
Function eis_timeline_plot_gui::tlbID

    Return, Self.tlbID
End

;______________________________________________________________________________
; Widget_Control wrapper
;______________________________________________________________________________
PRO eis_timeline_plot_gui::Control, _Ref_Extra=Widget_Control_Keywords

Widget_Control, Self.tlbID, _Extra=Widget_Control_Keywords

End

;______________________________________________________________________________
; Widget_Info wrapper
;______________________________________________________________________________
Function eis_timeline_plot_gui::Info, _Ref_Extra=Widget_Info_Keywords

Return, Widget_Info(Self.tlbID, _Extra=Widget_Info_Keywords)

End

;______________________________________________________________________________
; Realize wrapper
;______________________________________________________________________________
PRO eis_timeline_plot_gui::Realize

Widget_Control, Self.tlbID, /Realize

End

;______________________________________________________________________________
; XManager wrapper
;______________________________________________________________________________
PRO eis_timeline_plot_gui::XManager

XMANAGER , "eis_timeline_plot_gui" ,   Self.tlbID ,                                 $
    Event_Handler  = "eis_timeline_plot_gui_EV",                                    $
    cleanup        = "eis_timeline_plot_gui_Cleanup",                               $
    GROUP_LEADER   = Self.group_leader ,                                   $
    /NO_BLOCK

END

;______________________________________________________________________________
;
;______________________________________________________________________________
PRO eis_timeline_plot_gui_Event__Define

    struct = {  eis_timeline_plot_gui_Event,                                         $
                Type            : "",        $ ;Unique identifier for event
                eis_timeline_plot_gui   : OBJ_NEW(),  $ ;Reference to object passed
                extra           : 0          $ ;to - often object associated
             }
END
;______________________________________________________________________________
; Event Handler wrapper
;______________________________________________________________________________
PRO eis_timeline_plot_gui_EV , Event

;Get event handler structure containing eis_timeline_plot_gui type object
Widget_CONTROL,Event.ID,get_uvalue = eis_timeline_plot_gui_Event
;If a WIDGET_TAB event , just quit
IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ 'WIDGET_TAB') THEN BEGIN
    ;print,'tab event'
    RETURN
ENDIF

;Call eis_timeline_plot_gui's class member procedure "Handler"
eis_timeline_plot_gui_Event.eis_timeline_plot_gui->Handler,Event

END
;______________________________________________________________________________
;
; * THIS is the routine for putting in event handling NOT eis_timeline_plot_gui_Ev above.
;
; Event Handler - handle events.  Derived classes must
; contain their own implementation in order to handle events or else pass in an
; procedure name/function name using the Event_Pro/Event_Func keywords to
; CWidget::Init()
;______________________________________________________________________________
PRO eis_timeline_plot_gui::Handler, Event

WIDGET_CONTROL, Event.ID, Get_UValue = eis_timeline_plot_gui_Event
CASE eis_timeline_plot_gui_Event.Type OF
    "QUIT"          : Self->Control, /Destroy
    "TLB"           : Self->tlbResize , event.x , event.y
    "DRAW"          : Self->drawEvents , event
    "TL_DURATION"   : Self->updateTimelineDuration
    "DISPLAY_PREV"  : Self->set_new_datetime , /PREV
    "DISPLAY_NEXT"  : Self->set_new_datetime , /NEXT
    "DISPLAY_RESET" : Self->set_new_datetime , /RESET
    "REFRESH"       : Self->initialize_plot
;    "HELP_TEST"     : Self->set_new_datetime , /TEST
    "CPT_START"     : Self->set_cpt_start_time
    "CPT_STOP"      : Self->set_cpt_stop_time
    "META_START"    : Self->set_meta_start_time
    "META_STOP"     : Self->set_meta_stop_time
    "DVOL_START"    : Self->set_dvol_start_time
    "DVOL_STOP"     : Self->set_dvol_stop_time
    "MOVE_START"    : Self->set_move_start_time
    "MOVE_STOP"     : Self->set_move_stop_time
    "MOVE_NEW"      : Self->set_move_new_time
    "COPY_START"    : Self->set_copy_start_time
    "COPY_STOP"     : Self->set_copy_stop_time
    "COPY_NEW"      : Self->set_copy_new_time
    "DELETE_START"  : Self->set_delete_start_time
    "DELETE_STOP"   : Self->set_delete_stop_time
    "SOT_OFFSET"    : Self->set_sot_offset
    ELSE            : print,eis_timeline_plot_gui_Event.Type
ENDCASE

END
;______________________________________________________________________________
; Use context menu to set DVOL start_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::update_sot_offset

; Get new values and display them in the widgets
Self.parentClass->getProperty , sot_offset = sot_offset

value = STRING(format='(D6.1,A1,D6.1)', $
                      sot_offset[0],',',sot_offset[1])
value = STRCOMPRESS(value,/REMOVE_ALL)
WIDGET_CONTROL ,  Self.sot_offsetLabelID , set_value = value

END
;______________________________________________________________________________
; Use context menu to set DVOL start_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_sot_offset

Self.parentClass->invoke_pref_gui , set_tab_index = 1
; Get new values and display them in the widget_label "sot_offsetLabelID"

END
;______________________________________________________________________________
; Use context menu to set DVOL start_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_dvol_start_time

; Get cursor_position
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime

Self.parentClass->getProperty, dvol_gui = dvol_gui
dvol_gui->setProperty, tStartID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set DVOL stop_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_dvol_stop_time

; Get cursor_position
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime

Self.parentClass->getProperty, dvol_gui = dvol_gui
dvol_gui->setProperty, tStopID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set META start_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_meta_start_time

; Get cursor_position
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime

Self.parentClass->getProperty, meta_gui = meta_gui
meta_gui->setProperty, tStartID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set META stop_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_meta_stop_time

; Get cursor_position
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime

Self.parentClass->getProperty, meta_gui = meta_gui
meta_gui->setProperty, tStopID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set MOVE new_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_move_new_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime


Self.parentClass->getProperty, move_gui = move_gui
move_gui->setProperty, tNewID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set MOVE stop_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_move_stop_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime


Self.parentClass->getProperty, move_gui = move_gui
move_gui->setProperty, tStopID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set MOVE start_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_move_start_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime


Self.parentClass->getProperty, move_gui = move_gui
move_gui->setProperty, tStartID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set COPY start_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_copy_start_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui    ,     $
                                copy_gui        = copy_gui
cursor_time_gui->getProperty  , datetime = datetime
copy_gui->setProperty, tStartID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set COPY new_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_copy_new_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui    ,     $
                                copy_gui        = copy_gui
cursor_time_gui->getProperty  , datetime = datetime
copy_gui->setProperty, tNewID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set COPY stop_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_copy_stop_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui    ,     $
                                copy_gui        = copy_gui
cursor_time_gui->getProperty  , datetime = datetime
copy_gui->setProperty, tStopID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set DELETE start_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_delete_start_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui    ,     $
                                delete_gui      = delete_gui
cursor_time_gui->getProperty  , datetime = datetime
delete_gui->setProperty, tStartID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set DELETE stop_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_delete_stop_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui    ,     $
                                delete_gui      = delete_gui
cursor_time_gui->getProperty  , datetime = datetime
delete_gui->setProperty, tStopID = datetime
Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set cpt stop_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_cpt_stop_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime


Self.parentClass->getProperty, cpt_gui = cpt_gui
cpt_gui->setProperty, tStopID = datetime

Self->initialize_plot

END
;______________________________________________________________________________
; Use context menu to set cpt start_time
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_cpt_start_time

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime


Self.parentClass->getProperty, cpt_gui = cpt_gui
cpt_gui->setProperty, tStartID = datetime

Self->initialize_plot

END
;______________________________________________________________________________
; Timeline display - go back 24 hours
;______________________________________________________________________________
PRO eis_timeline_plot_gui::set_new_datetime , reset = reset   ,             $
                                              prev  = prev    ,             $
                                              next  = next    ,             $
                                              test  = test

Self.parentClass->getProperty , tl_graphics = tl_graphics
axes = tl_graphics.axes

; Get Display Start datetime (TAI)
Self.datetime_gui->getproperty , datetime = datetime
; Convert datetime to UTC
datetime_utc = anytim2utc(datetime)

;
; TEST - to 26-Nov-2006
;
IF (KEYWORD_SET(test) EQ 1) THEN BEGIN

    WIDGET_CONTROL , Self.tl_durationID , set_droplist_select = 5
    axes.x_axis_day_tai = anytim2tai('16-Jun-2007 00:00:00')
    axes.x_axis_start   = 0.0
    axes.x_axis_stop    = 24.0
    axes.x_axis_length  = 24.0
    ; Convert back to TAI
    datetime            = axes.x_axis_day_tai
ENDIF
;
; Reset - to start of day (00:00:00)
;
IF (KEYWORD_SET(reset) EQ 1) THEN BEGIN
    datetime_string   = systim()
    datetime_utc      = anytim2utc(datetime_string)
    datetime_utc.time = 0L
    ; Convert back to TAI
    datetime         = utc2tai(datetime_utc)
ENDIF
;
; - 24 hours
;
IF (KEYWORD_SET(prev)  EQ 1) THEN BEGIN

    duration            = axes.x_axis_length
    axes.x_axis_day_tai = axes.x_axis_day_tai - (duration * 3600)
    ; Need to go to UTC
    utc      = anytim2utc(axes.x_axis_day_tai)
    axes.x_axis_start = (utc.time / 3600) / 1000.
    axes.x_axis_stop   = axes.x_axis_start  +  duration

    ; Update datetime GUI
    datetime = datetime - (duration * 3600)

END

;
; + 24 hours
;
IF (KEYWORD_SET(next)  EQ 1) THEN BEGIN

    duration            = axes.x_axis_length
    axes.x_axis_day_tai = axes.x_axis_day_tai + (duration * 3600)
    axes.x_axis_start   = axes.x_axis_start   +  duration
    axes.x_axis_stop    = axes.x_axis_stop    +  duration

    ; Update datetime GUI
    datetime = datetime + (duration * 3600)

END

; Update tl_graphics structure
tl_graphics.axes = axes
Self.parentClass->setProperty , tl_graphics = tl_graphics
; Set Display Start datetime (TAI)
Self.datetime_gui->setproperty , datetime = datetime
Self->updateTimelineDuration

END
;______________________________________________________________________________
; Draw Events - get cursor position
;______________________________________________________________________________
PRO eis_timeline_plot_gui::updateTimelineDuration

;stop
Self.parentClass->savePlanToDatabase , /NO_DATE_DIALOG , /NO_PLOT_UPDATE
Self.parentClass->getProperty , eis_timeline_container = eis_timeline_container
;eis_timeline_container->clear_all

WIDGET_CONTROL , /HOURGLASS

; Get Display Start datetime (TAI)
Self.datetime_gui->getproperty,datetime=datetime

; Get "Display Duration" (droplist) value
duration = eis_get_display_duration_value(Self.tl_durationID)



Self.parentClass->getProperty , tl_graphics = tl_graphics
; Where newTime is a string of the form "4-May-2006 00:00:00"
; Update tl_graphics.axes tags

tl_graphics.axes.x_axis_day_tai = datetime
strTime                         = timstr2ex(anytim2utc(datetime,/STIME))
; strTime -> h m s ms d m y


;duration = duration - FLOAT(strTime[0])
tl_graphics.axes.x_axis_start   = FLOAT(strTime[0])
tl_graphics.axes.x_axis_length  = duration
tl_graphics.axes.x_axis_stop    = FLOAT(strTime[0]) + duration
;tl_graphics.axes.x_axis_stop    = duration


; Set Display Start datetime (TAI)
Self.datetime_gui->setproperty,datetime=datetime


; Update tl_graphics structure
Self.parentClass->setProperty , tl_graphics = tl_graphics
; Read plan from database
Self.parentClass->readPlanFromDatabase


END
;______________________________________________________________________________
; Draw Events - get cursor position
;______________________________________________________________________________
PRO eis_timeline_plot_gui::tracker

;t0 = SYSTIME(1)

; Create a temporary Pixmap window
WINDOW , /FREE , /PIXMAP , xsize = Self.xySize[0] , ysize = Self.xySize[1]
tempPixmap = !D.WINDOW
;  Create plot - with no data
Self->plotAxes , /NO_DATA
; Destroy Pixmap
WDELETE,tempPixmap
; Job Done

;timed = STRCOMPRESS(SYSTIME(1) - t0,/REMOVE_ALL)
;print,STRJOIN(['Tracking event V2 took ',timed,' seconds'],/SINGLE)

END
;______________________________________________________________________________
; Draw Events - CPT Context Menu
;______________________________________________________________________________
PRO eis_timeline_plot_gui::cpt_context_menu , event

contextbase                = WIDGET_BASE(Self.drawID            ,          $
                                   /CONTEXT_MENU)

cpt_start_Event            = {eis_timeline_plot_gui_Event}
cpt_start_Event.eis_timeline_plot_gui = Self
cpt_start_Event.Type       = "CPT_START"
value                      = 'Set as CPT start time'
cpt_startButton            = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = cpt_start_Event)

cpt_stop_Event             = {eis_timeline_plot_gui_Event}
cpt_stop_Event.eis_timeline_plot_gui = Self
cpt_stop_Event.Type        = "CPT_STOP"
value                      = 'Set as CPT stop time'
cpt_stopButton             = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = cpt_stop_Event)

widget_displaycontextmenu, event.id, event.x, event.y, contextbase

END
;______________________________________________________________________________
; Draw Events - Move Context Menu
;______________________________________________________________________________
PRO eis_timeline_plot_gui::move_context_menu , event

contextbase                = WIDGET_BASE(Self.drawID            ,          $
                                   /CONTEXT_MENU)

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime
ct = anytim2utc(datetime,/stime,/truncate)

move_start_Event           = {eis_timeline_plot_gui_Event}
move_start_Event.eis_timeline_plot_gui = Self
move_start_Event.Type      = "MOVE_START"
value = STRJOIN(['Set ',ct,' as MOVE start time'],/SINGLE)
move_startButton           = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = move_start_Event)

move_stop_Event            = {eis_timeline_plot_gui_Event}
move_stop_Event.eis_timeline_plot_gui = Self
move_stop_Event.Type       = "MOVE_STOP"
value = STRJOIN(['Set ',ct,' as MOVE stop time'],/SINGLE)
move_stopButton            = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = move_stop_Event)

move_new_Event             = {eis_timeline_plot_gui_Event}
move_new_Event.eis_timeline_plot_gui = Self
move_new_Event.Type       = "MOVE_NEW"
value = STRJOIN(['Set ',ct,' as NEW time'],/SINGLE)
move_newButton              = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = move_new_Event)

widget_displaycontextmenu, event.id, event.x, event.y, contextbase

END
;______________________________________________________________________________
; Draw Events - Move Context Menu
;______________________________________________________________________________
PRO eis_timeline_plot_gui::copy_context_menu , event

contextbase                = WIDGET_BASE(Self.drawID            ,          $
                                   /CONTEXT_MENU)

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime
ct = anytim2utc(datetime,/stime,/truncate)

copy_start_Event           = {eis_timeline_plot_gui_Event}
copy_start_Event.eis_timeline_plot_gui = Self
copy_start_Event.Type      = "COPY_START"
value = STRJOIN(['Set ',ct,' as COPY start time'],/SINGLE)
copy_startButton           = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = copy_start_Event)

copy_stop_Event            = {eis_timeline_plot_gui_Event}
copy_stop_Event.eis_timeline_plot_gui = Self
copy_stop_Event.Type       = "COPY_STOP"
value = STRJOIN(['Set ',ct,' as COPY stop time'],/SINGLE)
copy_stopButton            = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = copy_stop_Event)

copy_new_Event             = {eis_timeline_plot_gui_Event}
copy_new_Event.eis_timeline_plot_gui = Self
copy_new_Event.Type       = "COPY_NEW"
value = STRJOIN(['Set ',ct,' as NEW time'],/SINGLE)
copy_newButton              = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = copy_new_Event)

widget_displaycontextmenu, event.id, event.x, event.y, contextbase

END
;______________________________________________________________________________
; Draw Events - DATA VOLUME Context Menu
;______________________________________________________________________________
PRO eis_timeline_plot_gui::dvol_context_menu , event

contextbase                = WIDGET_BASE(Self.drawID            ,          $
                                   /CONTEXT_MENU)

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime
ct = anytim2utc(datetime,/stime,/truncate)

DVOL_start_Event           = {eis_timeline_plot_gui_Event}
DVOL_start_Event.eis_timeline_plot_gui = Self
DVOL_start_Event.Type      = "DVOL_START"
value = STRJOIN(['Set ',ct,' as DATA Volume start time'],/SINGLE)
DVOL_startButton           = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = DVOL_start_Event)

DVOL_stop_Event            = {eis_timeline_plot_gui_Event}
DVOL_stop_Event.eis_timeline_plot_gui = Self
DVOL_stop_Event.Type       = "DVOL_STOP"
value = STRJOIN(['Set ',ct,' as DATA Volume stop time'],/SINGLE)
DVOL_stopButton            = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = DVOL_stop_Event)

widget_displaycontextmenu, event.id, event.x, event.y, contextbase

END
;______________________________________________________________________________
; Draw Events - METADATA Context Menu
;______________________________________________________________________________
PRO eis_timeline_plot_gui::meta_context_menu , event

contextbase                = WIDGET_BASE(Self.drawID            ,          $
                                   /CONTEXT_MENU)

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime
ct = anytim2utc(datetime,/stime,/truncate)

META_start_Event           = {eis_timeline_plot_gui_Event}
META_start_Event.eis_timeline_plot_gui = Self
META_start_Event.Type      = "META_START"
value = STRJOIN(['Set ',ct,' as METADATA start time'],/SINGLE)
META_startButton           = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = META_start_Event)

META_stop_Event            = {eis_timeline_plot_gui_Event}
META_stop_Event.eis_timeline_plot_gui = Self
META_stop_Event.Type       = "META_STOP"
value = STRJOIN(['Set ',ct,' as METADATA stop time'],/SINGLE)
META_stopButton            = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = META_stop_Event)

widget_displaycontextmenu, event.id, event.x, event.y, contextbase

END
;______________________________________________________________________________
; Draw Events - Move Context Menu
;______________________________________________________________________________
PRO eis_timeline_plot_gui::delete_context_menu , event

contextbase                = WIDGET_BASE(Self.drawID            ,          $
                                   /CONTEXT_MENU)

;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime
ct = anytim2utc(datetime,/stime,/truncate)

DELETE_start_Event         = {eis_timeline_plot_gui_Event}
DELETE_start_Event.eis_timeline_plot_gui = Self
DELETE_start_Event.Type    = "DELETE_START"
value = STRJOIN(['Set ',ct,' as DELETE start time'],/SINGLE)
DELETE_startButton         = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = DELETE_start_Event)

DELETE_stop_Event          = {eis_timeline_plot_gui_Event}
DELETE_stop_Event.eis_timeline_plot_gui = Self
DELETE_stop_Event.Type     = "DELETE_STOP"
value = STRJOIN(['Set ',ct,' as DELETE stop time'],/SINGLE)
DELETE_stopButton          = WIDGET_BUTTON(contextbase          ,          $
                                   value       = value          ,          $
                                   uvalue      = DELETE_stop_Event)

widget_displaycontextmenu, event.id, event.x, event.y, contextbase

END
;______________________________________________________________________________
; Draw Events - get cursor position
;______________________________________________________________________________
PRO eis_timeline_plot_gui::drawEvents , event

; Catch TRACKING_EVENTS - redraw plot then bail!
IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ                $
                    'WIDGET_TRACKING') THEN BEGIN

    IF (event.enter EQ 1) THEN Self->tracker
    RETURN

ENDIF

;
; Check we have a left or right mouse press ONLY, where
;     PRESS -> event.type = 0
;
valid_click = 0B
;
; Case 1. Left click (press)
;
IF (event.type EQ 0) AND (event.press EQ 1) THEN valid_click = 1B
;
; Case 2. Right click (press) when CPT GUI is already invoked
;
; Is eis_cpt_gui up? If NOT then bail out!
valid_cpt_gui = XREGISTERED("eis_cpt_gui")
IF (event.type       EQ 0)     AND                                         $
   (event.press      EQ 4)     AND                                         $
   (valid_cpt_gui    GE 1)     THEN valid_click = 1B

; Case 3. Right click (press) when MOVE GUI is already invoked
;
; Is move_gui up? If NOT then bail out!
valid_move_gui = XREGISTERED("eis_move_tl_gui")
IF (event.type       EQ 0)     AND                                         $
   (event.press      EQ 4)     AND                                         $
   (valid_move_gui   GE 1)     THEN valid_click = 1B

; Case 3. Right click (press) when MOVE GUI is already invoked
;
; Is copy_gui up? If NOT then bail out!
valid_copy_gui = XREGISTERED("eis_copy_tl_gui")
IF (event.type       EQ 0)     AND                                         $
   (event.press      EQ 4)     AND                                         $
   (valid_copy_gui   GE 1)     THEN valid_click = 1B

; Case 4. Right click (press) when DELETE GUI is already invoked
;
; Is delete_gui up? If NOT then bail out!
valid_delete_gui = XREGISTERED("eis_delete_tl_gui")
IF (event.type       EQ 0)     AND                                         $
   (event.press      EQ 4)     AND                                         $
   (valid_delete_gui GE 1)     THEN valid_click = 1B

; Case 5. Right click (press) when METADATA GUI is already invoked
;
; Is meta_gui up? If NOT then bail out!
valid_meta_gui = XREGISTERED("eis_meta_tl_gui")
IF (event.type       EQ 0)     AND                                         $
   (event.press      EQ 4)     AND                                         $
   (valid_meta_gui   GE 1)     THEN valid_click = 1B

; Case 6. Right click (press) when DATA VOLUME GUI is already invoked
;
; Is dvol_gui up? If NOT then bail out!
valid_dvol_gui = XREGISTERED("eis_dvol_tl_gui")
IF (event.type       EQ 0)     AND                                         $
   (event.press      EQ 4)     AND                                         $
   (valid_dvol_gui   GE 1)     THEN valid_click = 1B

; Case 7. Motion Events
IF (event.type EQ 2) THEN valid_click = 1B

;
; All other cases are ignored!!!!
;
IF (valid_click NE 1) THEN RETURN

WIDGET_CONTROL , Self.drawID , get_value = drawID
WSET , drawID
;!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
;constrain coords to within the ROI draw area
event.x = 0 > event.x < (Self.xySize[0] - 1)
event.y = 0 > event.y < (Self.xySize[1] - 1)
;convert from DEVICE coords to DATA coords
coords = CONVERT_COORD(event.x , event.y , /DEVICE , /TO_DATA)
xPos = !x.crange[0] > coords[0] < !x.crange[1]
yPos = !y.crange[0] > coords[1] < !y.crange[1]

;
; Update cursor time (a property of eis_mk_plan)
;
Self.parentClass->getProperty , tl_graphics = tl_graphics
; OK, if more than 24 hours from display start, we need to update
; cursor time date as well!
IF (xPos GE 24.) THEN days = FLOOR(xPos/24. mod 24.)
offset   = xPos - tl_graphics.axes.x_axis_start
datetime = tl_graphics.axes.x_axis_day_tai + (offset*3600.)

; Motion Events. Print and bail out!
IF (event.type EQ 2) THEN BEGIN
   value = anytim2utc(datetime,/STIME,/TRUNCATE)
   WIDGET_CONTROL,Self.coordsLabelID, set_value = value
   RETURN
ENDIF


; Call eis_mk_plan method to update cursor time
Self.parentClass->updateCursorTime , datetime

Self->plot_cursor_time        ; onto cac_pixId pixmap
;stop
; ; Redraw graphics
; Self.parentClass->getProperty , replot = replot
; IF (replot EQ 1) THEN BEGIN
;     Self.parentClass->setProperty , replot = 0B
;     print,"Refreshing timeline plot"
;    Self->initialize_plot
; ENDIF
;stop
Self.parentClass->update_summary_selection
Self.parentClass->refresh_dr_gui
Self.parentClass->plot_pointing
Self->tracker
;stop

; Create context-sensitive menus if these guis are invoked
IF (event.type EQ 0)   AND (event.press EQ 4) THEN BEGIN
   IF (valid_cpt_gui    GE 1) THEN Self->cpt_context_menu    , event
   IF (valid_move_gui   GE 1) THEN Self->move_context_menu   , event
   IF (valid_copy_gui   GE 1) THEN Self->copy_context_menu   , event
   IF (valid_delete_gui GE 1) THEN Self->delete_context_menu , event
   IF (valid_meta_gui   GE 1) THEN Self->meta_context_menu   , event
   IF (valid_dvol_gui   GE 1) THEN Self->dvol_context_menu   , event
ENDIF

; Get Orbit Events
IF (FLOOR(yPos) EQ 5) THEN Self->get_obev , datetime
; Get Orbit Events
IF (FLOOR(yPos) EQ 3) THEN Self->get_pointing , datetime


END
;______________________________________________________________________________
; Draw Events - get Orbit Events
;______________________________________________________________________________
PRO eis_timeline_plot_gui::get_pointing , datetime

; OK, get the Pointing info
Self.parentClass->getProperty , rpev = rpev
; OK, check we have some re-point events to plot
valid_rpev = 1
IF (N_ELEMENTS(*rpev)  EQ 1)  AND                               $
   (N_TAGS((*rpev)[0]) EQ 0)  THEN valid_rpev = 0
IF (valid_rpev EQ 0) THEN BEGIN
   ;print,'No pointing info found'
   RETURN
ENDIF

; Get spacecraft pointing info
pointing = eis_get_raster_pointing(datetime                          ,     $
                                   0.D                               ,     $
                                   num_days = 5)

; JAR 7-Sep-2011
; Check if a structure is returned. If not then FAIL!
IF (N_TAGS(pointing) EQ 0) THEN BEGIN
   print,"Pointing info not found."
   RETURN
ENDIF

; Print results
x_point = STRTRIM(STRING(format='(F8.2)',pointing[0].x_point),2)
y_point = STRTRIM(STRING(format='(F8.2)',pointing[0].y_point),2)
track   = STRCOMPRESS(pointing[0].tracking,/REMOVE_ALL)
print,STRJOIN(['  Spacecraft Pointing = ',x_point,'",',y_point             ,     $
               '" on Tracking curve ',track,' at '                         ,     $
               anytim2utc(datetime,/STIME,/TRUNCATE)],/SINGLE)

; Get an array of structures for each re-point
rp_array = eis_get_rp_array(rpev)

before_cp_tai_list = WHERE(rp_array[*].date_time LE datetime,count)
; If there are none before the cursor time, then bail out
IF (count LT 1) THEN RETURN
; Get maximum value
last_repoint    = max(rp_array[before_cp_tai_list].date_time)


; Warn if cp_tai - last_repoint < 2 mins (default buffer)
time_diff = (datetime - last_repoint)
line01 = '  Time difference between cursor time and last repoint is: '
line02 = STRTRIM(string(format="(f8.2)",time_diff),2)
line03 = ' seconds ('
line04 = STRTRIM(SEC2DHMS(time_diff),2)
line05 = ').'
mText  = [line01,line02,line03,line04,line05]
print,mText


END
;______________________________________________________________________________
; Draw Events - get Orbit Events
;______________________________________________________________________________
PRO eis_timeline_plot_gui::free_period_report , datetime , obev

; Get previous obev stop time, and next obev event start_time
prev_stop_time_list = WHERE(obev[*].stop_time LE datetime,count)
IF (count EQ 0) THEN BEGIN
   Self.parentClass->getProperty , tl_graphics = tl_graphics
   prev_stop_time  = tl_graphics.axes.x_axis_day_tai
ENDIF ELSE BEGIN
   prev_stop_time = MAX(obev[prev_stop_time_list].stop_time)
ENDELSE

next_start_time_list = WHERE(obev[*].start_time GE datetime,count)
IF (count EQ 0) THEN BEGIN
   Self.parentClass->getProperty , tl_graphics = tl_graphics
   next_start_time =  tl_graphics.axes.x_axis_day_tai                +     $
                     (tl_graphics.axes.X_AXIS_LENGTH*3600.)
ENDIF ELSE BEGIN
   next_start_time = MIN(obev[next_start_time_list].start_time)
ENDELSE

line0 = 'Free Period: '
line1 = anytim2utc(prev_stop_time ,/STIME,/TRUNCATE)
line2 = anytim2utc(next_start_time,/STIME,/TRUNCATE,/TIME)
line3 = sec2dhms(next_start_time - prev_stop_time)
line  = STRJOIN([line0,line1,' to ',line2,' (',line3,')'],/SINGLE)
print,line
print,'+++++++++++++++++++++++++++++++++++++++++++++++++++++++'

END
;______________________________________________________________________________
; Draw Events - get Orbit Events
;______________________________________________________________________________
PRO eis_timeline_plot_gui::get_obev , datetime

;print,anytim2utc(datetime,/stime)
; OK, what time period are we observing?
Self.parentClass->getProperty , obev        = obev
IF (PTR_VALID(obev) NE 1) THEN RETURN
IF (N_TAGS(*obev[0]) EQ 0) THEN RETURN

obev = (*obev)

;
; SAA
; OK, need to "doctor" start and stop times of SAA events to include
; a 5-minute buffer. Let's work on "obev" since it's a local and
; temporary copy.
saa_list   = WHERE(STRLOWCASE(obev[*].name) EQ 'saa',count_saa)
saa_buffer = 5.*60. ; 5 mins
saa_buffer = 0.*60. ; 0 mins
FOR i = 0 , count_saa - 1 DO BEGIN
   obev[saa_list[i]].start_time = obev[saa_list[i]].start_time - saa_buffer
   obev[saa_list[i]].stop_time  = obev[saa_list[i]].stop_time  + saa_buffer
ENDFOR



; Get all orbit events in time range
obev_list = WHERE( (obev[*].start_time LE datetime)  AND                   $
                   (obev[*].stop_time  GE datetime)                  ,     $
                   count , complement = comp)
;print,'+++++++++++++++++++++++++++++++++++++++++++++++++++++++'
; If none found, then report and bail out.
IF (count EQ 0) THEN BEGIN
   Self->free_period_report , datetime , obev
   RETURN
ENDIF

; Create new array with event structures in this time range
obev_str_arr = obev[obev_list]

min_start_time = MIN(obev_str_arr[*].start_time)
max_stop_time  = MAX(obev_str_arr[*].stop_time)
obev_comp      = obev[comp]
count_start    = 1
count_stop     = 1

; OK, run thro' the complement of structures to find any that overlap
; with our new (minimum) start time
WHILE (count_start EQ 1) DO BEGIN
   obev_list_start = WHERE( (obev_comp.start_time LE min_start_time)  AND          $
                            (obev_comp.stop_time  GE min_start_time)         ,     $
                   count_start , complement = obev_comp_new)
   IF (count_start GE 1) THEN BEGIN
       obev_str_arr = [obev_str_arr , obev_comp[obev_list_start]]
       obev_comp = obev_comp[obev_comp_new]
       min_start_time = MIN(obev_str_arr[*].start_time)
   ENDIF ELSE count_start = 0

ENDWHILE

; OK, run thro' the complement of structures to find any that overlap
; with our new (maximum) stop time
WHILE (count_stop  EQ 1) DO BEGIN
   obev_list_stop  = WHERE( (obev_comp.start_time LE max_stop_time)  AND          $
                            (obev_comp.stop_time  GE max_stop_time)         ,     $
                   count_stop  , complement = obev_comp_new)
   IF (count_stop  GE 1) THEN BEGIN
       obev_str_arr = [obev_str_arr , obev_comp[obev_list_stop]]
       obev_comp = obev_comp[obev_comp_new]
       max_stop_time  = MAX(obev_str_arr[*].stop_time)
   ENDIF ELSE count_stop = 0

ENDWHILE

; Report our findings here
FOR i = 0 , N_ELEMENTS(obev_str_arr) - 1 DO BEGIN

   t0_string = ANYTIM2UTC(obev_str_arr[i].start_time,/STIME,/TRUNCATE)
   t1_string = ANYTIM2UTC(obev_str_arr[i].stop_time ,/STIME,/TRUNCATE)

   print,STRJOIN([ '  '                                              ,     $
                   STRUPCASE(obev_str_arr[i].name) + "  "            ,     $
                   ' '                                               ,     $
                   t0_string                                         ,     $
                   ' to '                                            ,     $
                   t1_string]                                        ,     $
                   /SINGLE)
ENDFOR

print,'  __________________________________________________'
; Now print total
print,STRJOIN([    '  '                                              ,     $
                   'Total'                                           ,     $
                   ' '                                               ,     $
                   anytim2utc(min_start_time,/stime,/trunc)          ,     $
                   ' to '                                            ,     $
                   anytim2utc(max_stop_time,/stime,/trunc)]          ,     $
                   /SINGLE)

END
;______________________________________________________________________________
; Draw Events - get cursor position
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_cursor_time

; Retrieve default colour table properties
Self.parentClass->getProperty , o_def_ct = o_def_ct
o_def_ct->getProperty , plotsCT = plotsCT , imageCT = imageCT

TVLCT , plotsCT[*,0] , plotsCT[*,1] , plotsCT[*,2] ;IMAGE ct
;
; Cache Pixmap
;
; Set cache pixmap as current window
WSET , Self.cac_pixID
; Copy contents of reference pixmap to cache pixmap
DEVICE , Copy = [ 0 , 0 , Self.xySize[0] , Self.xySize[1] , 0 , 0 , Self.ref_pixID ]
; Plot cursor_position to cache pixmap
Self->plot_cursor_position
; Plot studies to cache pixmap
Self->plot_timeline_entries

; Set draw widget as current window
WIDGET_CONTROL , Self.drawID , get_value = drawID
WSET , drawID
DEVICE , Copy = [ 0 , 0 , Self.xySize[0] , Self.xySize[1] , 0 , 0 , Self.cac_pixID ]

TVLCT , imageCT[*,0] , imageCT[*,1] , imageCT[*,2] ;IMAGE ct

END
;______________________________________________________________________________
; Select Timeline
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_cursor_position , no_refresh = no_refresh

; Onto pixmap: cac_pixId
Self.parentClass->getProperty , tl_graphics = tl_graphics ,                 $
                                eis_timeline_container = eis_timeline_container
; OK, we're doing this calculation in UTC - however, we need to take
; into account any difference in days
start_time_utc = anytim2utc(tl_graphics.axes.x_axis_day_tai)
day_start_mjd  = start_time_utc.mjd
day_start_time = start_time_utc.time
;
; Get cursor_position
;
Self.parentClass->getProperty , cursor_time_gui = cursor_time_gui
cursor_time_gui->getProperty  , datetime = datetime

; Difference between (in seconds)
diff = datetime - tl_graphics.axes.x_axis_day_tai
t0   = tl_graphics.axes.x_axis_start + diff/3600.
;
; We must plot this line thro' all plot rows
;
nRows = WHERE(tl_graphics.axes.y_axis_row[*].on_screen EQ 1 ,count)
OPLOT , [t0,t0] , [-.5,count+.5] , color = 5 ; , lines = 3
IF (eis_timeline_container->count() GT 0) THEN BEGIN
    Self->whichStudySelected; , no_refresh = no_refresh
ENDIF ELSE BEGIN
    eis_timeline_container->setProperty , working_position = -1
    eis_timeline_container->setProperty , study_selected   =  0
ENDELSE

END
;______________________________________________________________________________
;
;______________________________________________________________________________
PRO eis_timeline_plot_gui::whichStudySelected , no_refresh = no_refresh

Self.parentClass->getProperty ,                                             $
                        cursor_time_gui        = cursor_time_gui ,          $
                        eis_timeline_container = eis_timeline_container

; Get cursor time
cursor_time_gui->getProperty  , datetime = datetime
; Get working_position
working_position = eis_timeline_container->returnSelectedStudyIndex(datetime)
IF (working_position EQ -1) THEN RETURN


Self.parentClass->read_science_entry
Self.parentClass->updateStudyWidgets , no_refresh = no_refresh
Self.parentClass->updateStudyRasterListWidget
;Self.parentClass->plot_pointing ,/NO_POINT

END
;______________________________________________________________________________
;
;______________________________________________________________________________
PRO eis_timeline_plot_gui::tlbResize , xc , yc

geoTLB       = WIDGET_INFO(Self.tlbID , /GEOMETRY)
currentXSize = geoTLB.xSize
currentYSize = geoTLB.ySize

dx = xc - currentXSize
dy = yc - currentYSize

geoDrawID  = WIDGET_INFO(Self.drawID , /GEOMETRY)

Self.xySize = [geoDrawID.xSize + dx , geoDrawID.ySize + dy]

; Resize the draw widget
WIDGET_CONTROL , Self.drawID , xsize = Self.xySize[0] ,               $
                               ysize = Self.xySize[1]

WDELETE , Self.ref_pixID
WINDOW  , /FREE , /PIXMAP , xSize = Self.xySize[0] , ySize = Self.xySize[1]
Self.ref_pixID = !D.window

WDELETE , Self.cac_pixId
WINDOW  , /FREE , /PIXMAP , xSize = Self.xySize[0] , ySize = Self.xySize[1]
Self.cac_pixId = !D.window


Self->initialize_plot

END
;______________________________________________________________________________
; Read and plot OP Events
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_op_events

; OK, what time period are we observing?
Self.parentClass->getProperty , tl_graphics = tl_graphics            ,     $
                                num_days    = num_days

start_time = tl_graphics.axes.x_axis_day_tai
duration   = tl_graphics.axes.x_axis_length
opev       = eis_read_op_events(start_time , duration , num_days = num_days)
Self.parentClass->setProperty , opev = opev


IF (N_TAGS(opev[0]) EQ 0) THEN BEGIN

    ; OK, opev_*evt file NOT found
    plot_item , 0.0 , tl_graphics.axes.x_axis_stop , 2 , ''  ,              $
                                           color = 10 , maxcharsize = 2.5
    plot_item , 0.0 , tl_graphics.axes.x_axis_stop , 2 ,                    $
                                          'No OP Events data'  ,       $
                                           color = 0 , maxcharsize = 2.5
    RETURN

ENDIF ELSE BEGIN
    ; Plot OP Events
    FOR i = 0 , N_ELEMENTS(opev) - 1 DO BEGIN
        eis_plot_opev, opev[i], tl_graphics.axes.x_axis_day_tai, ROW=2
    ENDFOR
ENDELSE

END
;______________________________________________________________________________
; Read and plot Re-Pointing Events
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_repointing_events

t0 = SYSTIME(1)

; OK, what time period are we observing?
Self.parentClass->getProperty , tl_graphics = tl_graphics , rpev = rpev

; OK, check we have some re-point events to plot
valid_rpev = 1
IF (N_ELEMENTS(*rpev)  EQ 1)  AND                               $
   (N_TAGS((*rpev)[0]) EQ 0)  THEN valid_rpev = 0

; Get an array of structures for each re-point
IF (valid_rpev EQ 1) THEN rp_array = eis_get_rp_array(rpev)

IF (valid_rpev EQ 0) THEN BEGIN

    ; OK, rpev_*evt file NOT found
    plot_item , 0.0 , tl_graphics.axes.x_axis_stop , 3 , ''  ,              $
                                           color = 10 , maxcharsize = 2.5
    plot_item , 0.0 , tl_graphics.axes.x_axis_stop , 3 ,                    $
                                          'No Re-Pointing Events data'  ,   $
                                           color = 0 , maxcharsize = 2.5
    RETURN

ENDIF ELSE BEGIN
    ; Plot Re-pointing Events
    FOR i = 0 , N_ELEMENTS(rp_array) - 1 DO BEGIN
        eis_plot_rpev, rp_array[i], tl_graphics.axes.x_axis_day_tai, ROW=3
    ENDFOR
ENDELSE

elapsed_time = SYSTIME(1) - t0
IF (elapsed_time GT 1.) THEN BEGIN
   print,STRJOIN(['Re-point events took '                  ,         $
                  STRCOMPRESS(elapsed_time,/REMOVE_ALL)    ,         $
                  ' seconds'],/SINGLE)
ENDIF

END
;______________________________________________________________________________
; Read and plot Station Events
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_station_events

; OK, what time period are we observing?
Self.parentClass->getProperty , tl_graphics = tl_graphics , stev = stev

start_time = tl_graphics.axes.x_axis_day_tai
duration   = tl_graphics.axes.x_axis_length
;stev       = eis_read_station_events(start_time , duration)
stev       = *stev

IF (N_TAGS(stev[0]) EQ 0) THEN BEGIN

    ; OK, stev_*evt file NOT found
    plot_item , 0.0 , tl_graphics.axes.x_axis_stop , 4 , ''  ,              $
                                           color = 10 , maxcharsize = 2.5
    plot_item , 0.0 , tl_graphics.axes.x_axis_stop , 4 ,                    $
                                          'No Station Events data'  ,       $
                                           color = 0 , maxcharsize = 2.5
    RETURN

ENDIF ELSE BEGIN
    ; Plot Station Events
    FOR i = 0 , N_ELEMENTS(stev) - 1 DO BEGIN
        eis_plot_stev, stev[i], tl_graphics.axes.x_axis_day_tai, ROW=4
    ENDFOR
ENDELSE

END
;______________________________________________________________________________
; Read and plot Orbit Events
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_orbit_events

; OK, what time period are we observing?
Self.parentClass->getProperty , tl_graphics = tl_graphics            ,     $
                                obev        = obev

start_time = tl_graphics.axes.x_axis_day_tai
duration   = tl_graphics.axes.x_axis_length
obev       = *obev

IF (N_TAGS(obev[0]) EQ 0) THEN BEGIN

    ; OK, stev_*evt file NOT found
    plot_item , 0.0 , tl_graphics.axes.x_axis_stop , 5 , ''  ,              $
                                           color = 10 , maxcharsize = 2.5
    plot_item , 0.0 , tl_graphics.axes.x_axis_stop , 5 ,                    $
                                          'No Orbit Events data'  ,         $
                                           color = 0 , maxcharsize = 2.5

    RETURN

ENDIF ELSE BEGIN
    ;
    ; Plot Station Events
    ;
    saa_list = WHERE(STRLOWCASE(obev[*].name) EQ 'saa' , saa_count)
    hla_list = WHERE(STRLOWCASE(obev[*].name) EQ 'hla' , hla_count)
    ngt_list = WHERE(STRLOWCASE(obev[*].name) EQ 'ngt' , ngt_count)
    xtw_list = WHERE(STRLOWCASE(obev[*].name) EQ 'xtw' , xtw_count)


    IF (xtw_count GT 0) THEN BEGIN

        ; Extract array of NGT event structures
        xtw = obev[xtw_list]
        FOR i = 0, xtw_count -1 DO BEGIN
            eis_plot_xtw, xtw[i], tl_graphics.axes.x_axis_day_tai , ROW=5
        ENDFOR

    ENDIF

;     IF (ngt_count GT 0) THEN BEGIN
;
;         ; Extract array of NGT event structures
;         ngt = obev[ngt_list]
;         FOR i = 0, ngt_count -1 DO BEGIN
;             eis_plot_ngt, ngt[i], tl_graphics.axes.x_axis_day_tai , ROW=5
;         ENDFOR
;
;     ENDIF

    IF (saa_count GT 0) THEN BEGIN

        ; Extract array of SAA event structures
        saa = obev[saa_list]
        FOR i = 0, saa_count -1 DO BEGIN
            eis_plot_obev, saa[i], tl_graphics.axes.x_axis_day_tai , ROW=5
        ENDFOR

    ENDIF

    IF (hla_count GT 0) THEN BEGIN

        ; Extract array of HLA event structures
        hla = obev[hla_list]
        FOR i = 0, hla_count -1 DO BEGIN
            eis_plot_obev, hla[i], tl_graphics.axes.x_axis_day_tai , ROW=5
        ENDFOR

    ENDIF

ENDELSE

END
;______________________________________________________________________________
; Select Timeline
;______________________________________________________________________________
PRO eis_timeline_plot_gui::initialize_plot , no_refresh = no_refresh

WIDGET_CONTROL , /HOURGLASS

;t0 = SYSTIME(1)

; Retrieve default colour table properties
Self.parentClass->getProperty , o_def_ct = o_def_ct
o_def_ct->getProperty , plotsCT = plotsCT , imageCT = imageCT
;
; Reference Pixmap
;
; Set reference pixmap as current window
WSET , Self.ref_pixID

TVLCT,plotsCT[*,0] , plotsCT[*,1] , plotsCT[*,2] ;PLOT ct
; Plot the axes - to reference pixmap
Self->plotAxes

;
; Cache Pixmap
;
; Set cache pixmap as current window
WSET , Self.cac_pixID
; Copy contents of reference pixmap to cache pixmap
DEVICE , Copy = [ 0 , 0 , Self.xySize[0] , Self.xySize[1] , 0 , 0 , Self.ref_pixID ]

; Plot CPT
Self->plot_cpt
Self->plot_move
Self->plot_copy
Self->plot_meta
Self->plot_dvol
Self->plot_delete

; Plot studies to cache pixmap
Self->plot_timeline_entries


; Plot Station Events to cache pixmap
Self->plot_station_events
; Plot Orbit Events to cache pixmap
Self->plot_orbit_events
; Plot OP Events to cache pixmap
Self->plot_op_events
; Plot Re-Pointing Events to cache pixmap
Self->plot_repointing_events
; Plot cursor_position to cache pixmap
Self->plot_cursor_position , no_refresh = no_refresh

; Set draw widget as current window
WIDGET_CONTROL , Self.drawID , get_value = drawID
WSET , drawID
DEVICE , Copy = [ 0 , 0 , Self.xySize[0] , Self.xySize[1] , 0 , 0 , Self.cac_pixID ]

TVLCT , imageCT[*,0] , imageCT[*,1] , imageCT[*,2] ;IMAGE ct

;PRINT, SYSTIME(1) - t0, ' Seconds to draw graphics'

END
;______________________________________________________________________________
; Select Timeline
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plotAxes , no_data = no_data

charSize = 1.2

Self.parentClass->getProperty ,                                             $
                    tl_graphics            = tl_graphics            ,       $
                    eis_timeline_container = eis_timeline_container

baseTime     = tl_graphics.axes.x_axis_day_tai
tl_timestart = tl_graphics.axes.x_axis_start   ; default = 0.0  (midnight)
tl_timestop  = tl_graphics.axes.x_axis_stop    ; default = 24.0 (hours)

; Print xTitle = "11-Jan-2006 00:00:00" - or whatever
xTitle  = anytim2utc(tl_graphics.axes.x_axis_day_tai,/STIME,/TRUNCATE) + ' (UTC)'


; check which traces to plot
index = WHERE(tl_graphics.axes.y_axis_row[*].on_screen EQ 1, count)
nRows = count

;
; 21-Jun-2010. How many
;
tt_count = eis_timeline_container->get_num_tt_studies(baseTime        ,     $
                                   baseTime+(tl_timestop*3600.))
tt_count_string = STRCOMPRESS(tt_count,/REMOVE_ALL)

;
; 7-Nov-2011 JAR
; Add code to calculate Data Volume on the fly - and report it to TL plot
;
dvol_total = eis_timeline_container->get_dvol(  $
                       start_time = baseTime   ,     $
                       stop_time  = baseTime+(tl_timestop*3600.))

dvol_total_string = STRCOMPRESS(ROUND(dvol_total),/REMOVE_ALL)
WIDGET_CONTROL , Self.dvolLabelID , set_value = dvol_total_string
;---------------------------------------------------------------------------
;  Create ticks
;---------------------------------------------------------------------------
mk_timetick, tl_timestart, tl_timestop, basetime, label=tickname, value=value, $
                   major=major, minor=minor
;---------------------------------------------------------------------------
;  Create plot - with no data
;---------------------------------------------------------------------------

PLOT , [tl_timestart , tl_timestop  ]  ,                                    $
       [0  , nRows] ,                                                       $
                   xTitle    = xTitle ,                                     $
                   xTickname = tickname ,                                   $
                   xTickv    = value  ,                                     $
                   xTicks    = major    ,                                   $
                   xMinor    = minor    ,                                   $
                   xStyle    = 5        ,                                   $
                   xmargin   = [15, 8]  ,                                   $
                   charSize  = charSize ,                                   $
                   color     = 255    ,                                     $
;                   color     = 0    ,                                     $
                   yTicks    = nRows  ,                                     $
                   yTickName = REPLICATE(' ', nrows+1) ,                    $
                   ystyle    = 1        ,                                   $
                   yMargin   = [4,4]    ,                                   $
;                   background = 255, $
                   /NODATA
;---------------------------------------------------------------------------
;  Plot lower X-axis
;---------------------------------------------------------------------------
AXIS, xaxis=0, xstyle=1, xtickname=tickname, xticks=major, $
         xminor=minor, xtitle=xtitle, charsize=charsize, $
         xtickv=value, color=color , ticklen = -0.04

;---------------------------------------------------------------------------
;  Plot upper X-axis
;---------------------------------------------------------------------------
gap      = ROUND(local_diff())
!x.range = !x.range + gap
IF (!x.range(0) LT 0.0) THEN !x.range = !x.range + 24.0

;hours = 4.
;baseTime = baseTime + (hours * 3600.)

;stop
;tl_timestart = 8.
;tl_timestart = 8.

mk_timetick, tl_timestart     ,         $
             tl_timestop      ,         $
             basetime         ,         $
             label = tickname ,         $
             value = value    ,         $
             major = major    ,         $
             minor = minor    ,         $
             /LOCAL


AXIS, xaxis=1, xstyle=1, xtickname=tickname, xticks=major, $
            xminor=minor, xtitle='(Local Time)', charsize=charsize, $
            xtickv=value, color=255 , ticklen = -0.04

;stop

;---------------------------------------------------------------------------
;  draw the lines between rows
;---------------------------------------------------------------------------
dy = !d.y_ch_size * charsize / (3 * !y.s(1) * !d.y_size)

; check which traces to plot
;index = where(tl_graphics.axes.y_axis_row[*].on_screen eq 1, count)
index = reverse(index)
; save row number for each trace
tl_graphics.axes.y_axis_row[*].row = -1
for i = 0, count-1 do begin
    tl_graphics.axes.y_axis_row[index[i]].row = i
endfor
; create y-axis labels
ylabels    = strarr(count)
ylabels[*] = tl_graphics.axes.y_axis_row[index].row_label


; If called by TRACKING_EVENTS (ie: cursor has entered the plot area)
; we don't actually need to plot anything. Bail out!
IF (KEYWORD_SET(no_data) EQ 1) THEN RETURN


FOR i = 0, nRows DO BEGIN
    OPLOT, [tl_timestart, tl_timestop], [i, i], psym=0, linestyle=0, color=color
    xc = tl_timestart
    yc = i - 1 + .5 - dy

    ;IF (i GT 0) THEN XYOUTS, xc, yc, STRCOMPRESS(i,/REMOVE)

    IF (i GT 0) THEN BEGIN
        XYOUTS, xc, yc, align=1,                                            $
                ylabels(i-1)+blank(1),                                      $
                charsize = charsize , color=255
    ENDIF

    IF (i EQ 6) THEN BEGIN

        XYOUTS, tl_timestop + (tl_timestop*.005), yc-.2,                 $
                'SAA',                                      $
                charsize = charsize , color=2

        XYOUTS, tl_timestop + (tl_timestop*.005), yc+.2,                  $
                'XTW',                                      $
                charsize = charsize , color=5
    ENDIF

    IF (i EQ 5) THEN BEGIN

        XYOUTS, tl_timestop + (tl_timestop*.005), yc+.2,                 $
                'USC',                                      $
                charsize = charsize , color=3

        XYOUTS, tl_timestop + (tl_timestop*.005), yc-.2,                  $
                'SVA',                                      $
                charsize = charsize , color=9
    ENDIF

    IF (i EQ 4) THEN BEGIN

        XYOUTS, tl_timestop + (tl_timestop*.005), yc,                 $
                '0', charsize = charsize , color=1

        XYOUTS, tl_timestop + (tl_timestop*.013), yc,                 $
                '1', charsize = charsize , color=2

        XYOUTS, tl_timestop + (tl_timestop*.021), yc,                 $
                '2', charsize = charsize , color=3

        XYOUTS, tl_timestop + (tl_timestop*.029), yc,                 $
                '3', charsize = charsize , color=4

        XYOUTS, tl_timestop + (tl_timestop*.037), yc,                 $
                '4', charsize = charsize , color=5

    ENDIF

    IF (i EQ 3) THEN BEGIN

        XYOUTS, tl_timestop + (tl_timestop*.005), yc+.2,                 $
                'No Go!',                                      $
                charsize = charsize , color=1

        XYOUTS, tl_timestop + (tl_timestop*.005), yc-.2,                  $
                'OP',                                      $
                charsize = charsize , color=2
    ENDIF

    IF (i EQ 2) THEN BEGIN

       ; Is eis_cpt_gui up? If NOT then bail out!
       xy_out = ''
       IF XREGISTERED("eis_cpt_gui")       THEN xy_out = 'CPT'
       IF XREGISTERED("eis_move_tl_gui")   THEN xy_out = 'Move'
       IF XREGISTERED("eis_copy_tl_gui")   THEN xy_out = 'Copy'
       IF XREGISTERED("eis_delete_tl_gui") THEN xy_out = 'Delete'
       XYOUTS, tl_timestop + (tl_timestop*.005), yc,                 $
                xy_out , charsize = charsize , color=9

    ENDIF

ENDFOR

;t0 = SYSTIME(1)

;


; Plot Station Events
Self->plot_station_events
; Plot Orbit Events
Self->plot_orbit_events
; Plot OP Events
Self->plot_op_events
; Plot Re-Pointing Events
Self->plot_repointing_events
; Plot CPT
Self->plot_cpt
Self->plot_move
Self->plot_copy
Self->plot_meta
Self->plot_dvol
Self->plot_delete


;PRINT, SYSTIME(1) - t0, 'Seconds'

END
;______________________________________________________________________________
; Plot Delete time range
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_delete

; Is gui up? If NOT then bail out!
valid_gui = XREGISTERED("eis_delete_tl_gui")
IF (valid_gui NE 1) THEN RETURN

Self.parentClass->getProperty , tl_graphics = tl_graphics            ,     $
                                delete_gui  = delete_gui
;stop
delete_gui->getProperty , start_time = t1
delete_gui->getProperty , stop_time  = t2
IF (t1 EQ 0.) OR (t2 EQ 0.) THEN RETURN
cpt = {name:'delete',start_time:t1,stop_time:t2}
;eis_plot_cpt, cpt , tl_graphics.axes.x_axis_day_tai , row = 0
eis_plot_cpt, cpt , tl_graphics.axes.x_axis_day_tai , row = 1

END
;______________________________________________________________________________
; Plot Copy time range
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_copy

; Is gui up? If NOT then bail out!
valid_gui = XREGISTERED("eis_copy_tl_gui")
IF (valid_gui NE 1) THEN RETURN

Self.parentClass->getProperty , tl_graphics = tl_graphics            ,     $
                                copy_gui    = copy_gui

copy_gui->getProperty , start_time = t1
copy_gui->getProperty , stop_time  = t2
IF (t1 EQ 0.) OR (t2 EQ 0.) THEN RETURN
cpt = {name:'copy',start_time:t1,stop_time:t2}
eis_plot_cpt, cpt , tl_graphics.axes.x_axis_day_tai , row = 1

END
;______________________________________________________________________________
; Plot METADATA time range
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_meta

; Is gui up? If NOT then bail out!
valid_gui = XREGISTERED("eis_meta_tl_gui")
IF (valid_gui NE 1) THEN RETURN

Self.parentClass->getProperty , tl_graphics = tl_graphics            ,     $
                                meta_gui    = meta_gui

meta_gui->getProperty , start_time = t1
meta_gui->getProperty , stop_time  = t2
IF (t1 EQ 0.) OR (t2 EQ 0.) THEN RETURN
cpt = {name:'meta',start_time:t1,stop_time:t2}
eis_plot_cpt, cpt , tl_graphics.axes.x_axis_day_tai , row = 1

END
;______________________________________________________________________________
; Plot DATA Volume time range
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_dvol

; Is gui up? If NOT then bail out!
valid_gui = XREGISTERED("eis_dvol_tl_gui")
IF (valid_gui NE 1) THEN RETURN

Self.parentClass->getProperty , tl_graphics = tl_graphics            ,     $
                                dvol_gui    = dvol_gui

dvol_gui->getProperty , start_time = t1
dvol_gui->getProperty , stop_time  = t2
IF (t1 EQ 0.) OR (t2 EQ 0.) THEN RETURN
cpt = {name:'dvol',start_time:t1,stop_time:t2}
eis_plot_cpt, cpt , tl_graphics.axes.x_axis_day_tai , row = 1

END
;______________________________________________________________________________
; Plot Move time range
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_move

; Is gui up? If NOT then bail out!
valid_gui = XREGISTERED("eis_move_tl_gui")
IF (valid_gui NE 1) THEN RETURN

Self.parentClass->getProperty , tl_graphics = tl_graphics            ,     $
                                move_gui    = move_gui

move_gui->getProperty , start_time = t1
move_gui->getProperty , stop_time  = t2
IF (t1 EQ 0.) OR (t2 EQ 0.) THEN RETURN
cpt = {name:'move',start_time:t1,stop_time:t2}
eis_plot_cpt, cpt , tl_graphics.axes.x_axis_day_tai , row = 1

END
;______________________________________________________________________________
; Draw Events - get cursor position
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_cpt

; Is eis_cpt_gui up? If NOT then bail out!
valid_cpt_gui = XREGISTERED("eis_cpt_gui")
IF (valid_cpt_gui EQ 0) THEN RETURN

Self.parentClass->getProperty , tl_graphics = tl_graphics            ,     $
                                cpt_gui     = cpt_gui

cpt_gui->getProperty , start_time = t1
cpt_gui->getProperty , stop_time  = t2
IF (t1 EQ 0.) OR (t2 EQ 0.) THEN RETURN
cpt = {name:'cpt',start_time:t1,stop_time:t2}
eis_plot_cpt, cpt , tl_graphics.axes.x_axis_day_tai , row = 1

END
;______________________________________________________________________________
; Draw Events - get cursor position
;______________________________________________________________________________
PRO eis_timeline_plot_gui::plot_timeline_entries

;t0 = SYSTIME(1)
;print,' initialising plot'
;
; Plot studies
;
Self.parentClass->getProperty , eis_timeline_container =  tlc    ,          $
                                tl_graphics = tl_graphics


tlc_count  = tlc->count()
IF (tlc_count EQ 0) THEN RETURN
tlc->getProperty , working_position = working_position

; OK, we're doing this calculation in UTC - however, we need to take
; into account any difference in days
start_time_utc = anytim2utc(tl_graphics.axes.x_axis_day_tai)
day_start_mjd  = start_time_utc.mjd
day_start_time = start_time_utc.time
;stop

; Get number of study entries
; OK, loop over each entry and plot it

FOR i = 0 , tlc_count - 1 DO BEGIN


    ; Get object reference
    temp = tlc->get( position   = i)
    temp->getproperty , visible = visible
    IF (visible EQ 1) THEN BEGIN
        ; Get copy of eis_timeline_entry structure
        tl = temp->get()
        ; Need t1, t2, and acronym
        t1 = tl.time_component.start_time
        t2 = tl.time_component.end_time
        ;
        ; Convert t1 & t2 from TAI to hours since display start
        ;
        t1_utc = anytim2utc(t1)
        t1_mjd = t1_utc.mjd
        ; For days, get difference in minutes
        diff_days = t1_mjd  - day_start_mjd
        t1_pos = (t1_utc.time/3600000.) + (24.*diff_days)

        t2_utc = anytim2utc(t2)
        t2_mjd = t2_utc.mjd
        ; For days, get difference in minutes
        diff_days = t2_mjd  - day_start_mjd
        t2_pos = (t2_utc.time/3600000.)+ (24.*diff_days)

        ; IF plan entry starts before the timeline
        IF (t1_pos LT tl_graphics.axes.x_axis_start) THEN BEGIN
            t1_pos =  tl_graphics.axes.x_axis_start
        ENDIF

        ; IF plan entry extends past the timeline
        IF (t2_pos GT tl_graphics.axes.x_axis_stop) THEN BEGIN
            t2_pos =  tl_graphics.axes.x_axis_stop
        ENDIF

        tc = tl.time_component
        sc = tl.science_component

        ; XRT Flare
        xrtFlare_on = sc.xrt_flare_response.respond_to_xrt_flare
        IF (xrtFlare_on EQ 1) THEN BEGIN
            ; Plotting now!
            plot_item, t1_pos , t2_pos , 6 , ''  , color = 2 ,              $
                                                   maxcharsize = 2.5

            plot_item, t1_pos , t2_pos , 6 , 'XRT Flare'  , color = 0 ,     $
                                               maxcharsize = 2.5
        ENDIF

        ; EIS Event
        eisEvent_on = tc.respond_to_eis_event
        IF (eisEvent_on EQ 1) THEN BEGIN
            ; Plotting now!

            ;
            ; JAR 18-Jun-2010
            ; Plot hunter + response study duration in top row

            ; Get Response Study ID - and then its duration
            resp_st_id  = sc.eis_event_response.response_study_id
            ; Open study database
            status      = eis_open_db(/STUDY)
            resp_st_dur = (dbval(resp_st_id , 'DURATION')/1000./60./60.)
            dbclose
            ; Set t3_pos as total duration of both hunter + response studies
            t3_pos      = t2_pos + resp_st_dur

            plot_item, t1_pos , t3_pos , 6 , ''  , color = 2 ,              $
                                                   maxcharsize = 2.5

            plot_item, t1_pos , t3_pos , 6 , 'BPTrigger'  , color = 0 ,     $
                                               maxcharsize = 2.5
        ENDIF

        ; EIS Flare
        eisFlare_on = tc.respond_to_eis_flare
        IF (eisFlare_on EQ 1) THEN BEGIN
            ; Plot hunter + response study duration in top row

            ; Get Response Entry DB ID - and then its duration
            ;
            ; JAR 22-Oct-2010
            resp_id = sc.eis_flare_response.response_study_id
            resp    = db_read_response_entry(id = resp_id)
            IF (resp.response_st_id EQ 0) THEN BEGIN
               ; No response study defined yet.
               t3_pos = t2_pos
            ENDIF ELSE BEGIN

               ; Open study database
               status      = eis_open_db(/STUDY)
               resp_st_dur = (dbval(resp.response_st_id                ,   $
                                      'DURATION')/1000./60./60.)
               dbclose
               ; Set t3_pos as total duration of both hunter + response studies
               t3_pos      = t2_pos + resp_st_dur

            ENDELSE


            plot_item, t1_pos , t3_pos , 6 , ''  , color = 2 ,              $
                                                   maxcharsize = 2.5

            plot_item, t1_pos , t3_pos , 6 , 'EISFLARE'  , color = 0 ,     $
                                               maxcharsize = 2.5
        ENDIF

       ; Print SEQ_ID
        seq_id = STRCOMPRESS(tc.sequence_id,/REMOVE_ALL)
        plot_item, t1_pos , t2_pos , 1 , seq_id  , color = 255 ,     $
                                                   maxcharsize = 2.5


        ; Wot colour?
        CASE tc.time_tagged OF
            0     : color = 4      ; CYAN for NON-time-tagged
            1     : color = 1      ; RED  for time-tagged
            ELSE  : stop           ; oh oh!
        ENDCASE

        ; Engineering Studies
        IF (tc.entry_type EQ 'E') THEN BEGIN

            ; Plotting now!
            plot_item, t1_pos , t2_pos , 6 , ''  , color = 2 ,              $
                                                   maxcharsize = 2.5

            plot_item, t1_pos , t2_pos , 6 , 'ENG'  , color = 0 ,           $
                                                   maxcharsize = 2.5

            color = 2

        ENDIF

        ;
        ; JAR 26-Mar-2007
        ; Recursive/Default Studies
        IF (tc.recursive EQ 1) THEN BEGIN

            ; Plotting now!
            plot_item, t1_pos , t2_pos , 6 , ''  , color = 3 ,              $
                                                   maxcharsize = 2.5

            plot_item, t1_pos , t2_pos , 6 , 'R' , color = 0 ,              $
                                                   maxcharsize = 2.5

            color = 3

        ENDIF



        IF (i EQ working_position) THEN color = 5

        ; Plotting now!
        plot_item, t1_pos , t2_pos , 0 , ''  , color = color ,         $
                                                   maxcharsize = 2.5

        ; Print study acronym
        plot_item, t1_pos , t2_pos , 0 , STRTRIM(tc.acronym , 2)  ,     $
                                        color = 0 , maxcharsize = 2.5

    ENDIF

ENDFOR

;PRINT, SYSTIME(1) - t0, 'Seconds'
;print,'finished plot'

END
;______________________________________________________________________________
; Define Data members
;______________________________________________________________________________
PRO eis_timeline_plot_gui__define

struct = { eis_timeline_plot_gui                         ,     $
               tlbID               : 0L                  ,     $
               group_leader        : 0L                  ,     $
               drawId              : 0L                  ,     $
               ref_pixID           : 0L                  ,     $
               cac_pixId           : 0L                  ,     $
               xySize              : LONARR(2)           ,     $
               parentClass         : OBJ_NEW()           ,     $
               datetime_gui        : OBJ_NEW()           ,     $
               coordsLabelID       : 0L                  ,     $
               dvolLabelID         : 0L                  ,     $
               sot_offsetLabelID   : 0L                  ,     $
               tl_durationID       : 0L                        $
         }

END
