Compile function NDW_GAN_PROD_SPEC_EVENTS(CtrlEntId, Event, @PARAMS)
/***********************************************************************************************************************

    This program is proprietary and is not to be used by or disclosed to others, nor is it to be copied without written
    permission from Infineon.

    Name        :   NDW_GaN_Prod_Spec_Events

    Description :   This function acts as a commuter module for all events related to this window.

    Notes       :   Commuter Modules are automatically called from the Promoted_Events function which is called by the
                    application-specific promoted event handler. This makes it possible to add QuickEvents that need to
                    execute Basic+ logic without having use the Form Designer to make the association, although this is
                    limited to the events which are currently promoted.

                    If the form needs to call the commuter module directly then the QuickEvent parameters should be
                    formatted like this:

                        '@SELF','@EVENT',['@PARAM1','@PARAMx']

    Parameters  :
        CtrlEntId   [in] -- The fully qualified name of the control calling the promoted event
        Event       [in] -- The event being executed. See the Notes section regarding "PRE" events
        Param1-15   [in] -- Additional event parameter holders
        EventFlow  [out] -- Set to 1 or 0 so the calling event knows whether or not to chain forward. See comments in
                            EVENT_SETUP insert               

    History     :   (Date, Initials, Notes)
        12/03/19    djs     Created initial commuter module.
        06/06/20    djs     Cutover to CR-004 and CR-005                                           

***********************************************************************************************************************/
#pragma precomp SRP_PreCompiler
#window NDW_GAN_PROD_SPEC

declare subroutine set_list_box_data, utility, obj_Appwindow, Comm_Prod_Spec_SI, Set_Property, ErrMsg
declare subroutine Database_Services, Start_Window
declare function set_property, fieldcount, center_window, send_event, prod_spec_comm
declare function memberof, SQL_Services, SRP_Array, Datetime, Database_Services, Error_Services
$insert quote_spec_equ
$insert lsl_common
$insert PS_Equates

$INSERT MSG_EQUATES
$INSERT SECURITY_RIGHTS_EQU
$INSERT POPUP_EQUATES
$INSERT LOGICAL
$INSERT RDS_EQU
$INSERT REACT_RUN_EQUATES
$INSERT GAN_PARAMS_EQUATES
$INSERT PROD_SPEC_EQUATES
$INSERT GAN_PARAM_CONFIG_EQUATES

EQU SUB_INFO$	TO 1
EQU EPI_INFO$	TO 2
EQU ADDL_INFO$	TO 3
EQU NEW_DEV$	TO 4
EQU PRE_PROD$	TO 5

//-----------------------------------------------------------------------------
// EVENT HANDLERS
//-----------------------------------------------------------------------------

$insert APP_INSERTS

Declare subroutine Set_Property
Declare function   Get_Property, Form_Services

SubclassInfo    = Form_Services('FindSubclassControl')
Subclass        = SubclassInfo<1>

// The purpose of this line is to prevent the SRP Editor from throwing a warning when compiling.
If Not(Assigned(Param8)) then Param8 = ''

// Update the arguments so that the OpenInsight OLE event will treate the ActiveX event as a native event handler.
If Event EQ 'OLE' then
    Transfer Event to OIEvent
    Transfer Param1 to Event
    Transfer Param2 to Param1
    Transfer Param3 to Param2
    Transfer Param4 to Param3
    Transfer Param5 to Param4
    Transfer Param6 to Param5
    Transfer Param7 to Param6
    Transfer Param8 to Param7
end

GoToEvent Event for CtrlEntId else
    // Event not implemented
end

Return EventFlow or 1

//-----------------------------------------------------------------------------
// EVENT HANDLERS
//-----------------------------------------------------------------------------

Event WINDOW.CREATE(CreateParam)
				
    RDSWarnFlag		= FALSE$
    SpecInstFlag	= FALSE$

    SaveCheckControls = ''

    Set_Property(@WINDOW:'.GROUP_3','ENABLED',0)

    Set_Property(@WINDOW, '@HOLDVAR', CreateParam)

    SubstrateInfo = field( CreateParam, char(244), 1 )
    EpiInfo       = field( CreateParam, char(244), 2 )
    AddlInfo      = field( CreateParam, char(244), 3 )
    NDInfo        = field( CreateParam, char(244), 4 )
    PPInfo        = field( CreateParam, char(244), 5 )

    CONVERT @SVM TO '' IN EpiInfo


    * WE KNOW THAT WE NO LONGER HAVE SEP LAYERS BUT DO ALLOW SAME LAYERS
    * SO COUNT CHAR(248) 

    NumLayers = fieldcount(EpiInfo,char(247))
    FirstLayer    = field( EpiInfo, char(247), 1 )

    ButtonText = Get_Property(@Window:'.SAME_REACTOR_BUTTON', 'TEXT')
    Set_Property(@Window:'.SAME_REACTOR_BUTTON', 'TEXT', fieldcount( FirstLayer, char(248) ):' ':ButtonText)
    FirstLayer = field(FirstLayer,char(248),1)

    Void = set_property( @window, '@CurSepLayer', 1 )
    Void = set_property( @window, '@EpiInfo', EpiInfo )
    Void = set_property( @window, '@OrigEpiInfo', EpiInfo )
    ***********************************************************************
    Controls = 'SUB_ORIENTATION/SUB_TYPE/SUB_WAFERSIZE/SUB_RESISTIVITY/SUB_REST_UNITS/'
    Controls:= 'SUB_DOPANT/SUB_PRE_CLEAN/SUB_BL1_DOPANT/SUB_BL2_DOPANT/'
    Controls:= 'SUB_OXIDE/SUB_POST_CLEAN/SUB_BACKSEAL/SUB_WAFERMFG/SUB_SUBSTRATETYPE/'
    Controls:= 'SUB_INSTRUCTIONS/BLANK_NOT_USED/SUB_WAF_SUP_BY/SPEC_TYPE/SUB_POLISH/SUB_PRODUCTS/'
    *Controls:= 'SUB_BL3_DOPANT/SUB_OXIDE_ANG/PRE_AKRION_RECIPE/POST_AKRION_RECIPE/SUB_THICKNESS'
    Controls:= 'SUB_BL3_DOPANT/SUB_OXIDE_ANG/PRECLEAN_AKRIONRECIPES/POSTCLEAN_AKRIONRECIPES/SUB_THICKNESS'

    * SUB WAFER MFG HAS BEEN MOVED TO THE PSN MAIN WINDOW TO ALLOW MULTIPLE MFGS FOR DIFFERENT SUB PART NUMS
    * 3/6/01 BRYCE MEEK IF ADDING A NEW FIELD TO THIS WINDOW "SUB_WAFERMFG" IS AVAIL JUST RENAME
    * THE CONTROL "SUB_WAFERMFG" ON THE FORM WILL BE SET TO INVISIBLE

    swap '/' with @rm:@window:'.' in Controls
    Controls = @window:'.':Controls
    SaveCheckControls = Controls
    Void = set_property( @window, '@SubControls', Controls )
    SubPromptCnt  = fieldcount( Controls, @rm )
    * so set_property does not propagate
    ValueCnt = fieldcount( SubstrateInfo, @vm )
    if ValueCnt < SubPromptCnt then
       SubstrateInfo := str( @vm, SubPromptCnt-ValueCnt - (SubstrateInfo='') )
    end
    * ok
    if SubstrateInfo<1,QSSubProduct$> = '' then
       * DEFAULT TO SILICON EPI ON THE PRODUCT
       SubstrateInfo<1,QSSubProduct$> = 'SiEpi'   
    end
    if SubstrateInfo<1,QSSubSubstrate$> = '' then
       * DEFAULT TO SILICON FOR THE SUBSTRATE
       SubstrateInfo<1,QSSubSubstrate$> = 'Silicon'
    end
    Void = set_property( @window, '@OrigSubstrateInfo', SubstrateInfo )
    convert @vm to @rm in SubstrateInfo
    Void = set_property( Controls, 'INVALUE', SubstrateInfo )
    ***********************************************************************
    * now load the additional information
    Controls = 'PROVEIN_INST/STRESS_MEASURE/TRANS_MEASURE/STRESS_MIN/'
    Controls:= 'STRESS_MAX/TRANS_SPEC/'

    swap '/' with @rm:@window:'.' in Controls
    Controls = @window:'.':Controls
    SaveCheckControls := @rm:@window:'.PROVEIN_INST':@rm:@window:'.STRESS_MEASURE'
    SaveCheckControls := @rm:@window:'.TRANS_MEASURE':@rm:@window:'.STRESS_MIN'
    SaveCheckControls := @rm:@window:'.STRESS_MAX':@rm:@window:'.TRANS_SPEC'
    Void = set_property( @window, '@AddlControls', Controls )
    AddlPromptCnt  = fieldcount( Controls, @rm )
    * so set_property does not propagate
    ValueCnt = fieldcount( AddlInfo, @vm )
    if ValueCnt < AddlPromptCnt then
       AddlInfo := str( @vm, AddlPromptCnt-ValueCnt - (AddlInfo = '') )
    end
    *
    Void = set_property( @window, '@OrigAddlInfo', AddlInfo )
    convert @vm to @rm in AddlInfo
    Void = set_property( Controls, 'INVALUE', AddlInfo )


    ***********************************************************************			

    * now load the EPI specific prompts

    Controls = 'EPI_CONC_MIN_THICK/EPI_CONC_MAX_THICK/EPI_CONC_UNITS/'
    Controls:= 'EPI_RES_MIN_THICK/EPI_RES_MAX_THICK/EPI_RES_UNITS/EPI_MIN_THICK/'
    Controls:= 'EPI_MAX_THICK/EPI_THICK_UNITS/EPI_DOPANT/EPI_RECIPE/EPI_RECIPE_NAME/'
    Controls:= 'EPI_THICKMEASURE/EPI_RESMEASURE/EPI_CONMEASURE'

    swap '/' with @rm:@window:'.' in Controls
    Controls = @window:'.':Controls
    SaveCheckControls = Controls:@rm:SaveCheckControls
    Void = set_property( @window, '@EpiControls', Controls )

    EpiPromptCnt = fieldcount( Controls, @rm )
    Void = set_property( @window, '@EpiPromptCnt', EpiPromptCnt )
    ValueCnt = fieldcount( FirstLayer, @vm )
    * so set_property does not propagate
    if ValueCnt < EpiPromptCnt then
       FirstLayer := str( @vm, EpiPromptCnt-ValueCnt - (FirstLayer = '') )
    end
    * ok
    convert @vm to @rm in FirstLayer
    Void = set_property( Controls, 'INVALUE':@rm:'INVALUE':@rm:'INVALUE', FirstLayer )
    *Void = set_property( Controls, 'INVALUE', FirstLayer )								;* Changes 1/27/2009 JCH 
    Void = set_property( @window, '@SaveCheckControls', SaveCheckControls )
    Void = set_property( @window, '@SaveCheckControlData', get_property( SaveCheckControls, 'INVALUE' ) )
    *
    ***********************************************************************			
    * now load the new development specific prompts
    Controls = 'ND_INST_OBS/ND_EXP_PLAN/ND_TEST_RESULTS/ND_SPECIAL_INST'
    swap '/' with @rm:@window:'.' in Controls
    Controls = @window:'.':Controls
    Void = set_property( @window, '@NDControls', Controls )
    NDPromptCnt = fieldcount( Controls, @rm )
    Void = set_property( @window, '@NDPromptCnt', NDPromptCnt )
    ValueCnt = fieldcount( NDInfo, @vm )
    * so set_property does not propagate
    if ValueCnt < NDPromptCnt then
       NDInfo := str( @vm, NDPromptCnt-ValueCnt - (NDInfo = '') )
    end
    Void = set_property( @window, '@OrigNDInfo', NDInfo )
    convert @vm to @rm in NDInfo
    Void = set_property( Controls, 'INVALUE', NDInfo )
    ***********************************************************************
    * now load the pre production specific prompts
    Controls = 'PP_INST_OBS/PP_SPECIAL_INST/PP_PROVEIN_INST'
    swap '/' with @rm:@window:'.' in Controls
    Controls = @window:'.':Controls
    Void = set_property( @window, '@PPControls', Controls )
    PPPromptCnt = fieldcount( Controls, @rm )
    Void = set_property( @window, '@PPPromptCnt', PPPromptCnt )
    ValueCnt = fieldcount( PPInfo, @vm )
    * so set_property does not propagate
    if ValueCnt < PPPromptCnt then
       PPInfo := str( @vm, PPPromptCnt-ValueCnt - (PPInfo = '') )
    end
    Void = set_property( @window, '@OrigPPInfo', PPInfo )
    convert @vm to @rm in PPInfo
    Void = set_property( Controls, 'INVALUE', PPInfo )
    ***********************************************************************
    set_list_box_data( @window )

    void = Set_Property(@WINDOW:'.EPI_CONC_UNITS','LIST','cm-3')
    void = Set_Property(@WINDOW:'.EPI_RES_UNITS','LIST','Ãª-cm':@FM:'Ãª/Ãœ')
    void = Set_Property(@WINDOW:'.EPI_THICK_UNITS','LIST','Ã¦m':@FM:'Â')
    
    GoSub Setup_OLE_Controls
    FormSize = '' 
    SRP_Show_Window(@Window, '', 'C', 'C', 1, '', False$, False$, FormSize)
    
End Event


Event WINDOW.CLOSE(CancelFlag)

    Set_Property(@Window:'.OLE_TAB', "OLE.FlickerFree", False$)
    Savewarn = Get_Property(@Window, '@SAVEWARN')
    If Savewarn EQ True$ then
        // Send message
        Message = 'Would you like to save your changes?'
        MsgStruct = ''
        MsgStruct<MTEXT$> = Message
        MsgStruct<MTYPE$> = 'BNYC'
        Response = Msg(@Window, MsgStruct)
        Begin Case
            Case Response EQ 1
                // User clicked yes
                // Save changes
                Response    = Dialog_Box('NDW_VERIFY_USER', @WINDOW, @USER4 : @FM : 'GAN_PARAMETERS')
                Valid       = Response<1>
                If (Valid EQ True$) then
                    GoSub SaveParameters          
                    Eventflow = 1
                end else
                    Eventflow = 0
                end
            Case Response EQ 0
                // User clicked no
                Eventflow = 1
            Case Response EQ Char(27)
                // User click cancel or clicked the escape button
                Eventflow = 0
        End Case
        
    end else
        Eventflow = 1
    end
    
end event


Event WINDOW.OMNIEVENT(Message, Param1, Param2, Param3, Param4)    

    If Message _EQC 'EnableImportButton' then        
        GoSub EnableImportButton
    end
    
end event


Event PUB_PARAM_MANAGER.CLICK()
    
    PSNo = Get_Property('PROD_SPEC.PROD_SPEC_ID', 'TEXT')
    rv = Start_Window('NDW_GAN_PARAM_MANAGER', @Window, PSNo)
    
end event


Event PUB_IMPORT_CP.CLICK()

    GoSub UpdateLimits
    GoSub HideTabs
    GoSub FillDispStageCtrl
    GoSub ColorTabs    
    GoSub EnableSaveButton
    GoSub EnableSavewarn
    GoSub EnableImportButton
    
end event


Event PUB_SAVE.CLICK()

    Response    = Dialog_Box('NDW_VERIFY_USER', @WINDOW, @USER4 : @FM : 'GAN_PARAMETERS')
    Valid       = Response<1>
    If (Valid EQ True$) then
        GoSub SaveParameters
        GoSub ResetColorArrays
        GoSub FillDispStageCtrl
        GoSub DisplayTimestamps
        GoSub EnableImportButton
        Set_Property(@Window, '@SAVEWARN', False$)
        Set_Property(@Window:'.PUB_SAVE', 'ENABLED', False$)
        ParameterList = Get_Property(@Window, '@VALUE_LIST')
        Set_Property(@Window, '@ORIG_VALUE_LIST', ParameterList)
        Set_Property(@Window, '@ORIG_MET_LIST', NewParamNameList)
        GoSub ColorTabs
    end else
        Return 0
    end
    
end event


Event OLE_TAB.SelChanged(Index, PrevIndex)
    
    GoSub FillDispStageCtrl
    
end event


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Internal GoSubs
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Setup_OLE_Controls:

    GoSub SetupTabCtrl
    GoSub SetupDispStageCtrl
    GoSub ReadCurrParams
    GoSub FillDispStageCtrl
    GoSub ColorTabs
    GoSub HideTabs
    GoSub EnableSaveButton
    GoSub EnableImportButton
    GoSub DisplayTimestamps
    
return


ResetColorArrays:
    
    PSNo = Get_Property('PROD_SPEC.PROD_SPEC_ID', 'TEXT')
    PartNo = Get_Property(@Window, '@CURR_PART_NO')
    GaNParamStages = Get_Property(@Window, '@GAN_PARAM_STAGES')
    CellColorArray = ''
    For each Stage in GaNParamStages using @VM setting TabIndex       
        GaNParamConfigKey = PSNo:'*':PartNo:'*':Stage
        GaNParamConfigRec = Database_Services('ReadDataRow', 'GAN_PARAM_CONFIG', GaNParamConfigKey)
        ParamNames        = GaNParamConfigRec<GAN_PARAM_CONFIG.PARAM_NAME$>
        For each ParamName in ParamNames using @VM setting RowPos                             
            CellColorArray<TabIndex, RowPos, 1> = 'None'
            CellColorArray<TabIndex, RowPos, 2> = 'None'
            CellColorArray<TabIndex, RowPos, 3> = 'None'
            CellColorArray<TabIndex, RowPos, 4> = 'None'
            CellColorArray<TabIndex, RowPos, 5> = 'None'            
        Next ParamName                               
    Next Stage
    Set_Property(@Window, '@COLOR_ARRAY', CellColorArray)
    
return


DisplayTimestamps:
    
    PSNo = Get_Property('PROD_SPEC.PROD_SPEC_ID', 'TEXT')
    If PSNo NE '' then
        ProdSpecRec = Database_Services('ReadDataRow', 'PROD_SPEC', PSNo)
        RevCPDTM = ProdSpecRec<PROD_SPEC_GAN_REV_CP_DTM$>
        RevOIDTM = ProdSpecRec<PROD_SPEC_GAN_REV_OI_DTM$>
        RevUser  = ProdSpecRec<PROD_SPEC_GAN_REV_USER$>
        RevCPDTM = OConv(RevCPDTM, 'DT2/^H')
        RevOIDTM = OConv(RevOIDTM, 'DT2/^H')
        Set_Property(@Window:'.TXT_OI_DTM', 'TEXT', RevOIDTM)
        Set_Property(@Window:'.TXT_CP_DTM', 'TEXT', RevCPDTM)
        Set_Property(@Window:'.TXT_USER', 'TEXT', OConv(RevUser, '[XLATE_CONV,LSL_USERS*FIRST_LAST]'))
    end
    
return


SetupTabCtrl:
    
    PSNo = Get_Property('PROD_SPEC.PROD_SPEC_ID', 'TEXT')
    
    PartNos = Xlate('PROD_SPEC', PSNo, 'PROD_VER_EPI_PART_NO', 'X')
    NumPartNos = DCount(PartNos, @VM)
    CurrPartNo = Field(PartNos, @VM, NumPartNos)
    Set_Property(@Window, '@CURR_PART_NO', CurrPartNo)
    GaNParamStages = Xlate('APP_INFO', 'GAN_PARAM_STAGES', '', 'X')
    TabCtrl = @Window:'.OLE_TAB'
    Set_Property(TabCtrl, "OLE.TabCount", 12)
    Convert @VM to ',' in GaNParamStages
    Set_Property(TabCtrl, "OLE.CaptionList", GaNParamStages)
    FontArray = 'Segoe UI':@SVM:9:@SVM:700
    Set_Property(TabCtrl, "OLE.Font", FontArray)
    Set_Property(TabCtrl, "OLE.SelectFont", FontArray)
    
    // Qualify OLE events that we want to intercept
    Qualifier = ''
    Qualifier<1> = 1
    Qualifier<4> = 0 ; * process synchronously (i.e. immediately)
    Send_Message(TabCtrl, 'QUALIFY_EVENT', 'OLE.SelChanged', Qualifier)
    
    Set_Property(TabCtrl, "OLE.FlickerFree", True$)
    
return


UpdateLimits:

    PSNo = Get_Property('PROD_SPEC.PROD_SPEC_ID', 'TEXT')
    If PSNo NE '' then
        CurrDTM = DateTime()
        PartNos = Xlate('PROD_SPEC', PSNo, 'PROD_VER_EPI_PART_NO', 'X')
        NumPartNos = DCount(PartNos, @VM)
        CurrPartNo = Field(PartNos, @VM, NumPartNos)
        If CurrPartNo EQ 'U014' then CurrPartNo = 'G5HTMV675AA'
        Query = "SELECT [Parameter] "                           |
              : ",[LSL] "                                       |
              : ",[Target] "                                    |
              : ",[USL] "                                       |
              : "FROM [ControlPlans].[dbo].[Part_Parameter] "   |
              : "WHERE [Part] = '":CurrPartNo:"' "              |
              : "ORDER BY [Parameter]"
*        Response = SQL_Services_DJS('PostSQLRequest', 'iqsdms1', Query)
        Response = SQL_Services('PostSQLRequest', 'IQSDMS1', Query)
        Convert @FM to @VM in Response
        Convert @RM to @FM in Response

        Response = SRP_Array('Rotate', Response, @FM, @VM)
        ResponseParamList = Response<1>
      
        // Get Control Plan data
        GaNParamKeys = Xlate('PROD_SPEC', PSNo, 'GAN_PARAM_KEYS', 'X')
        Stages = Database_Services('ReadDataRow', 'APP_INFO', 'GAN_PARAM_STAGES', 'X')
        ParameterList = ''
        ParamNameList = ''
        CellColorArray = ''

        For each Stage in Stages using @VM setting TabIndex

            MetType = Stage
            GaNParamConfigKey = PSNo:'*':CurrPartNo:'*':MetType
            GaNParamConfigRec = Database_Services('ReadDataRow', 'GAN_PARAM_CONFIG', GaNParamConfigKey)
            If Error_Services('NoError') then
                ConfigMetNames    = GaNParamConfigRec<GAN_PARAM_CONFIG.MET_NAME$>
                ConfigParams      = GaNParamConfigRec<GAN_PARAM_CONFIG.PARAM_NAME$>
                EnabledArray      = GaNParamConfigRec<GAN_PARAM_CONFIG.ENABLED$>
                CurrVals = Get_Property(@Window, '@ORIG_VALUE_LIST')<TabIndex>
                CurrNames = Get_Property(@Window, '@ORIG_MET_LIST')<TabIndex>
                For each ParamName in ConfigParams using @VM setting RowPos
                    ParamEnabled = EnabledArray<0, RowPos>
                    If ParamEnabled EQ True$ then
                        NextRow = DCount(ParamNameList<TabIndex>, @VM) + 1
                        ParamNameList<TabIndex, NextRow> = ConfigMetNames<0, RowPos>
                        Locate ParamName in CurrNames using @VM setting CurrRow then
                            Locate ParamName in ResponseParamList using @VM setting vPos then      
                                NewLSL     = Response<2, vPos>
                                NewTarget  = Response<3, vPos>
                                NewUSL     = Response<4, vPos>
                                PrevLSL    = CurrVals<0, CurrRow, 1>
                                PrevTarget = CurrVals<0, CurrRow, 2>
                                PrevUSL    = CurrVals<0, CurrRow, 3>
                                
                                If (PrevLSL EQ NewLSL) then
                                    CellColorArray<TabIndex, NextRow, 1> = 'None'
                                end else
                                    CellColorArray<TabIndex, NextRow, 1> = 'Yellow'
                                end
                                If (PrevTarget EQ NewTarget) then
                                    CellColorArray<TabIndex, NextRow, 2> = 'None'
                                end else
                                    CellColorArray<TabIndex, NextRow, 2> = 'Yellow'
                                end
                                If (PrevUSL EQ NewUSL) then
                                    CellColorArray<TabIndex, NextRow, 3> = 'None'
                                end else
                                    CellColorArray<TabIndex, NextRow, 3> = 'Yellow'
                                end
                                
                                ParameterList<TabIndex, NextRow, 1> = NewLSL
                                ParameterList<TabIndex, NextRow, 2> = NewTarget
                                ParameterList<TabIndex, NextRow, 3> = NewUSL
                            end else                                
                                ParameterList<TabIndex, NextRow, 1> = 'None'
                                ParameterList<TabIndex, NextRow, 2> = 'None'
                                ParameterList<TabIndex, NextRow, 3> = 'None'
                            end   
                        end else
                            // New parameter being added
                            Locate ParamName in ResponseParamList using @VM setting vPos then
                                NewLSL     = Response<2, vPos>
                                NewTarget  = Response<3, vPos>
                                NewUSL     = Response<4, vPos>
                                ParameterList<TabIndex, NextRow, 1> = NewLSL
                                ParameterList<TabIndex, NextRow, 2> = NewTarget
                                ParameterList<TabIndex, NextRow, 3> = NewUSL
                                CellColorArray<TabIndex, NextRow, 1> = 'Yellow'
                                CellColorArray<TabIndex, NextRow, 2> = 'Yellow'
                                CellColorArray<TabIndex, NextRow, 3> = 'Yellow'
                            end
                        end
                    end
                                   
                Next ParamName
            end
        Next Stage     
    end
           
    Set_Property(@Window, '@NAME_LIST', ParamNameList)
    Set_Property(@Window, '@VALUE_LIST', ParameterList)
    Set_Property(@Window, '@COLOR_ARRAY', CellColorArray)
       
return


SetupDispStageCtrl:
    
    DispStageCtrl     = @Window:'.OLE_DISP_STAGE_EDT'
    HeaderRowTitles   = 'LSL':@VM:'Target':@VM:'USL'
    DispStageDimArray = 5:@FM:1
    Set_Property(DispStageCtrl, "OLE.Dimension", DispStageDimArray)
    Set_Property(DispStageCtrl, "OLE.TitleList", HeaderRowTitles)
    
    HeaderFontArray   = 'Segoe UI':@SVM:8:@SVM:700
    Set_Property(DispStageCtrl, "OLE.HeaderFont[All; All]", HeaderFontArray)
    HeaderColArray = 180:@FM:True$:@FM:False$:@FM:False$
    Set_Property(DispStageCtrl, "OLE.HeaderColumn[1]", HeaderColArray)
    
    Set_Property(DispStageCtrl, "OLE.HeaderText[1; 1]", "Metrology Limits")
    
    // Disable resizing of columns as there is no need for this on this form
    StageColSize = Get_Property(DispStageCtrl, "OLE.DataColumn[1]")
    StageColSize<1> = 100
    StageColSize<3> = False$
    Set_Property(DispStageCtrl, "OLE.DataColumn[All]", StageColSize)
    Set_Property(DispStageCtrl, "OLE.CellProtection[All; All]", 'Read Only')

return


ReadCurrParams:
    
    PSNo = Get_Property('PROD_SPEC.PROD_SPEC_ID', 'TEXT')
    If PSNo NE '' then
        GaNParamStages = Xlate('APP_INFO', 'GAN_PARAM_STAGES', '', 'X')
        Set_Property(@Window, '@GAN_PARAM_STAGES', GaNParamStages)
        
        GaNParamKeys = Xlate('PROD_SPEC', PSNo, 'GAN_PARAM_KEYS', 'X')
        ParameterList = ''
        ParamNameList = ''
        MetNameList   = ''
        For each GaNParamKey in GaNParamKeys using @VM
            MetType = Field(GaNParamKey, '*', 2)
            Locate MetType in GaNParamStages using @VM setting TabPos then
         
                GaNParamRec = Database_Services('ReadDataRow', 'GAN_PARAMS', GaNParamKey)
                PartNo  = Field(GaNParamKey, '*', 1)
                
                ParamNames = GaNParamRec<GAN_PARAMS.PARAM_NAME$>
                MetNames   = GaNParamRec<GAN_PARAMS.MET_NAME$>
                
                For each ParamName in ParamNames using @VM setting RowPos
                    
                    MetNameList<TabPos, RowPos> = ParamName
                    ParamNameList<TabPos, RowPos> = MetNames<0, RowPos>
                    ParameterList<TabPos, RowPos, 1> = GaNParamRec<GAN_PARAMS.LSL$, RowPos>
                    ParameterList<TabPos, RowPos, 2> = GaNParamRec<GAN_PARAMS.TARGET$, RowPos>
                    ParameterList<TabPos, RowPos, 3> = GaNParamRec<GAN_PARAMS.USL$, RowPos>
                    
                Next ParamName
           
            end        
        Next GaNParamKey
        Set_Property(@Window, '@NAME_LIST', ParamNameList)
        Set_Property(@Window, '@VALUE_LIST', ParameterList)
        Set_Property(@Window, '@ORIG_VALUE_LIST', ParameterList)
        Set_Property(@Window, '@ORIG_MET_LIST', MetNameList)
          
    end
    
return


FillDispStageCtrl:
    
    DispStageCtrl     = @Window:'.OLE_DISP_STAGE_EDT'
    TabCtrl           = @Window:'.OLE_TAB'
    TabIndex          = Get_Property(TabCtrl, 'OLE.SelectedTab')
    HeaderTitles      = Get_Property(@Window, '@NAME_LIST')<TabIndex>
    ParameterList     = Get_Property(@Window, '@VALUE_LIST')<TabIndex>
    CellColorArray    = Get_Property(@Window, '@COLOR_ARRAY')<TabIndex>   
    NumCols           = 3   
    NumRows           = DCount(ParameterList, @VM)
    DispStageDimArray = NumCols:@FM:NumRows
    Set_Property(DispStageCtrl, "OLE.Dimension", DispStageDimArray)
    Convert @VM to @FM in ParameterList
    Convert @SVM to @VM in ParameterList
    Set_Property(@Window:'.OLE_DISP_STAGE_EDT', 'OLE.LIST', ParameterList)
    
    Convert @VM to @FM in HeaderTitles
    Convert @SVM to @VM in HeaderTitles
    For each HeaderTitle in HeaderTitles using @FM setting RowIndex
        Set_Property(DispStageCtrl, "OLE.HeaderText[1; ":RowIndex + 1:"]", HeaderTitle)
    Next HeaderTitle
        
    Set_Property(DispStageCtrl, "OLE.HeaderAlignment[1; 2-":NumRows + 1:"]", 'C':@FM:'L':@FM:'L')
    Set_Property(DispStageCtrl, "OLE.CellAlignment[All; All]", 'C':@FM:'R':@FM:'L')
    Set_Property(DispStageCtrl, "OLE.HeaderAlignment[All; 1]", 'C':@FM:'C':@FM:'L')
    
    GoSub ColorCells
       
return


EnableSaveButton:
    
    ChangeDetected = False$
    OrigVals = Get_Property(@Window, '@ORIG_VALUE_LIST')
    CurrVals = Get_Property(@Window, '@VALUE_LIST')
    ChangeDetected = (OrigVals NE CurrVals)
    Set_Property(@Window:'.PUB_SAVE', 'ENABLED', ChangeDetected)
    
return


EnableImportButton:

    NameList = Get_Property(@Window, '@NAME_LIST')
    ChangeDetected = False$
    PSNo         = Get_Property('PROD_SPEC.PROD_SPEC_ID', 'TEXT')
    CurrPartNo   = Get_Property(@Window, '@CURR_PART_NO')
    Stages       = Get_Property(@Window, '@GAN_PARAM_STAGES')
    DataToImport = False$
    For each Stage in Stages using @VM setting TabIndex
        ThisNameList = NameList<TabIndex>
        GaNParamConfigKey = PSNo:'*':CurrPartNo:'*':Stage
        GaNParamConfigRec = Database_Services('ReadDataRow', 'GAN_PARAM_CONFIG', GaNParamConfigKey)
        If Error_Services('NoError') then
            MetNames     = GaNParamConfigRec<GAN_PARAMS.MET_NAME$>
            EnabledArray = GaNParamConfigRec<GAN_PARAM_CONFIG.ENABLED$>
            If MetNames NE '' then
                For each MetName in MetNames using @VM setting vPos
                    Enabled = EnabledArray<0, vPos>
                    If Enabled EQ True$ then
                        Locate MetName in ThisNameList using @VM setting nPos else
                            ChangeDetected = True$
                        end
                    end else
                        Locate MetName in ThisNameList using @VM setting nPos then
                            ChangeDetected = True$
                        end
                    end
                Until ChangeDetected EQ True$
                Next MetName
            end
        end
    Until ChangeDetected EQ True$
    Next Stage
    Set_Property(@Window:'.PUB_IMPORT_CP', 'ENABLED', ChangeDetected)
        
return


ColorCells:

    DispStageCtrl = @Window:'.OLE_DISP_STAGE_EDT'
    DimArray      = Get_Property(DispStageCtrl, "OLE.Dimension")
    NumCols       = DimArray<1>
    NumRows       = DimArray<2>
    For Row = 1 to NumRows
         For Col = 1 to NumCols
             CellColor = CellColorArray<0, Row, Col> 
             Set_Property(DispStageCtrl, 'OLE.CellColors[':Col:';':Row:']', @FM:CellColor)
         Next Col
    Next Row
    
return


ColorTabs:
    
    ChangeDetected = False$
    OrigVals = Get_Property(@Window, '@ORIG_VALUE_LIST')
    CurrVals = Get_Property(@Window, '@VALUE_LIST')
    GaNParamStages = Get_Property(@Window, '@GAN_PARAM_STAGES')
    For each Stage in GaNParamStages using @VM setting TabIndex
        ThisOrigVals = OrigVals<TabIndex>
        ThisCurrVals = CurrVals<TabIndex>
        GoSub ColorTab
    Next Stage
    
return


HideTabs:

    SelTabIndex    = Get_Property(@Window:".OLE_TAB", "OLE.SelectedTab")
    GaNParamStages = Get_Property(@Window, '@GAN_PARAM_STAGES')
    NameArray      = Get_Property(@Window, '@NAME_LIST')
    For each Stage in GaNParamStages using @VM setting TabIndex
        ThisNameArray = NameArray<TabIndex>
        GoSub HideTab
    Next Stage
    
    SelTabVisible = Get_Property(@Window:'.OLE_TAB', 'OLE.TabVisible[':SelTabIndex:']')
    If SelTabVisible EQ False$ then
        For TabIndex = 1 to 12
            TabVisible = Get_Property(@Window:'.OLE_TAB', 'OLE.TabVisible[':TabIndex:']')        
        Until TabVisible EQ True$
        Next TabIndex
        If TabVisible EQ True$ then Set_Property(@Window:".OLE_TAB", "OLE.SelectedTab", TabIndex)
    end
    
return


HideTab:

    If ThisNameArray EQ '' then
        Set_Property(@Window:'.OLE_TAB', 'OLE.TabVisible[':TabIndex:']', False$)
    end else
        Set_Property(@Window:'.OLE_TAB', 'OLE.TabVisible[':TabIndex:']', True$) 
    end
    
return


ColorTab:

    ChangeDetected = (ThisOrigVals NE ThisCurrVals)
    If ChangeDetected EQ False$ then
        Colors = ""
        Colors<1, 2> = "None"
        Colors<2, 2> = "None"
        Colors<3, 2> = "None"
        Colors<4, 1> = "None"
        Colors<4, 2> = "None"
        Colors<5>    = "None"
        Set_Property(TabCtrl, "OLE.TabColors[":TabIndex:"]", Colors)
    end else
        Colors = ""
        Colors<1, 2> = "Vertical(Gradient(Yellow L=80, Yellow L=90), Border(Yellow))"
        Colors<2, 2> = "Vertical(Gradient(Yellow L=90, Yellow L=95), Border(Yellow))"
        Colors<3, 2> = "Vertical(Gradient(Yellow L=85, Yellow L=95), Border(Yellow))"
        Colors<4, 1> = "Gray"
        Colors<4, 2> = "Vertical(Gradient(Gray L=80, Gray L=90), Border(Gray))"
        Colors<5>    = "Vertical(Gradient(Yellow L=95, Yellow L=80), Border(Yellow))"
        Set_Property(TabCtrl, "OLE.TabColors[":TabIndex:"]", Colors)
    end
    
return


EnableSavewarn:
    
    OrigVals = Get_Property(@Window, '@ORIG_VALUE_LIST')
    CurrVals = Get_Property(@Window, '@VALUE_LIST')
    ChangeDetected = (OrigVals NE CurrVals)
    Set_Property(@Window, '@SAVEWARN', ChangeDetected)
    
return


SaveParameters:
    
    PSNo   = Get_Property('PROD_SPEC.PROD_SPEC_ID', 'TEXT')        
    PartNo = Get_Property(@Window, '@CURR_PART_NO')
    If ( (PSNo NE '') and (PartNo NE '') ) then
        CurrDTM = DateTime()      
        // Get Control Plan data
        NewGaNParamKeys = ''
        ProdSpecRec     = Database_Services('ReadDataRow', 'PROD_SPEC', PSNo)
        GaNParamKeys    = ProdSpecRec<PROD_SPEC_GAN_PARAM_KEYS$>
        GaNParamStages  = Database_Services('ReadDataRow', 'APP_INFO', 'GAN_PARAM_STAGES')
        NewParamNameList = ''
        
        For each GaNParamStage in GaNParamStages using @VM setting TabIndex
            MetType           = GaNParamStage
            GaNParamConfigKey = PSNo:'*':PartNo:'*':MetType
            GaNParamConfigRec = Database_Services('ReadDataRow', 'GAN_PARAM_CONFIG', GaNParamConfigKey)
            MetNames          = GaNParamConfigRec<GAN_PARAM_CONFIG.MET_NAME$>
            ParamNames        = GaNParamConfigRec<GAN_PARAM_CONFIG.PARAM_NAME$>
            HeaderTitles      = Get_Property(@Window, '@NAME_LIST')<TabIndex>
            ParameterList     = Get_Property(@Window, '@VALUE_LIST')<TabIndex>

            If ParameterList NE '' then                   
                // Create new GaN Param record.
                GaNParamRec = ''
                For each ParamName in HeaderTitles using @VM setting RowPos
                    Locate ParamName in MetNames using @VM setting vPos then
                        NewParamNameList<TabIndex, RowPos>          = ParamNames<0, vPos>
                        GaNParamRec<GAN_PARAMS.MET_NAME$, RowPos>   = MetNames<0, vPos>
                        GaNParamRec<GAN_PARAMS.PARAM_NAME$, RowPos> = ParamNames<0, vPos>
                        GaNParamRec<GAN_PARAMS.LSL$, RowPos>        = ParameterList<0, RowPos, 1>
                        GaNParamRec<GAN_PARAMS.TARGET$, RowPos>     = ParameterList<0, RowPos, 2>
                        GaNParamRec<GAN_PARAMS.USL$, RowPos>        = ParameterList<0, RowPos, 3>
                    end
                Next ParamName
                
                NewGaNParamKey = PartNo:'*':MetType:'*':CurrDTM
                NewGaNParamKeys<0, -1> = NewGaNParamKey
                Database_Services('WriteDataRow', 'GAN_PARAMS', NewGaNParamKey, GaNParamRec, True$, False$, True$)
            end
        
        Next GaNParamStage    
        
        Query = "SELECT [Stamp] "                               |
              : "FROM [ControlPlans].[dbo].[Part_Parameter] "   |
              : "WHERE [Part] = 'U012' "                        |
              : "GROUP BY [Stamp]"
        
*        ControlPlanDTM = SQL_Services_DJS('PostSQLRequest', 'iqsdms1', Query)
        ControlPlanDTM = SQL_Services('PostSQLRequest', 'IQSDMS1', Query)
        ControlPlanDTM[-3, 1] = ''
        ControlPlanDTM = IConv(ControlPlanDTM, "DT")
        
        ProdSpecRec<PROD_SPEC_GAN_PARAM_KEYS$> = NewGaNParamKeys
        ProdSpecRec<PROD_SPEC_GAN_REV_CP_DTM$> = ControlPlanDTM
        ProdSpecRec<PROD_SPEC_GAN_REV_OI_DTM$> = CurrDTM
        ProdSpecRec<PROD_SPEC_GAN_REV_USER$>   = @User4 
        Database_Services('WriteDataRow', 'PROD_SPEC', PSNo, ProdSpecRec, True$, False$, True$)
    end
    
return


