# $Revision$ on $Date$
# The above revision line needs to be the first line for all techtk files
# Copyright (c) 2006 Ansys Inc
#----------------------------------------------------------------------------
#
# PADT---------------------------------------------------- Phoenix Analysis &
#                                                         Design Technologies
#
#----------------------------------------------------------------------------
#
#       Package: AI-Environment GUI Management
#
#
#          File: builder.tcl
#
#
#     Developer: Matt Sutton
#
#
#   Description: This file defines the basic routines used to construct the
#                GUI from the tree representation.  The algorithm involves
#                a depth first traversal of the GUI tree where each node is
#                visited twice; once upon entering and once upon leaving.
#                Visiting each node in the tree at two different points in the
#                traversal allows for maximum flexability while constructing
#                the GUI.
#
#
#  Example Tree:
#                             Root
#                            /    \
#                           /      \
#                      Child_1     Child_2
#
#
#      Traversal 
#         Order: 1. enterRoot
#                2. enterChild_1
#                3. leaveChild_1
#                4. enterChild_2
#                5. leaveChild_2
#                6. leaveRoot
#
#   
#
#      03/25/02: Demo release 1. Limited/partial widget support. 
#                Limited error checking.
#
#           
#           
#
#-----------------------------------------------------------------------------
# For support: 1-480-813-4884 ext. 125 -or- matt.sutton@padtinc.com
#-----------------------------------------------------------------------------


namespace eval ::AIEnv::GUIManagement {
	
}
   

proc ::AIEnv::GUIManagement::SetDefaultGUIParameters {} {
    variable GUIDisplayData
    variable BuildContext
    variable CATRootDir
    variable GUIZones
    variable IconDir
    variable SmallScreen
    
    global tcl_platform
	global bigfont normalfont smallfont
	global italicfont nonboldfont boldfont
	global fixedfont fixedboldfont fixednonboldfont
	global smallnonboldfont normalnonboldfont bignonboldfont
	global icon_size1 icon_size2 mess_frame

	# must set aie_SurfStyle(wire) for #53965;
	set ::aie_SurfStyle(wire) 1

	::compute_sizes
	
	set fam [font actual $smallfont -family]
	set ssize [font actual $smallfont -size]
	set smallnonboldfont [font create -family $fam -size $ssize]
	set fam [font actual $normalfont -family]
	set nsize [font actual $normalfont -size]
	if {$nsize <= $ssize} { set nsize [expr $nsize + 2] }	
	set normalnonboldfont [font create -family $fam -size $nsize]
	set fam [font actual $bigfont -family]
	set bsize [font actual $bigfont -size]
	if {$bsize <= $nsize} { set bsize [expr $bsize + 2] }
	set bignonboldfont [font create -family $fam -size $bsize]

	set GUIDisplayData("ToolBarSeparatorPadx") 4
	set GUIDisplayData("IconButtonBorderWidth") 1
	set GUIDisplayData("IconButtonPadx") 1
	set GUIDisplayData("IconButtonPady") 1
	set GUIDisplayData("ButtonBoxSpacing") 0
	set GUIDisplayData("ButtonBoxPadx") 0
	set GUIDisplayData("ButtonBoxPady") 0
	set GUIDisplayData("TabbedIconBarInternalBorderwidth") 3
	set GUIDisplayData("TabbedIconBarHeight") 24
	if {$tcl_platform(platform) == "unix"} {
	   set GUIDisplayData("ButtonWidth") 4
	} else {
	   set GUIDisplayData("ButtonWidth") 8
	}
	if {$SmallScreen == 1} {
	   set GUIDisplayData("TreeFont") $nonboldfont
	   set GUIDisplayData("DefaultFont") $nonboldfont
	   set GUIDisplayData("TabFont") $boldfont
	   set GUIDisplayData("MenuFont") $nonboldfont
  	   set GUIDisplayData("MenuBarFont") $boldfont
	   set GUIDisplayData("DEZTitleFont") $boldfont
	   set GUIDisplayData("LabelFont") $nonboldfont
	   set GUIDisplayData("EntryFont") $nonboldfont
	   set GUIDisplayData("ButtonFont") $nonboldfont
	   set GUIDisplayData("ButtonBoldFont") $boldfont
	   set GUIDisplayData("CheckButtonFont") $nonboldfont
	   set GUIDisplayData("RadioButtonFont") $nonboldfont
       set GUIDisplayData("BubbleFont") $nonboldfont
       set GUIDisplayData("HistoBigFont") $boldfont
       set GUIDisplayData("HistoSmallFont") $nonboldfont
	   set GUIDisplayData("MultiSelectFont") $boldfont
       set GUIDisplayData("AboutBigFont") $boldfont
	} else {
        if {$icon_size1 == "24" && $icon_size2 == "35"} {
            set GUIDisplayData("TreeFont") $smallnonboldfont
	        set GUIDisplayData("DefaultFont") $smallnonboldfont
	        set GUIDisplayData("TabFont") $smallnonboldfont
	        set GUIDisplayData("MenuFont") $smallnonboldfont
  	        set GUIDisplayData("MenuBarFont") $smallnonboldfont
	        set GUIDisplayData("DEZTitleFont") $smallfont
	        set GUIDisplayData("LabelFont") $smallnonboldfont
	        set GUIDisplayData("EntryFont") $smallnonboldfont
	        set GUIDisplayData("ButtonFont") $smallnonboldfont
	        set GUIDisplayData("ButtonBoldFont") $smallfont
	        set GUIDisplayData("CheckButtonFont") $smallnonboldfont
	        set GUIDisplayData("RadioButtonFont") $smallnonboldfont
            set GUIDisplayData("BubbleFont") $smallnonboldfont
            set GUIDisplayData("HistoBigFont") $normalfont
            set GUIDisplayData("HistoSmallFont") $smallnonboldfont
	        set GUIDisplayData("MultiSelectFont") $smallfont
            set GUIDisplayData("AboutBigFont") $bigfont
        }
        if {$icon_size1 == "35" && $icon_size2 == "35"} {
            set GUIDisplayData("TreeFont") $normalnonboldfont
            set GUIDisplayData("DefaultFont") $normalnonboldfont
	        set GUIDisplayData("TabFont") $normalnonboldfont
	        set GUIDisplayData("MenuFont") $normalnonboldfont
  	        set GUIDisplayData("MenuBarFont") $normalnonboldfont
	        set GUIDisplayData("DEZTitleFont") $normalfont
	        set GUIDisplayData("LabelFont") $normalnonboldfont
	        set GUIDisplayData("EntryFont") $normalnonboldfont
	        set GUIDisplayData("ButtonFont") $normalnonboldfont
	        set GUIDisplayData("ButtonBoldFont") $normalfont
	        set GUIDisplayData("CheckButtonFont") $normalnonboldfont
	        set GUIDisplayData("RadioButtonFont") $normalnonboldfont
            set GUIDisplayData("BubbleFont") $normalnonboldfont
            set GUIDisplayData("HistoBigFont") $normalfont
            set GUIDisplayData("HistoSmallFont") $smallfont
	        set GUIDisplayData("MultiSelectFont") $normalnonboldfont
            set GUIDisplayData("AboutBigFont") $bigfont
        }
        if {$icon_size1 == "35" && $icon_size2 == "48"} {
            set GUIDisplayData("TreeFont") $bignonboldfont
            set GUIDisplayData("DefaultFont") $normalfont
	        set GUIDisplayData("TabFont") $bignonboldfont
	        set GUIDisplayData("MenuFont") $normalnonboldfont
  	        set GUIDisplayData("MenuBarFont") $bignonboldfont
	        set GUIDisplayData("DEZTitleFont") $bignonboldfont
	        set GUIDisplayData("LabelFont") $normalnonboldfont
	        set GUIDisplayData("EntryFont") $normalnonboldfont
	        set GUIDisplayData("ButtonFont") $normalnonboldfont
	        set GUIDisplayData("ButtonBoldFont") $normalfont
	        set GUIDisplayData("CheckButtonFont") $normalnonboldfont
	        set GUIDisplayData("RadioButtonFont") $normalnonboldfont
            set GUIDisplayData("BubbleFont") $normalnonboldfont
            set GUIDisplayData("HistoBigFont") $bignonboldfont
            set GUIDisplayData("HistoSmallFont") $normalfont
	        set GUIDisplayData("MultiSelectFont") $normalnonboldfont
            set GUIDisplayData("AboutBigFont") $bigfont
        }
	}
    $mess_frame.text configure -font $GUIDisplayData("DefaultFont")
    $mess_frame.bot.log configure -font $GUIDisplayData("DefaultFont")
    $mess_frame.bot.save configure -font $GUIDisplayData("DefaultFont")
    $mess_frame.bot.clear configure -font $GUIDisplayData("DefaultFont")
    $GUIZones("StatusMessageZone") configure -font $GUIDisplayData("DefaultFont")
    set top_tree [set ::AIEnv::GUIManagement::Tree::aieTree]
    $top_tree itemconfigure modelNode -font $GUIDisplayData("TreeFont")
	set GUIDisplayData("FixedTextFont") $fixednonboldfont

	if {$SmallScreen == 1} {
	    set GUIDisplayData("DEZTitleWrapLength") 140
        set GUIDisplayData("ColumnMultiSelectWrapLength") 95
        set GUIDisplayData("CheckLabelWrapLength") 140
        set GUIDisplayData("LabelWrapLength") 140
	    set GUIDisplayData("RadioWrapLength") 105
	} else {
        if {$icon_size1 == "24" && $icon_size2 == "35"} {
            set GUIDisplayData("DEZTitleWrapLength") 220
            set GUIDisplayData("ColumnMultiSelectWrapLength") 125
            set GUIDisplayData("CheckLabelWrapLength") 185
            set GUIDisplayData("LabelWrapLength") 185
	        set GUIDisplayData("RadioWrapLength") 145
        }
        if {$icon_size1 == "35" && $icon_size2 == "35"} {
            set GUIDisplayData("DEZTitleWrapLength") 220
            set GUIDisplayData("ColumnMultiSelectWrapLength") 125
            set GUIDisplayData("CheckLabelWrapLength") 185
            set GUIDisplayData("LabelWrapLength") 185
	        set GUIDisplayData("RadioWrapLength") 145
        }
        if {$icon_size1 == "35" && $icon_size2 == "48"} {
            set GUIDisplayData("DEZTitleWrapLength") 220
            set GUIDisplayData("ColumnMultiSelectWrapLength") 125
            set GUIDisplayData("CheckLabelWrapLength") 185
            set GUIDisplayData("LabelWrapLength") 185
	        set GUIDisplayData("RadioWrapLength") 145
        }
	}
	
	if {$SmallScreen != 1 && [aie_wb2_is_running]} {
	    if {$icon_size1 == "24" && $icon_size2 == "35"} {
	        set incrLen 50
	    }
	    if {$icon_size1 == "35" && $icon_size2 == "35"} {
	        set incrLen 25
	    }
	    if {$icon_size1 == "35" && $icon_size2 == "48"} {
	        set incrLen 0
	    }
	    if [info exists incrLen] {
	        incr GUIDisplayData("DEZTitleWrapLength") $incrLen
	        incr GUIDisplayData("ColumnMultiSelectWrapLength") $incrLen
	        incr GUIDisplayData("CheckLabelWrapLength") $incrLen
	        incr GUIDisplayData("LabelWrapLength") $incrLen
	        incr GUIDisplayData("RadioWrapLength") $incrLen
	    }
	}

	if {$SmallScreen == 1 || ![aie_wb2_is_running]} {
        set GUIDisplayData("NumberofEntryinGroupRow") 5
	} else {
        if {$icon_size1 == "24" && $icon_size2 == "35"} {
            set GUIDisplayData("NumberofEntryinGroupRow") 7
        }
        if {$icon_size1 == "35" && $icon_size2 == "35"} {
            set GUIDisplayData("NumberofEntryinGroupRow") 6
        }
        if {$icon_size1 == "35" && $icon_size2 == "48"} {
            set GUIDisplayData("NumberofEntryinGroupRow") 5
        }
	} 
	
	set GUIDisplayData("NumberofEntryinGroupRow") 5
	
	set GUIDisplayData("ButtonHeight") 1
	set GUIDisplayData("ButtonPad") 4
	set GUIDisplayData("DEZRowHeight") 25
	set GUIDisplayData("DEZPadx") 4
	set GUIDisplayData("DEZPady") 4
	set GUIDisplayData("ImageSize") 24
	set GUIDisplayData("LabelJustify") right
	set GUIDisplayData("RadioJustify") left
	set GUIDisplayData("MenuTearOffEnable") 0
	set GUIDisplayData("ToolbarSeparatorWidth") 12
	set GUIDisplayData("ToolbarSeparatorPadding") 3
	set GUIDisplayData("TextEntryWidth") 8

    set IconDir "icons"
    set BuildContext ""
    set GUIDisplayData("UseIconsInTabZone") 1
    set GUIDisplayData("UseTabIcons") 0
    set GUIDisplayData("UseIconsInCommonZone") 1
    set GUIDisplayData("IconButtonRelief") link 
    set GUIDisplayData("TextIconButtonRelief") raised
    set GUIDisplayData("NormalBackground") white

    set GUIDisplayData("DisabledBackground") grey
    
    ComputeIconButtonDimensions
    option add *font $GUIDisplayData("DefaultFont")

    DynamicHelp::configure -font $GUIDisplayData("BubbleFont")
 #  $GUIZones("MenuZone") configure -font $GUIDisplayData("MenuBarFont")

#    set GUIDisplayData("GUIBackground") gray90
#    set GUIDisplayData("GUIBackground")  [$GUIZones("TabbedIconZone") cget -background]
    set GUIDisplayData("GUIBackground")  [. cget -background]
    option add *background $GUIDisplayData("GUIBackground")
# Sunken with white does not look good with transparent icons. If icons
# are not transparent, grey50 should be good.
#    set GUIDisplayData("SunkenBackground") white
    set GUIDisplayData("SunkenBackground") $GUIDisplayData("GUIBackground")


#  Following needs special attention otherwise they turn grey with above
#  setting
    option add *Entry.background white
    option add *Text.background white
    option add *Listbox.background white
    option add *canvas.background white

#    option add *Dialog.background $GUIDisplayData("GUIBackground")
#    $GUIZones("MenuZone") configure -background $GUIDisplayData("GUIBackground")
#    $GUIZones("IconZone") configure -background $GUIDisplayData("GUIBackground")
#    $GUIZones("TabbedIconZone") configure -background $GUIDisplayData("GUIBackground")
#    $GUIZones("DataEntryZone") configure -background $GUIDisplayData("GUIBackground")
#    $GUIZones("PopupZone") configure -background $GUIDisplayData("GUIBackground")

    # Force all text to be black
    foreach t {Entry Listbox Text Label Menubutton Menu Checkbutton Radiobutton} {
        option add *$t.foreground black
    }
}

   
proc ::AIEnv::GUIManagement::BuildGUI {} {
    global BuildProgressValue
    global BuildProgressIndicator
    global BuildProgressStage
    global AppName Version
    global use_workbench
    global BuildProgressValueMax

    variable ExcludedTypes
    set ExcludedTypes ""
    lappend ExcludedTypes "WizardColumnRoot"
    if {![info exists use_workbench]} {
        ShowBuildProgress
    }
    
    struct::stack ExcludedNodeStack

    set BuildProgressValueMax [expr 2 * [MainTree size]]
    if {![info exists use_workbench]} {
        set BuildProgressValue 0
        if {[info exists BuildProgressIndicator] && \
            [winfo exist $BuildProgressIndicator]} {
            $BuildProgressIndicator configure -type normal \
		-maximum $BuildProgressValueMax
        }
	
        if {[info exists BuildProgressStage] && \
            [winfo exist $BuildProgressStage]} {
            $BuildProgressStage configure -text \
                  "Initializing $AppName $Version: Building the User Interface..."
            update
        }
    }
    
    SetDefaultGUIParameters
    
    TreeStack push MainTree 
    MainTree walk "root" -order both -type dfs -command "BuildGUIItem %n %a" 
	TreeStack pop
     
    ExcludedNodeStack destroy
}

proc ::AIEnv::GUIManagement::BuildSubcomponent {} {
	set Tree [TreeStack peek_one]
	$Tree walk "root" -order both -type dfs -command "BuildSubcomponentItem %n %a"
}

proc ::AIEnv::GUIManagement::BuildSubcomponentItem {NodeID Action} {
	set Tree [TreeStack peek_one]
	set Type [$Tree get $NodeID -key "Type"]
	eval "::AIEnv::GUIManagement::${Action}${Type}Build $NodeID"	
}

proc ::AIEnv::GUIManagement::BuildGUIItem {NodeID Action} {
	variable ExcludedTypes
	global BuildProgressValue
	global BuildProgressValue
        global CurBuildProgressValue
	global BuildProgressValueMax

    	#don't update frequently - Ganesan 
    	if {[expr $CurBuildProgressValue - $BuildProgressValue] > [expr $BuildProgressValueMax/20]} {
		set BuildProgressValue $CurBuildProgressValue
    	}
    	incr CurBuildProgressValue

	set GUITree [TreeStack peek_one]
	
    set Type [$GUITree get $NodeID -key "Type"]
    # Because of the syntax of some widgets, such as the wizard, we
    # have to avoid certain branches of the tree during the main build
    # process. These branches are processed in a unique order by the 
    # specified widget
    if { [lsearch $ExcludedTypes $Type] == -1 } {
    	if { [ExcludedNodeStack size] == 0 } {
    		eval "::AIEnv::GUIManagement::${Action}${Type}Build $NodeID"
		}
	} else {
		switch $Action {
			enter {
				ExcludedNodeStack push $NodeID
			}
			leave {
				ExcludedNodeStack pop
			}
		}
	}
}

#-------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterRootBuild {NodeID} {
	# Intentionally empty
}

proc ::AIEnv::GUIManagement::leaveRootBuild {NodeID} {
	# Intentionally empty
}

#-------------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterDataEntryZoneBuild {NodeID} {
   
}

proc ::AIEnv::GUIManagement::leaveDataEntryZoneBuild {NodeID} {
   
}


#-------------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterTextEntryBuild {NodeID} {
    variable GUIDisplayData
    
    set GUITree [TreeStack peek_one]
    set RowParent [DEZInsert 1]
    set Row [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]

    # Create the label
    set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"] -font $GUIDisplayData("LabelFont") \
		   -wraplength $GUIDisplayData("LabelWrapLength") -justify $GUIDisplayData("LabelJustify") ]
    # Create the variable name in the proper namespace
    set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
    set type [$GUITree get $NodeID -key "EntryType"]
    if {$type == "READONLY"} {
	    set Text [label $Parent.$NodeID-text -textvariable $VariableName -relief sunken -font $GUIDisplayData("EntryFont")]
    } elseif {$type == "INVISIBLE"} {
	    set Text [label $Parent.$NodeID-text -textvariable $VariableName -relief flat]
		$Text configure -foreground [$Text cget -background] -activebackground [$Text cget -background] -activeforeground [$Text cget -background] \
		    -disabledforeground $GUIDisplayData("DisabledBackground")
    } else {
	    set Text [entry $Parent.$NodeID-text -textvariable $VariableName \
		      -font $GUIDisplayData("EntryFont") -foreground black -background white -width $GUIDisplayData("TextEntryWidth")]
        if [aie_wb2_is_running] {
            if [aie_wb2_is_input_parameter [aie_get_global current_wb_input_name] [GetObject] [$GUITree get $NodeID -key "Label"]] {
                set Button [button $Parent.$NodeID-btn -height $GUIDisplayData("ButtonHeight") -font $GUIDisplayData("ButtonBoldFont") \
                    -relief ridge -bg white -activebackground white -activeforeground white]
                set title [aie_get_global current_wb_input_parameter]
                if {$title == "___NA___" || [aie_wb2_nonvalid_input_title $title]} {
                    set title [$GUITree get node1 -key "Title"]
                }
                if {[GetObject] == "mParamsDEZ" && $title == "Edge Params"} {
                    aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Edge Params: [$GUITree get $NodeID -key "Label"]]
                } elseif {[GetObject] == "mszCurveDEZ" && $title == "Curve Mesh Setup"} {
                    aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Curve Mesh Setup: [$GUITree get $NodeID -key "Label"]]
                } elseif {[GetObject] == "mszSurfDEZ" && $title == "Surface Mesh Setup"} {
                    aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Surface Mesh Setup: [$GUITree get $NodeID -key "Label"]]
                } elseif {[GetObject] == "modifyDensityDEZ" && $title == "Modify Density"} {
                    aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Modify Density: [$GUITree get $NodeID -key "Label"]]
                } elseif {[GetObject] == "moveBVertexDEZ" && $title == "Set Location"} {
                    aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Set Location: [$GUITree get $NodeID -key "Label"]]
                }
			    $Button configure -command "aie_wb2_parameter_dialog $NodeID $Button [GetObject] [list $title]"
			    bubble_define $Button "Create/Delete Workbench Input Parameter"
			    set wb2_is_running 1
			}
        }
        $Text configure -validate key -validatecommand "::AIEnv::GUIManagement::validateTextEntryInput $NodeID $Text %P"
	    bind $Text <Key-Return> "[GetObject] apply"
    }
    
    if [info exists wb2_is_running] {
        grid configure $Label -row $Row -column 0 -sticky e
        if {$type != "INVISIBLE"} {
            grid configure $Text -row $Row -column 1 -columnspan 2 -sticky ew -padx $GUIDisplayData("DEZPadx")
        }
        grid configure $Button -row $Row -column 2 -sticky ew -pady $GUIDisplayData("ButtonPad")
        $GUITree set $NodeID -key "WindowPath" [list $Label $Text]
        if {[ic_wb2_get_parameter input "$title: [$GUITree get $NodeID -key "Label"]"] != "___NA___"} {
			$Button configure -text "P" -fg blue
			$GUITree set $NodeID -key "WBInputParam" 1
			ToggleGreyByNodeID $NodeID 1
        } else {
            $Button configure -text "P" -fg white
            $GUITree set $NodeID -key "WBInputParam" 0
            ToggleGreyByNodeID $NodeID 0
        }
        unset wb2_is_running
    } else {
        grid configure $Label -row $Row -column 0 -sticky e 
        if {$type != "INVISIBLE"} {
            grid configure $Text -row $Row -column 1 -columnspan 2 -sticky ew -padx $GUIDisplayData("DEZPadx")
        }
        $GUITree set $NodeID -key "WindowPath" [list $Label $Text]
    }
    set ParentDEZ [GetObject]
}

proc ::AIEnv::GUIManagement::leaveTextEntryBuild {NodeID} {
# Intentionally empty
}

proc ::AIEnv::GUIManagement::validateTextEntryInput {NodeID TextID {Input ""}} {
    return 1
    status_message ""
    if {$Input == ""} { return 1 }
    if [string match *\ * $Input] { return 1 }
    if {[regexp {\+} $Input]} { return 1 }
    if {[regexp {\-} $Input]} { return 1 } 
    if {[regexp {\*} $Input]} { return 1 }
    if {[regexp {\/} $Input]} { return 1 }
    set GUITree [TreeStack peek]
    set label [$GUITree get $NodeID -key "Label"]
    set type [$GUITree get $NodeID -key "EntryType"]
    if {$type == "INT" } {
        set int_re {^[	]*-?[0-9]+[	]*$}
	    if {![regexp $int_re $Input dummy]} {
            status_message "Invalid input for \"$label\""
            set bg [$TextID cget -background]
            $TextID configure -background red; update
            after 250; $TextID configure -background $bg
            
	    }
    } elseif {$type == "NUM"} {
        set float_re1 {[	]*-?[0-9]*(\.[0-9]*)?([eE][+-]?[0-9]+)?[ 	]*}
        set float_re "^$float_re1\$"
	    if {![regexp $float_re $Input dummy]} {
	        if {![string match *e* $Input] && ![string match *E* $Input]} {
                status_message "Invalid input for \"$label\""
                set bg [$TextID cget -background]
                $TextID configure -background red; update
                after 250; $TextID configure -background $bg
            }
	    }
    }
    return 1
}

#-------------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterTextEntry2Build {NodeID} {
    set GUITree [TreeStack peek_one]
    variable GUIDisplayData
    
    set RowParent [DEZInsert 1]
    set Row [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]
    
    # Create the label
    set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"]  \
		   -font $GUIDisplayData("LabelFont") \
		   -wraplength $GUIDisplayData("LabelWrapLength") \
		   -justify $GUIDisplayData("LabelJustify") ]   
    # Create the variable name in the proper namespace
    set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
    set type [$GUITree get $NodeID -key "EntryType"]
    if {$type == "READONLY"} {
	set Text [label $Parent.$NodeID-text -textvariable $VariableName \
			-relief sunken -font $GUIDisplayData("EntryFont")]
	
    } else {
	    set Text [entry $Parent.$NodeID-text -textvariable $VariableName \
		      -font $GUIDisplayData("EntryFont") \
		      -foreground black \
		      -background white -width $GUIDisplayData("TextEntryWidth")]
    }       
    set ParentDEZ [GetObject]
    # create entry2
    set VariableName2 [CreateVariable [$GUITree get $NodeID -key "Variable2"]]
    set type2 [$GUITree get $NodeID -key "EntryType2"]
    if {$type2 == "READONLY"} {
	    set Text2 [label $Parent.$NodeID-text2 -textvariable $VariableName2 \
			-relief sunken -font $GUIDisplayData("EntryFont")]
    } else {
	    set Text2 [entry $Parent.$NodeID-text2 -textvariable $VariableName2 \
		      -font $GUIDisplayData("EntryFont") \
		      -foreground black \
		      -background white -width $GUIDisplayData("TextEntryWidth")]
    }
    if [aie_wb2_is_running] {
        if [aie_wb2_is_input_parameter [aie_get_global current_wb_input_name] [GetObject] [$GUITree get $NodeID -key "Label"]] {
            set Button [button $Parent.$NodeID-btn -height $GUIDisplayData("ButtonHeight") -font $GUIDisplayData("ButtonBoldFont") \
                -relief ridge -bg white -activebackground white -activeforeground white]
            set title [aie_get_global current_wb_input_parameter]
            if {$title == "___NA___" || [aie_wb2_nonvalid_input_title $title]} {
                set title [$GUITree get node1 -key "Title"]
            }           
            if {[GetObject] == "mParamsDEZ" && $title == "Edge Params"} {
                aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Edge Params: [$GUITree get $NodeID -key "Label"]]
            } elseif {[GetObject] == "mszCurveDEZ" && $title == "Curve Mesh Setup"} {
                aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Curve Mesh Setup: [$GUITree get $NodeID -key "Label"]]
            } elseif {[GetObject] == "mszSurfDEZ" && $title == "Surface Mesh Setup"} {
                aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Surface Mesh Setup: [$GUITree get $NodeID -key "Label"]]
            }
			$Button configure -command "aie_wb2_parameter_dialog $NodeID $Button [GetObject] [list $title]"
			bubble_define $Button "Create/Delete Workbench Input Parameter"
			set wb2_is_running 1
        }
    }
    if [info exists wb2_is_running] {
        grid configure $Label -row $Row -column 0 -sticky e 
        grid configure $Text -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
        grid configure $Text2 -row $Row -column 2 -sticky w -padx $GUIDisplayData("DEZPadx")
        grid configure $Button -row $Row -column 3 -sticky w -padx $GUIDisplayData("DEZPadx")
        $GUITree set $NodeID -key "WindowPath" [list $Label $Text $Text2]
        if {[ic_wb2_get_parameter input "$title: [$GUITree get $NodeID -key "Label"]"] != "___NA___"} {
			$Button configure -text "P" -fg blue
			$GUITree set $NodeID -key "WBInputParam" 1
			ToggleGreyByNodeID $NodeID 1
        } else {
            $Button configure -text "P" -fg white
            $GUITree set $NodeID -key "WBInputParam" 0
            ToggleGreyByNodeID $NodeID 0
        }
        unset wb2_is_running
    } else {
        grid configure $Label -row $Row -column 0 -sticky e 
        grid configure $Text -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
        grid configure $Text2 -row $Row -column 2 -sticky w -padx $GUIDisplayData("DEZPadx")
        $GUITree set $NodeID -key "WindowPath" [list $Label $Text $Text2]
   }
}

proc ::AIEnv::GUIManagement::leaveTextEntry2Build {NodeID} {
	# Intentionally empty
}


proc ::AIEnv::GUIManagement::enterTextEntryEditBuild {NodeID} {
   set GUITree [TreeStack peek_one]
   variable GUIDisplayData
   variable CATRootDir
   variable IconDir

   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set wp ""
   set Label [$GUITree get $NodeID -key "Label"]
   if {$Label != ""} {
       set Label [label $Parent.$NodeID-label -text $Label \
                   -font $GUIDisplayData("LabelFont") \
                   -wraplength $GUIDisplayData("LabelWrapLength") \
                   -justify $GUIDisplayData("LabelJustify") ]
       grid configure $Label -row $Row -column 0 -sticky e
       lappend wp $Label
   }

   set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]

   set Text [entry $Parent.$NodeID-text -textvariable $VariableName \
                   -font $GUIDisplayData("EntryFont") -foreground black \
                   -background white -width $GUIDisplayData("TextEntryWidth")]

   set Name [$GUITree get $NodeID -key "Name"]
   set ButBox [ButtonBox $Parent.$NodeID-buttonbox -spacing \
                        [expr $GUIDisplayData("ImageSize") / 4] -padx 1 -pady 1]

   set im [image create photo -format GIF -file \
                 [GetFileName [file join $CATRootDir "$IconDir" TTKeditText.gif]]]

   $ButBox add -image $im -highlightthickness 0 -takefocus 0 \
                  -relief link -borderwidth 1  -padx 1 -pady 1 \
                  -helptext "Edit the text entry" \
                  -command "::AIEnv::GUIManagement::EditTextEntry $VariableName"

   grid configure $Text -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
   grid configure $ButBox -row $Row -column 2 -sticky w
   lappend wp $Text $ButBox
   $GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::EditTextEntry {VariableName} {
   set fn [tmp_filename]
   set fp [open $fn w]
   puts $fp [set $VariableName]
   close $fp
   edit_file $fn 0
   set fp [open $fn r]
   set $VariableName [read -nonewline $fp]
   close $fp
   cmd_rm $fn
}

proc ::AIEnv::GUIManagement::leaveTextEntryEditBuild {NodeID} {
}

#-------------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterTextTableEntryBuild {NodeID} {
    set GUITree [TreeStack peek_one]
    variable GUIDisplayData
    variable CATRootDir
    
    set RowParent [DEZInsert 1]
    set Row [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]
    
    # Create the label
    set labtext [$GUITree get $NodeID -key "Label"]
    set Label [label $Parent.$NodeID-label -text $labtext  \
		   -font $GUIDisplayData("LabelFont") \
		   -wraplength $GUIDisplayData("LabelWrapLength") \
		   -justify $GUIDisplayData("LabelJustify") ]
    
    # Create the variable name in the proper namespace
    set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
    
    set Text [entry $Parent.$NodeID-text -textvariable $VariableName \
		  -font $GUIDisplayData("EntryFont") \
		  -foreground black \
		  -background white -width $GUIDisplayData("TextEntryWidth")]
    
    set TableType [$GUITree get $NodeID -key "TableType"]
    
    #set TableButton [button $Parent.$NodeID-tbut -text Table -command [list aie_edit_table $TableType $VariableName $labtext]]
    set im [image create photo -file $CATRootDir/icons/Table.gif]
    set m $Parent.$NodeID-tbut.m
    set TableButton [menubutton $Parent.$NodeID-tbut -image $im -menu $m]
    menu $m -postcommand [list aie_edit_table_pre $TableType $VariableName] \
	-tearoff $GUIDisplayData("MenuTearOffEnable") -font $GUIDisplayData("MenuFont")
    set post [list aie_edit_table_post $TableType $VariableName]
    $m add checkbutton -label Temperature-Dependent \
	-variable aie_edit_table(temp) -command $post -font $GUIDisplayData("CheckButtonFont")
    if {$TableType != "temp_only"} {
	$m add checkbutton -label Non-Linear \
	    -variable aie_edit_table(nonlinear) -command $post -font $GUIDisplayData("CheckButtonFont")
    }
    $m add command -label "Table Editor" -command "aie_edit_table_doit; $post" -font $GUIDisplayData("CheckButtonFont")
    
    grid configure $Label -row $Row -column 0 -sticky e 
    grid configure $Text -row $Row -column 1 -sticky ew\
	-padx $GUIDisplayData("DEZPadx")
    grid configure $TableButton -row $Row -column 2 -sticky ew \
	-padx $GUIDisplayData("DEZPadx")
    
    $GUITree set $NodeID -key "WindowPath" [list $Label $Text $TableButton]    
}

proc ::AIEnv::GUIManagement::leaveTextTableEntryBuild {NodeID} {
	# Intentionally empty
}

#-------------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterTableEntryBuild {NodeID} {
    set GUITree [TreeStack peek_one]
    variable GUIDisplayData
    variable CATRootDir
    
    set RowParent [DEZInsert 1]
    set Row [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]
    
    # Create the label
    set labtext [$GUITree get $NodeID -key "Label"]
    set Label [label $Parent.$NodeID-label -text $labtext  \
		   -font $GUIDisplayData("LabelFont") \
		   -wraplength $GUIDisplayData("LabelWrapLength") \
		   -justify $GUIDisplayData("LabelJustify") ]
    
    # Create the variable name in the proper namespace
    set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
    
    set Text [entry $Parent.$NodeID-text -textvariable $VariableName \
		  -font $GUIDisplayData("EntryFont") \
		  -foreground black \
		  -background white -width $GUIDisplayData("TextEntryWidth")]
    
    set TableType [$GUITree get $NodeID -key "TableType"]
    
    #set TableButton [button $Parent.$NodeID-tbut -text Table -command [list aie_edit_table $TableType $VariableName $labtext]]
    set im [image create photo -file $CATRootDir/icons/Table.gif]
    set m $Parent.$NodeID-tbut.m
    set TableButton [menubutton $Parent.$NodeID-tbut -image $im -menu $m]
    menu $m -postcommand [list aie_edit_table_pre_new $TableType $VariableName] \
	-tearoff $GUIDisplayData("MenuTearOffEnable") -font $GUIDisplayData("MenuFont")
    set post [list aie_edit_table_post_new $TableType $VariableName]
    $m add checkbutton -label Temperature-Dependent \
	-variable aie_edit_table(temp) -command $post -font $GUIDisplayData("CheckButtonFont")
    if {$TableType != "temp_only"} {
	$m add checkbutton -label Non-Linear \
	    -variable aie_edit_table(nonlinear) -command $post -font $GUIDisplayData("CheckButtonFont")
    }
    $m add command -label "Table Editor" -command "aie_edit_table_doit; $post" -font $GUIDisplayData("CheckButtonFont")
    
    grid configure $Label -row $Row -column 0 -sticky e 
    grid configure $Text -row $Row -column 1 -sticky ew\
	-padx $GUIDisplayData("DEZPadx")
    grid configure $TableButton -row $Row -column 2 -sticky ew \
	-padx $GUIDisplayData("DEZPadx")
    
    $GUITree set $NodeID -key "WindowPath" [list $Label $Text $TableButton]    
}

proc ::AIEnv::GUIManagement::leaveTableEntryBuild {NodeID} {
	# Intentionally empty
}
#-------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterColorOptMenuBuild {NodeID} {
   variable GUIDisplayData
   set GUITree [TreeStack peek_one]
   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set wp ""
   set Label [$GUITree get $NodeID -key "Label"]
   if {$Label != ""} {
      set Label [label $Parent.$NodeID-label -text $Label \
                             -font $GUIDisplayData("LabelFont")\
                             -wraplength $GUIDisplayData("LabelWrapLength") \
                             -justify $GUIDisplayData("LabelJustify")]
      grid configure $Label -row $Row -column 0 -sticky e
      lappend wp $Label
   }
   set VarName [$GUITree get $NodeID -key "VarName"]
   set Proc [$GUITree get $NodeID -key "Proc"]
   if {$Proc == "NULL"} {set Proc ""}

   set Fm [frame $Parent.$NodeID-fm -bd 0 -relief flat]

   SelectColorMenu $Fm.col -type menubutton -variable $VarName -command \
            [list ::AIEnv::GUIManagement::SelectColorOptMenuCmd $VarName $Proc]

   $Fm.col configure -width 16 -height 16

   upvar #0 $VarName var
   set CurrentObjectName [ObjectStack peek_one]
   trace variable var w  "::AIEnv::GUIManagement::DEZ::TraceFunc $CurrentObjectName"

 # grid configure $Fm.col -row 0 -column 0 -sticky nsew -padx $GUIDisplayData("DEZPadx")
   pack $Fm.col -fill both -expand 1 -padx $GUIDisplayData("DEZPadx")

   grid configure $Fm -row $Row -column 1 -columnspan 2 -sticky ew
   lappend wp $Fm

   $GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::leaveColorOptMenuBuild {NodeID} {
        # Intentionally empty
}

proc ::AIEnv::GUIManagement::SelectColorOptMenuCmd {VarName Proc args} {
   global [lindex [split $VarName \(] 0]
   if {[info command from_tkcolor_get] != ""} {
      set $VarName [from_tkcolor_get value [set $VarName]]
   }
   if {($Proc != "NULL") && ($Proc != "")} { eval $Proc }
}

# ---------------------------------------------

proc ::AIEnv::GUIManagement::enterTextOptMenuBuild {NodeID} {
   variable GUIDisplayData
   set GUITree [TreeStack peek_one]
   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set wp ""
   set Label [$GUITree get $NodeID -key "Label"]
   set LabelSide [$GUITree get $NodeID -key "LabelSide"]

   if {($Label != "") && ($LabelSide == "LEFT")} {
      set Label [label $Parent.$NodeID-label -text $Label \
                             -font $GUIDisplayData("LabelFont")\
                             -wraplength $GUIDisplayData("LabelWrapLength") \
                             -justify $GUIDisplayData("LabelJustify")]
      grid configure $Label -row $Row -column 0 -sticky e
      lappend wp $Label
   }
   set VarName [$GUITree get $NodeID -key "VarName"]

 #  set WVarName [$GUITree get $NodeID -key "WVarName"]
   set WVarName ""

   set Proc [$GUITree get $NodeID -key "Proc"]
   if {$Proc == "NULL"} {set Proc ""}

   set NRows [$GUITree get $NodeID -key "NRows"]
   if ![string is integer -strict $NRows] {set NRows 0}

   set FmOut [frame $Parent.$NodeID-fm -bd 0 -relief flat]
   set Fm [frame $FmOut.fm -bd 1 -relief sunken]

   set conf [list -relief sunken -background #ffffff -indicatoron 0 \
                  -padx 0 -borderwidth 0 -takefocus 1] 
   if {$NRows > 0} {lappend conf -pady 2}

   set MList [$GUITree get $NodeID -key "MList"]
   if [string match ::?* $MList] {
      if ![info exist $MList] {set $MList ""}
      set listfunc "set $MList"
   } elseif {[llength $MList] == 1} {
      set listfunc $MList  
   } else {
      set listfunc ""
   }
   if {$listfunc != ""} {
      text_optionMenu_dynamic $Fm.choices $VarName $listfunc $NRows $conf $Proc
      set trc [list update_text_optionMenu_dynamic $Fm.choices $VarName \
                         $listfunc $NRows $conf $Proc $WVarName]
   } else {
      text_optionMenu $Fm.choices $VarName $NRows $conf $Proc $MList $WVarName

      set trc [list update_text_optionMenu $Fm.choices "" $WVarName]
   }

   set arrow [eval ArrowButton::create $Fm.arr -dir bottom -type button \
                     -highlightthickness 0 \
                     -borderwidth 1 -takefocus 0 -width 12 -ipadx 0 -arrowbd 0 \
                     -command [list "foptionMenu_pulldown $Fm.choices"]]

 
 # grid configure $Fm.choices -row 0 -column 0 -sticky nsew -padx $GUIDisplayData("DEZPadx")
   pack $arrow -side right -fill y -expand 0 -padx 0
   pack $Fm.choices -side left -fill both -expand 1 -padx 0
   pack $Fm -fill both -expand 1 -ipadx 0 -padx $GUIDisplayData("DEZPadx")

   upvar #0 $VarName var
   set CurrentObjectName [ObjectStack peek_one]
   trace variable var w  "$trc; ::AIEnv::GUIManagement::DEZ::TraceFunc $CurrentObjectName"

   grid configure $FmOut -row $Row -column 1 -columnspan 2 -sticky ew
   lappend wp $FmOut

   if {($Label != "") && ($LabelSide == "RIGHT")} {
      set Label [label $Parent.$NodeID-label -text $Label \
                             -font $GUIDisplayData("LabelFont")\
                             -wraplength $GUIDisplayData("LabelWrapLength") \
                             -justify $GUIDisplayData("LabelJustify")]
      grid configure $Label -row $Row -column 2 -sticky w
      lappend wp $Label
   }


   $GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::leaveTextOptMenuBuild {NodeID} {
        # Intentionally empty
}

# ---------------------------------------------

proc ::AIEnv::GUIManagement::enterBmpOptMenuBuild {NodeID} {
   variable GUIDisplayData
   set GUITree [TreeStack peek_one]
   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set wp ""
   set Label [$GUITree get $NodeID -key "Label"]
   if {$Label != ""} {
      set Label [label $Parent.$NodeID-label -text $Label \
                             -font $GUIDisplayData("LabelFont")\
                             -wraplength $GUIDisplayData("LabelWrapLength") \
                             -justify $GUIDisplayData("LabelJustify")]
      grid configure $Label -row $Row -column 0 -sticky e
      lappend wp $Label
   }
   set VarName [$GUITree get $NodeID -key "VarName"]
   foreach v {BmpPath BmpFiles} {
      set p [$GUITree get $NodeID -key "$v"]
      if {[string index $p 0] == "\$"} {
         global [string range $p 1 end]; eval set $v $p
      } else {
         set $v $p
      }
   }

 #  set WVarName [$GUITree get $NodeID -key "WVarName"]
   set WVarName ""

   set Proc [$GUITree get $NodeID -key "Proc"]
   if {$Proc == "NULL"} {set Proc ""}

   set NRows [$GUITree get $NodeID -key "NRows"]
   if ![string is integer -strict $NRows] {set NRows 0}

   set FmOut [frame $Parent.$NodeID-fm -bd 0 -relief flat]
   set Fm [frame $FmOut.fm -bd 1 -relief sunken]


   set conf [list -relief sunken -background #ffffff -indicatoron 0 \
                  -padx 0 -borderwidth 0 -takefocus 1]
   #set conf [list -relief groove -padx 2]
   if {$NRows > 0} {lappend conf -pady 2}
   fbitmap_optionMenu $Fm.choices $VarName $NRows $conf $Proc $BmpPath $BmpFiles $WVarName

   set arrow [eval ArrowButton::create $Fm.arr -dir bottom -type button \
                     -highlightthickness 0 \
                     -borderwidth 1 -takefocus 0 -width 12 -ipadx 0 -arrowbd 0 \
                     -command [list "foptionMenu_pulldown $Fm.choices"]]

 # grid configure $Fm.choices -row 0 -column 0 -sticky nsew -padx $GUIDisplayData("DEZPadx")
   pack $arrow -side right -fill y -expand 0 -padx 0
   pack $Fm.choices -side left -fill both -expand 1 -padx 0
   pack $Fm -fill both -expand 1 -ipadx 0 -padx $GUIDisplayData("DEZPadx")


   set trc [list update_fbitmap_optionMenu $Fm.choices $WVarName]
   set CurrentObjectName [ObjectStack peek_one]
   upvar #0 $VarName var
   trace variable var w  "$trc; ::AIEnv::GUIManagement::DEZ::TraceFunc $CurrentObjectName"


   grid configure $FmOut -row $Row -column 1 -columnspan 2 -sticky ew
   lappend wp $FmOut

   $GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::leaveBmpOptMenuBuild {NodeID} {
   # empty
}

# ---------------------------------------------

proc ::AIEnv::GUIManagement::enterEntryButtonBuild {NodeID} {
   variable GUIDisplayData
   variable BuildContext
   set GUITree [TreeStack peek_one]
   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set ButBox [ButtonBox $Parent.$NodeID-buttonbox -spacing \
                        [expr $GUIDisplayData("ImageSize") / 4] -padx 1 -pady 1]

   set VarName [CreateVariable [$GUITree get $NodeID -key "VarName"]]
   set imName [$GUITree get $NodeID -key "ImageName"]
   if {$imName != "NULL"} {
      variable CATRootDir
      variable IconDir
      set im [image create photo -format GIF -file \
                   [GetFileName [file join $CATRootDir "$IconDir" "$imName"]]]
      set butn [$ButBox add -image $im -highlightthickness 0 \
                     -takefocus 0 -relief link -borderwidth 1  -padx 1 -pady 1]
   } else {
      set butn [$ButBox add -text [$GUITree get $NodeID -key "Label"] \
                  -relief raised -borderwidth 1  -padx 1 -pady 1]
   }

   set Proc [$GUITree get $NodeID -key "Proc"]
   if {$Proc != "NULL"} {
      $butn configure -helptext [$GUITree get $NodeID -key "ToolTip"] \
                  -command "$Proc $VarName"
   } else {
      $butn configure -relief flat
   }
              
   grid configure $ButBox -row $Row -column 0 -sticky e

   set Text [entry $Parent.$NodeID-text -textvariable $VarName \
                 -font $GUIDisplayData("EntryFont") -width $GUIDisplayData("TextEntryWidth")]
   if {$Proc != "NULL"} { bind $Text <Return> "$Proc $VarName" }
   grid configure $Text -row $Row -column 1 -columnspan 2 -sticky ew -padx $GUIDisplayData("DEZPadx")

   $GUITree set $NodeID -key "WindowPath" [list $ButBox $Text]
}

proc ::AIEnv::GUIManagement::leaveEntryButtonBuild {NodeID} {
   # none
}

proc ::AIEnv::GUIManagement::enterCoordsEntryBuild {NodeID} {
   variable GUIDisplayData
   variable BuildContext
   variable CATRootDir
   variable IconDir
   variable SelectCoordsImage

   set GUITree [TreeStack peek_one]
   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set wp ""
   set Label [$GUITree get $NodeID -key "Label"]
   if {$Label != ""} {
      set Label [label $Parent.$NodeID-label -text $Label \
                             -font $GUIDisplayData("LabelFont")\
                             -wraplength $GUIDisplayData("LabelWrapLength") \
                             -justify $GUIDisplayData("LabelJustify")]
      grid configure $Label -row $Row -column 0 -sticky e
      lappend wp $Label
   }
   set ListName [$GUITree get $NodeID -key "ListName"]
   set VarName [CreateVariable $ListName]
   set Text [entry $Parent.$NodeID-text -textvariable $VarName \
                 -font $GUIDisplayData("EntryFont") -width $GUIDisplayData("TextEntryWidth")]

   set Name [$GUITree get $NodeID -key "Name"]
   set ButBox [ButtonBox $Parent.$NodeID-buttonbox -spacing \
                        [expr $GUIDisplayData("ImageSize") / 4] -padx 1 -pady 1]

   if [info exists SelectCoordsImage] {
      set im $SelectCoordsImage
   } else {
      set FileName [GetFileName [file join $CATRootDir "$IconDir" "TTKselectCoords.gif"]]
      set im [image create photo -format GIF -file $FileName]
      set SelectCoordsImage $im
   }

   $ButBox add -image $im -highlightthickness 0 -takefocus 0 \
                  -relief link -borderwidth 1  -padx 1 -pady 1 \
                  -helptext "Select a point in the current graphic window" \
                  -command "::AIEnv::GUIManagement::SelectCoordsEntryCmd $VarName"

   grid configure $Text -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
   grid configure $ButBox -row $Row -column 2 -sticky w
   lappend wp $Text $ButBox

   $GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::leaveCoordsEntryBuild {NodeID} {
   # none
}

proc ::AIEnv::GUIManagement::SelectCoordsEntryCmd {VarName} {
   global tdv_current_viewer tdv_select_loc

   if {![info exist tdv_current_viewer] || \
       ![winfo exist $tdv_current_viewer]} {return ""}

   set w $tdv_current_viewer
   if {[tdv_get_win_dim $w] < 2} {
      mess "Selecting a 3D point in 1D window is impossible\n"
      return ""
   }

   set tdv_select_loc($w) ""
   tdv_set_mouse_press_binding $w <ButtonPress-1> 1 select_loc

   eval tkwait variable tdv_select_loc($w)

   set x [lindex $tdv_select_loc($w) 1]
   set y [lindex $tdv_select_loc($w) 2] 

   set rr [$w get_3d_point $x $y -1]
   set $VarName [lrange $rr 0 2]
}


# ---------------------------------------------

proc ::AIEnv::GUIManagement::enterEntityButtonBuild {NodeID} {
   variable GUIDisplayData
   variable BuildContext
   variable CATRootDir
   variable IconDir
   set GUITree [TreeStack peek_one]
   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set wp ""
   set Label [$GUITree get $NodeID -key "Label"]
   if {$Label != ""} {
      set Label [label $Parent.$NodeID-label -text $Label \
                            -font $GUIDisplayData("LabelFont")\
                            -wraplength $GUIDisplayData("LabelWrapLength") \
                            -justify $GUIDisplayData("LabelJustify")]
      grid configure $Label -row $Row -column 0 -sticky e
      lappend wp $Label
   }
   set ListName [$GUITree get $NodeID -key "ListName"]
   set entrytype [$GUITree get $NodeID -key "EntryType"]
   set state normal
   if {$entrytype == "READONLY"} { set state readonly }
   set Text [entry $Parent.$NodeID-text -textvariable [CreateVariable $ListName] \
                      -font $GUIDisplayData("EntryFont") \
                      -state $state -foreground black \
                      -background white -width $GUIDisplayData("TextEntryWidth")]
   set Name [$GUITree get $NodeID -key "Name"]
   set ButBox [ButtonBox $Parent.$NodeID-buttonbox -spacing \
                        [expr $GUIDisplayData("ImageSize") / 4] -padx 1 -pady 1]

   set ParentObject [GetObject]
   set Proc [$GUITree get $NodeID -key "Proc"]
   set imName [$GUITree get $NodeID -key "ImageName"]
   set im [image create photo -format GIF -file \
                 [GetFileName [file join $CATRootDir "$IconDir" "$imName"]]]

   $ButBox add -image $im -highlightthickness 0 -takefocus 0 \
                  -relief link -borderwidth 1  -padx 1 -pady 1 \
                  -helptext [$GUITree get $NodeID -key "ToolTip"] \
                  -command "$Proc $ParentObject $ListName"
   grid configure $Text -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
   grid configure $ButBox -row $Row -column 2 -sticky w
   lappend wp $Text $ButBox

   $GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::leaveEntityButtonBuild {NodeID} {
   # none
}

proc ::AIEnv::GUIManagement::getSelectionImage {type} {
    global icon_size1
    switch $type {
	HEX_BLOCK - STR_DOMAIN {set im select_blocks$icon_size1.gif}
	HEX_EDGE - STR_EDGE {set im select_edge$icon_size1.gif}
	HEX_FACE - STR_SUBFACE {set im select_face$icon_size1.gif}
	HEX_VERTEX - STR_VERTEX {set im select_vertex$icon_size1.gif}
	POINT {set im select_d0_on$icon_size1.gif}
	CURVE {set im select_d1_on$icon_size1.gif}
	CURVE_OR_COMPCURVE {set im select_d1_on$icon_size1.gif}
	SURF {set im select_d2_on$icon_size1.gif}
	BODY {set im select_matpt$icon_size1.gif}
    GEOMETRY {set im select_d3_on$icon_size1.gif}
	POINT_0D_EL -  NODE - STR_NODE {set im select_Nodes_on$icon_size1.gif}
	CURVE_1D_EL - 1D_EL {set im select_Bars_on$icon_size1.gif}
	SURF_2D_EL - 2D_EL {set im select_Shells_on$icon_size1.gif}
	BODY_3D_EL - 3D_EL - ELEM {set im select_VolElems_on$icon_size1.gif}
	DENSITY {set im select_density$icon_size1.gif}
	SUBSET {set im select_subset_pic$icon_size1.gif}
	POINTORXYZ {set im select_location$icon_size1.gif}
	PART - SUBPART - PART_0D - PART_1D - PART_0D_1D - PART_0D_1D_2D - PART_2D - PART_3D - PART_PRISM - PART_VOLUME {set im select_part_pic$icon_size1.gif}
	HEX_COMPCURVE {set im select_comp_curve$icon_size1.gif}
	ENTITY - ANY_ENTITY {set im select_any$icon_size1.gif}
	EDGE {set im select_edges$icon_size1.gif}
	ENDPOINT {set im select_end$icon_size1.gif}
	default {set im select_location$icon_size1.gif}
    }

    return $im
}

proc ::AIEnv::GUIManagement::getAddMinusImage {type how} {
    global icon_size1

    set im ""
    switch $type {
        HEX_BLOCK - STR_DOMAIN {set im select_blocks }
        HEX_EDGE - STR_EDGE {set im select_edge }
        HEX_FACE - STR_SUBFACE {set im select_face }
        HEX_VERTEX - STR_VERTEX {set im select_vertex }
    }

    if {$im != ""} {
       return ${im}_${how}$icon_size1.gif
    } else {
       return select_location$icon_size1.gif
    }
}

proc ::AIEnv::GUIManagement::enterEntityAddRemoverBuild {NodeID} {
    return [enterEntityChooserBuild $NodeID]
}

proc ::AIEnv::GUIManagement::leaveEntityAddRemoverBuild {NodeID} {
    return [leaveEntityChooserBuild $NodeID]
}

# ---------------------------------------------
proc ::AIEnv::GUIManagement::enterEntityChooserBuild {NodeID} {
    variable GUIDisplayData
    variable BuildContext
    variable CATRootDir
    variable SelectEntImage
    variable MoreButImage
    variable AddEntImage
    variable MinusEntImage

    set GUITree [TreeStack peek_one]
    set RowParent [DEZInsert 1]
    set Row [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]
    set EntryType [$GUITree get $NodeID -key "EntryType"]    

    set widget_type [$GUITree get $NodeID -key "Type"]

    set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"] \
		   -font $GUIDisplayData("LabelFont")\
		   -wraplength $GUIDisplayData("LabelWrapLength") \
		   -justify $GUIDisplayData("LabelJustify")]
    # Create the variable name in the proper namespace
    set ListVariableName [CreateVariable [$GUITree get $NodeID -key "ListName"]]
    
    if {$widget_type != "EntityAddRemover"} {
	    set Text [entry $Parent.$NodeID-text -textvariable $ListVariableName \
		      -font $GUIDisplayData("EntryFont") -background white \
		      -width $GUIDisplayData("TextEntryWidth")]
    }
    set Name [$GUITree get $NodeID -key "Name"]
    set AutoApply [$GUITree get $NodeID -key "AutoApply"]

    # Create the toolbar that will hold the selector tools                                       
    set ButBox [ButtonBox $Parent.$NodeID-buttonbox -spacing [expr $GUIDisplayData("ImageSize") / 4] -padx 1 -pady 1]
    set SelectionType [$GUITree get $NodeID -key "ChoiceType"]

    if {$widget_type == "EntityAddRemover"} {
        if [info exists AddEntImage($SelectionType)] {
            set im1 $AddEntImage($SelectionType)
        } else {
            set add_image [getAddMinusImage $SelectionType add]
            set FileName [GetFileName [file join $CATRootDir "icons" $add_image]]
            set im1 [image create photo -format GIF -file $FileName]
            set AddEntImage($SelectionType) $im1
        }
        if [info exists MinusEntImage($SelectionType)] {
	        set im2 $MinusEntImage($SelectionType)
	    } else {
	        set rm_image [getAddMinusImage $SelectionType minus]
	        set FileName [GetFileName [file join $CATRootDir "icons" $rm_image]]
	        set im2 [image create photo -format GIF -file $FileName]
	        set MinusEntImage($SelectionType) $im2
	    }
    } else {
        if [info exists SelectEntImage($SelectionType)] {
	        set im1 $SelectEntImage($SelectionType)
        } else {
	        set selimage [getSelectionImage $SelectionType]
	        set FileName [GetFileName [file join $CATRootDir "icons" $selimage]]
	        set im1 [image create photo -format GIF -file $FileName]
	        set SelectEntImage($SelectionType) $im1
        }
        if [info exists MoreButImage] {
	        set im2 $MoreButImage
        } else {
	        set FileName [GetFileName [file join $CATRootDir "icons" "moreButton.gif"]]
	        set im2 [image create photo -format GIF -file $FileName]
	        set MoreButImage $im2
        }
    }
    
    set NumberOfEntities [$GUITree get $NodeID -key "NumberOfEntities"]
    set ExactNumber [$GUITree get $NodeID -key "ExactNumber"]
    set SelectOptions [$GUITree get $NodeID -key "SelectOptions"]
    
    if {$SelectOptions == "NULL"} {
        set SelectOptions ""
    }

    set SelectMessage [$GUITree get $NodeID -key "SelectMessage"]
    set Parent [GetObject]
    BeginTypeDefinition Picker
    BeginObjectDefinition $Name
    $Name set -key variable $ListVariableName
    $Name set -key type $SelectionType
    $Name set -key maxNumber $NumberOfEntities
    $Name set -key requireExactNumber $ExactNumber
    $Name set -key parent $Parent
    $Name set -key selectOptions $SelectOptions
    $Name set -key selectMessage $SelectMessage
    $Name set -key autoApply $AutoApply
    EndObjectDefinition
    EndTypeDefinition

    switch $SelectionType {
	    HEX_BLOCK {set selectionText "Select block(s)" ; set deselectText "Deselect block(s)"}
	    STR_DOMAIN {set selectionText "Select domain(s)" ; set deselectText "Deselect domain(s)"}
	    HEX_EDGE - STR_EDGE {set selectionText "Select edge(s)" ; set deselectText "Deselect edge(s)"}
	    HEX_FACE {set selectionText "Select face(s)" ; set deselectText "Deselect face(s)"}
	    STR_SUBFACE {set selectionText "Select subface(s)" ; set deselectText "Deselect subface(s)"}
	    HEX_VERTEX - STR_VERTEX {set selectionText "Select vert(s)" ; set deselectText "Deselect vert(s)"}
	    POINT {set selectionText "Select point(s)"}
	    CURVE {set selectionText "Select curve(s)"}
	    CURVE_OR_COMPCURVE {set selectionText "Select curve(s) or compcurve(s)"}
	    SURF {set selectionText "Select surface(s)"}
	    BODY {set selectionText "Select material point(s)"}
	    GEOMETRY {set selectionText "Select geometry"}
	    POINT_0D_EL -  NODE - STR_NODE {set selectionText "Select node(s)"}
	    CURVE_1D_EL {set selectionText "Select line element(s) or curve(s)"}
	    SURF_2D_EL {set selectionText "Select shell element(s) or surface(s)"}
	    BODY_3D_EL {set selectionText "Select volume element(s) or bodies"}
	    1D_EL {set selectionText "Select line element(s)"}
	    2D_EL {set selectionText "Select shell element(s)"}
	    3D_EL {set selectionText "Select volume element(s)"}
	    ELEM {set selectionText "Select element(s)"}
	    DENSITY {set selectionText "Select density region(s)"}
	    SUBSET {set selectionText "Select subset(s)"}
	    POINTORXYZ {set selectionText "Select location(s)"}
	    PART - SUBPART - PART_0D - PART_0D_1D - PART_0D_1D_2D - PART_1D - PART_2D - PART_3D - PART_PRISM - PART_VOLUME {set selectionText "Select part(s)"}
	    HEX_COMPCURVE {set selectionText "Select compcurve(s)"}
	    ENTITY - ANY_ENTITY {set selectionText "Select entities"}
	    EDGE {set selectionText "Select edge(s)"}
	    ENDPOINT {set selectionText "Select endpoint(s)"}
	    default {set selectionText "Select items"; set deselectText "Deselect items"}
    }
    
    set selbut [$ButBox add -image $im1 -highlightthickness 0 -takefocus 0 \
		    -relief link -borderwidth 1 -padx 1 -pady 1 -helptext $selectionText \
		    -command "$Name pick"]
    if {$widget_type != "EntityAddRemover"} {
	    switch $SelectionType {
	        CURVE - CURVE_OR_COMPCURVE - SURF - BODY - ANY_ENTITY - POINT - GEOMETRY - DENSITY -
	        ELEM - POINT_0D_EL - CURVE_1D_EL - SURF_2D_EL - BODY_3D_EL - NODE - PART -
	        1D_EL - 2D_EL - 3D_EL {
		        menu $selbut.m -tearoff 0
		        bind $selbut <Button-3> "tk_popup $selbut.m %X %Y {}"
		        $selbut.m add command -label "Add to selection" -command "$Name pick -add"
	        }
	    }
    }
    
    set EnableMulti disabled
    if {$NumberOfEntities > 1} {
        set EnableMulti active
    }
    if {$widget_type == "EntityAddRemover"} {
	    set editbut [$ButBox add -image $im2 -highlightthickness 0 -takefocus 0 \
			 -relief link -borderwidth 1 -padx 1 -pady 1 \
			 -helptext $deselectText -command "$Name pick -remove"]
    } else {
	    set editbut [$ButBox add -text ". . ." -highlightthickness 0 -takefocus 0 -relief link \
			 -borderwidth 1 -padx 1 -pady 1 -helptext "More" -state $EnableMulti \
			 -font $GUIDisplayData("DEZTitleFont") -command "$Name showItems"]
	    if {$EntryType == "READONLY"} {
	        $editbut configure -state disabled
	    }
    }
    
    # Pack everything in
    grid configure $Label -row $Row -column 0 -sticky e
    if {$widget_type == "EntityAddRemover"} {
	    grid configure $ButBox -row $Row -column 1 -sticky w
	    $GUITree set $NodeID -key "WindowPath" [list $Label $ButBox]
    } else {
	    grid configure $Text -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
	    grid configure $ButBox -row $Row -column 2 -sticky w
	    $GUITree set $NodeID -key "WindowPath" [list $Label $Text $ButBox]
    }
}

proc ::AIEnv::GUIManagement::leaveEntityChooserBuild {NodeID} {
    # Intentionally empty
}

# --- RadioFrame Group ---------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterRadioFrameBuild {NodeID} {
    variable BuildContext
    variable GUIDisplayData
    variable FrameData
    set GUITree [TreeStack peek_one]
        # For now the frame does not support any nested frames or
    # radio groups, or dialog separators

    # Set the number of rows to be equal to the number of children
    # within the frame
    set Rows [llength [$GUITree children $NodeID]]

    set RowParent [DEZInsert $Rows 1]
    set TopRow [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]

    set Text  [$GUITree get $NodeID -key "Label"]
    set Variable [CreateVariable [$GUITree get $NodeID -key "Variable"]]
    set Value [$GUITree get $NodeID -key "Value"]
    set Proc [$GUITree get $NodeID -key "Proc"]
    if {$Proc == "NULL"} {set Proc ""}

    set RFrame [RadioFrame $Parent.$NodeID-tf -text $Text \
                        -variable $Variable -value $Value -command $Proc \
                        -font $GUIDisplayData("DEZTitleFont")]
    set InteriorFrame [$RFrame getframe]

       # grid in the frame
    grid configure $RFrame -row $TopRow -column 0 -columnspan 3 -rowspan $Rows -sticky nsew

    # configure the Interior frame
    grid columnconfigure $InteriorFrame 0 -weight 0
    grid columnconfigure $InteriorFrame 1 -weight 1
    grid columnconfigure $InteriorFrame 2 -weight 0

    WindowPathStack push $InteriorFrame
    DEZRowCountStack push 0

    $GUITree set $NodeID -key "WindowPath" $RFrame
}

proc ::AIEnv::GUIManagement::leaveRadioFrameBuild {NodeID} {
    WindowPathStack pop
    DEZRowCountStack pop
}


# --- CheckFrame Group ---------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterCheckFrameBuild {NodeID} {
    variable BuildContext
    variable GUIDisplayData
    variable FrameData
    set GUITree [TreeStack peek_one]
        # For now the frame does not support any nested frames or
    # radio groups, or dialog separators
   
    # Set the number of rows to be equal to the number of children
    # within the frame
    set Rows [llength [$GUITree children $NodeID]]
   
    set RowParent [DEZInsert $Rows 1]
    set TopRow [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]

    set Text  [$GUITree get $NodeID -key "Label"]
    set Variable [CreateVariable [$GUITree get $NodeID -key "Variable"]]
    set Proc [$GUITree get $NodeID -key "Proc"]
    if {$Proc == "NULL"} {set Proc ""}

    set CFrame [CheckFrame $Parent.$NodeID-tf -text $Text \
                        -variable $Variable -command $Proc \
                        -font $GUIDisplayData("DEZTitleFont")]
    set InteriorFrame [$CFrame getframe]

       # grid in the frame
    grid configure $CFrame -row $TopRow -column 0 -columnspan 3 -rowspan $Rows -sticky nsew -pady $GUIDisplayData("DEZPady")

    # configure the Interior frame
    grid columnconfigure $InteriorFrame 0 -weight 0
    grid columnconfigure $InteriorFrame 1 -weight 1
    grid columnconfigure $InteriorFrame 2 -weight 0

    WindowPathStack push $InteriorFrame
    DEZRowCountStack push 0

    $GUITree set $NodeID -key "WindowPath" $CFrame
}

proc ::AIEnv::GUIManagement::leaveCheckFrameBuild {NodeID} {
    WindowPathStack pop
    DEZRowCountStack pop
}


# --- Frame Group ---------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterFrameBuild {NodeID} {
    variable BuildContext
    variable GUIDisplayData
    variable FrameData
    set GUITree [TreeStack peek_one]
	# For now the frame does not support any nested frames or
    # radio groups, or dialog separators
    
    # Set the number of rows to be equal to the number of children
    # within the frame
    set Rows [llength [$GUITree children $NodeID]]
    
    set RowParent [DEZInsert $Rows 1]
    set TopRow [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]

    set Text  [$GUITree get $NodeID -key "Label"]
    if {$Text != "NULL"} {
       set LabFrame [TitleFrame $Parent.$NodeID-tf -text [$GUITree get $NodeID -key "Label"] \
			-font $GUIDisplayData("DEZTitleFont")]
       set InteriorFrame [$LabFrame getframe]

       # grid in the frame
       grid configure $LabFrame -row $TopRow -column 0 -columnspan 3 -rowspan $Rows -sticky nsew -pady $GUIDisplayData("DEZPady")
       set wp $LabFrame
    } else {
       set InteriorFrame [frame $Parent.$NodeID-f]
       grid configure $InteriorFrame -row $TopRow -column 0 -columnspan 3 -rowspan $Rows -sticky nsew -pady $GUIDisplayData("DEZPady")
       set wp $InteriorFrame
    }

    # configure the Interior frame
    grid columnconfigure $InteriorFrame 0 -weight 0
    grid columnconfigure $InteriorFrame 1 -weight 1
    grid columnconfigure $InteriorFrame 2 -weight 0

    WindowPathStack push $InteriorFrame
    DEZRowCountStack push 0

    $GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::leaveFrameBuild {NodeID} {
    WindowPathStack pop
    DEZRowCountStack pop
}

# --- Radio Group ---------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterRadioGroupBuild {NodeID} {

    variable BuildContext
    variable GUIDisplayData
    variable RadioGroupData
	
	set GUITree [TreeStack peek_one]
    
    # Query the number of children we have
    set NumItems [llength [$GUITree children $NodeID]]
    set NumCols [$GUITree get $NodeID -key "NumCol"]
    set DrawBox [$GUITree get $NodeID -key "DrawBox"]
    set Rows [ceil [expr double($NumItems) / $NumCols]]
    # Add one row for the frame label
    incr Rows

    # Create the frame into which the radio items will be inserted
    
    set RowParent [DEZInsert $Rows 1]
    set TopRow [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]
    
    set LabFrame [TitleFrame $Parent.$NodeID-tf -text [$GUITree get $NodeID -key "Label"] \
		      -font $GUIDisplayData("DEZTitleFont")]
    if !$DrawBox { $LabFrame configure -relief flat }
    
    set InteriorFrame [$LabFrame getframe]
    
    # Configure the interior frame
    for {set i 0} {$i <= $NumCols} {incr i} {
	grid columnconfigure $InteriorFrame $i -weight 0
    }
    grid columnconfigure $InteriorFrame [expr $NumCols + 1] -weight 1
    grid columnconfigure $InteriorFrame 0 -minsize 50
    
    # grid in the radio button group frame
    grid configure $LabFrame -row $TopRow -column 0 -columnspan 3 -rowspan $Rows -sticky nsew -pady $GUIDisplayData("DEZPady")
    
    WindowPathStack push $InteriorFrame
    
    # Setup the data necessary to compute the row and column for a given radio button
    set RadioGroupData("NumCols") $NumCols
    set RadioGroupData("CurrentItem") 0
    
    $GUITree set $NodeID -key "WindowPath" $LabFrame
    
    # Set up this variable
    CreateVariable [$GUITree get $NodeID -key "Variable"]
}

proc ::AIEnv::GUIManagement::leaveRadioGroupBuild {NodeID} {

    WindowPathStack pop
}

proc ::AIEnv::GUIManagement::GetRadioItemRowCol {} {
    variable RadioGroupData
    set CurItem $RadioGroupData("CurrentItem")
    set Row [expr int($CurItem / $RadioGroupData("NumCols"))]
 #  set Col [expr int($CurItem % $RadioGroupData("NumCols")) + 1]  --- don't know why + 1
    set Col [expr int($CurItem % $RadioGroupData("NumCols"))]
    if {$Col < 0} {set Col 0}
    set Data [list $Row $Col]
    incr CurItem
    set RadioGroupData("CurrentItem") $CurItem
    return $Data
}

# --- Radio Item ----------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterRadioItemBuild {NodeID} {
    variable GUIDisplayData

    set RowCol [GetRadioItemRowCol]
    set GUITree [TreeStack peek_one]
    
    set Row [lindex $RowCol 0]
    set Col [lindex $RowCol 1]
    
    set ParentWindow [WindowPathStack peek_one]
    
    # Create the variable name in the proper namespace
    set VarName [$GUITree get [$GUITree parent $NodeID] -key "Variable"]
    if [string match ::?* $VarName] {
	set Variable $VarName
    } else {
	set Variable [GetFullyQualifiedVariableName $VarName]
    }
    set DEZName [GetObject]
    
    set Label [$GUITree get $NodeID -key "Label"]
    set Value [$GUITree get $NodeID -key "Value"]
    
    set Radio [radiobutton $ParentWindow.$NodeID -value $Value -variable $Variable \
		   -text $Label \
		   -font $GUIDisplayData("RadioButtonFont")]
    
    
    set TheProc [$GUITree get [$GUITree parent $NodeID] -key "Proc"]
    if { $TheProc != "NULL" } {
	$Radio configure -command "$DEZName proc $TheProc"
    }
    grid $Radio -row $Row -column $Col -sticky w -padx $GUIDisplayData("DEZPadx")
    
    $GUITree set $NodeID -key "WindowPath" $Radio
}

proc ::AIEnv::GUIManagement::leaveRadioItemBuild {NodeID} {
    # Intentionally empty
}

# --- Dropdown Entry -------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterDropDownEntryBuild {NodeID} {
    variable GUIDisplayData
    set GUITree [TreeStack peek_one]
    
    set RowParent [DEZInsert 1] 
    set Row [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]

    set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"] \
    				-font $GUIDisplayData("LabelFont")\
    				-wraplength $GUIDisplayData("LabelWrapLength") \
    				-justify $GUIDisplayData("LabelJustify")]
    
    set Name [$GUITree get $NodeID -key "Name"]
    
    # Create the variable name in the proper namespace
    set ListVar [CreateVariable [$GUITree get $NodeID -key "List"]]
    set Variable [CreateVariable [$GUITree set $NodeID -key "Variable"]]

    # TO DO: Set the command to run when the user makes a selection
    set TextVariableName $Name-$NodeID
    set ModifyMode [$GUITree get $NodeID -key "ModifyMode"]

    set IndVar [CreateVariable __${Name}_Last_Index]
    set $IndVar 0

    set Drop $Parent.$NodeID-ComboBox

    set is_editable true
    set dcmd ""
    if {$ModifyMode == "MENULIKE" || $ModifyMode == "READONLY"} {
       set is_editable false
    } elseif  {$ModifyMode == "WRITABLE"} {
       set dcmd "::AIEnv::GUIManagement::DropDownWroteEntryCmd $Drop $ListVar $Name $IndVar"
    }

    ComboBox $Parent.$NodeID-ComboBox  -editable $is_editable \
    	  -height 5 -disabledforeground $GUIDisplayData("DisabledBackground") \
    	  -textvariable $Variable -entrybg white \
    	  -width $GUIDisplayData("TextEntryWidth") \
    	  -font $GUIDisplayData("EntryFont") -exportselection 0 \
          -modifycmd "::AIEnv::GUIManagement::DropDownModifyCmd $Drop $ListVar $Variable $Name $IndVar $ModifyMode" \
          -command $dcmd -foreground black \
          -postcommand "::AIEnv::GUIManagement::DropDownModifyHeight $Drop $ListVar"

    # Place a trace on the list variable so that we properly update things when
    # the variable changes

    trace variable $ListVar w "::AIEnv::GUIManagement::DropDownListVariableMonitor $Drop $ListVar $IndVar"

    interp alias {} ::${Name} {} ::AIEnv::GUIManagement::WidgetProc $Drop
    # Set up the onLoad handler
    # set ParentDEZ [GetObject]
    #$ParentDEZ addloadproc "::AIEnv::GUIManagement::DropDownAutoLoad $Drop $ListVar $Variable" AFTER_ON_LOAD
    # Grid it in
    grid configure $Label -row $Row -column 0 -sticky e
    grid configure $Drop -row $Row -column 1 -columnspan 2 \
      -sticky ew -padx $GUIDisplayData("DEZPadx")

    $GUITree set $NodeID -key "WindowPath" [list $Label $Drop]
}

proc ::AIEnv::GUIManagement::DropDownAutoLoad {DropName ListVariable Variable} {
   if { [info exists $Variable] && [info exists $ListVariable] } {
	set Index [lsearch [subst $[subst $ListVariable]] [subst $[subst $Variable]]]
	if { $Index != -1 } {
		$DropName setvalue @$Index	
	}
   }
}

proc ::AIEnv::GUIManagement::leaveDropDownEntryBuild {NodeID} {
	# Intentionally empty
}

proc ::AIEnv::GUIManagement::DropDownWroteEntryCmd {Widget ListVar Name IndVar} {
   set oldID  [set $IndVar]
   set newVal [$Widget cget -text]
   set ListValues [subst $[subst $ListVar]]

   if {$newVal == ""} {
      set $ListVar [lreplace $ListValues $oldID $oldID]   
   } else {
      set $ListVar [lreplace $ListValues $oldID $oldID $newVal]
   }
   set PName on${Name}WroteEntry
   if {[info command $PName] != ""} {$PName $oldID $newVal}
}

proc ::AIEnv::GUIManagement::DropDownModifyCmd {Widget ListVar VariableName Name IndVar Mode} {
    set oldID  [set $IndVar]
    set newVal [set $VariableName]
    set SelectionID [$Widget getvalue]
    if { $SelectionID != -1 } {
       set ListValues [subst $[subst $ListVar]]
       if {($oldID != -1) && ($oldID != $SelectionID) && ($newVal != "")} {
          set oldVal [lindex $ListValues $oldID]
          if {($newVal != $oldVal) && ([lsearch $ListValues $newVal] < 0)} {
             switch -- $Mode {
                WRITABLE {
                   ::AIEnv::GUIManagement::DropDownWroteEntryCmd $Widget $ListVar $Name $IndVar
                }
                ADDABLE  { set ListValues [lappend $ListVar $newVal] }
             }
          }
       }
       if { $SelectionID < [llength $ListValues] } {
          set $VariableName [lindex $ListValues $SelectionID]
       } else {
          set $VariableName ""
       }
    }

    set $IndVar $SelectionID 

    set ProcName "on[string toupper $Name 0 0]Modify"
    if {[info command $ProcName] != ""} { $ProcName $Name [set $VariableName] }
}

proc ::AIEnv::GUIManagement::DropDownListVariableMonitor {Widget ListVar IndVar args} {
    set ListValues [subst $[subst $ListVar]]
    $Widget configure -values $ListValues
    if {[set $IndVar] > [llength $ListValues]} {set $IndVar -1}
}

# This is a convenience function to set a dropdown by value and not by index.

proc ::AIEnv::GUIManagement::SetDropDown {name value} {
    set vals [uplevel 1 \"$name\" cget -values]
#    puts "vals $vals"
    set i 0
    set pos 0 ;# so there is some default value
    foreach v $vals {
#	puts "$value == $v"
	if {$value == $v} { set pos $i; break }
	incr i
    }
    uplevel 1 \"$name\" setvalue @$pos
}

proc ::AIEnv::GUIManagement::DropDownModifyHeight {Widget ListVar} {

   set ListValues [subst $[subst $ListVar]]
    set lenlist [llength $ListValues]
    if {$lenlist <= 5} {
       set heightlist [expr $lenlist + 1]
    } elseif {$lenlist > 5 &&  $lenlist <= 10} {
       set heightlist 5
    } elseif {$lenlist > 10 &&  $lenlist <= 20} {
       set heightlist 10
    } else {
       set heightlist 20
    }
    $Widget configure -height $heightlist
}

# --- Integer Entry ---------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterIntegerEntryBuild {NodeID} {
    variable GUIDisplayData
	set RowParent [DEZInsert 1]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
	set GUITree [TreeStack peek_one]
	
	set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"] \
					 -font $GUIDisplayData("LabelFont")\
					 -wraplength $GUIDisplayData("LabelWrapLength") \
					 -justify $GUIDisplayData("LabelJustify")]

	set Min  [$GUITree get $NodeID -key "Min"]
	set Max  [$GUITree get $NodeID -key "Max"]
	set Incr [$GUITree get $NodeID -key "Increment"]
	set Range [list $Min $Max $Incr]

	# Create the variable name in the proper namespace
	set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
	set IntegerSpin [SpinBox $Parent.$NodeID-SpinBox -range $Range -textvariable $VariableName \
			-font $GUIDisplayData("EntryFont") -width $GUIDisplayData("TextEntryWidth")]
	set Default  [$GUITree get $NodeID -key "Default"]
	if {$Default != ""} {set $VariableName $Default}

    if [aie_wb2_is_running] {
        if [aie_wb2_is_input_parameter [aie_get_global current_wb_input_name] [GetObject] [$GUITree get $NodeID -key "Label"]] {
            set Button [button $Parent.$NodeID-btn -height $GUIDisplayData("ButtonHeight") -font $GUIDisplayData("ButtonBoldFont") \
                    -relief ridge -bg white -activebackground white -activeforeground white]
            set title [aie_get_global current_wb_input_parameter]
            if {$title == "___NA___" || [aie_wb2_nonvalid_input_title $title]} {
                set title [$GUITree get node1 -key "Title"]
            }          
            if {[GetObject] == "mParamsDEZ" && $title == "Edge Params"} {
                aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Edge Params: [$GUITree get $NodeID -key "Label"]]
            } elseif {[GetObject] == "mszCurveDEZ" && $title == "Curve Mesh Setup"} {
                aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Curve Mesh Setup: [$GUITree get $NodeID -key "Label"]]
            } elseif {[GetObject] == "mszSurfDEZ" && $title == "Surface Mesh Setup"} {
                aie_set_global wb_parameter_input_button [list $NodeID $Button] [list Surface Mesh Setup: [$GUITree get $NodeID -key "Label"]]
            }
			$Button configure -command "aie_wb2_parameter_dialog $NodeID $Button [GetObject] [list $title]"
			bubble_define $Button "Create/Delete Workbench Input Parameter"
			set wb2_is_running 1
        }
     }

    if [info exists wb2_is_running] {
	    grid configure $Label -row $Row -column 0 -sticky e
	    grid configure $IntegerSpin -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
        grid configure $Button -row $Row -column 2 -sticky ew -pady $GUIDisplayData("ButtonPad")
        $GUITree set $NodeID -key "WindowPath" [list $Label $IntegerSpin]
        if {[ic_wb2_get_parameter input "$title: [$GUITree get $NodeID -key "Label"]"] != "___NA___"} {
			$Button configure -text "P" -fg blue
			$GUITree set $NodeID -key "WBInputParam" 1
			ToggleGreyByNodeID $NodeID 1
        } else {
            $Button configure -text "P" -fg white
            $GUITree set $NodeID -key "WBInputParam" 0
            ToggleGreyByNodeID $NodeID 0
        }
        unset wb2_is_running
    } else {
	    grid configure $Label -row $Row -column 0 -sticky e
	    grid configure $IntegerSpin -row $Row -column 1 -columnspan 2 -sticky ew -padx $GUIDisplayData("DEZPadx")
        $GUITree set $NodeID -key "WindowPath" [list $Label $IntegerSpin]
    }
}

proc ::AIEnv::GUIManagement::leaveIntegerEntryBuild {NodeID} {
	# Intentionally empty
}

# --- Integer Entry Icon ---------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterIntegerEntryIconBuild {NodeID} {
    variable GUIDisplayData
    variable CATRootDir
    variable IconDir
    set RowParent [DEZInsert 1]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
	set GUITree [TreeStack peek_one]
	
	set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"] \
					 -font $GUIDisplayData("LabelFont")\
					 -wraplength $GUIDisplayData("LabelWrapLength") \
					 -justify $GUIDisplayData("LabelJustify")]

	set Min  [$GUITree get $NodeID -key "Min"]
	set Max  [$GUITree get $NodeID -key "Max"]
	set Incr [$GUITree get $NodeID -key "Increment"]
	set Range [list $Min $Max $Incr]
	set Proc [$GUITree get $NodeID -key "Proc"]

	# Create the variable name in the proper namespace
	set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]

	set IntegerSpin [SpinBox $Parent.$NodeID-SpinBox -range $Range -textvariable $VariableName \
			-font $GUIDisplayData("EntryFont") -width $GUIDisplayData("TextEntryWidth")]
	$Parent.$NodeID-SpinBox.arrup configure -height 0 -width 0
	$Parent.$NodeID-SpinBox.arrdn configure -height 0 -width 0
	set Default [$GUITree get $NodeID -key "Default"]
	if {$Default!=""} {$Parent.$NodeID-SpinBox setvalue $Default}

	set ButBox [ButtonBox $Parent.$NodeID-buttonbox -spacing [expr $GUIDisplayData("ImageSize") / 4] -padx 1 -pady 1]
	set FileName [GetFileName [file join $CATRootDir "icons" "select_dynamicID24.gif"]]
	set im1 [image create photo -format GIF -file $FileName]
	$ButBox add -image $im1 -highlightthickness 0 -takefocus 0 -relief link \
				-borderwidth 1 -padx 1 -pady 1 -helptext "Increment/Decrement on screen" -command "$Proc"
	# Grid it in
	grid configure $Label -row $Row -column 0 -sticky e
	grid configure $IntegerSpin -row $Row -column 1 \
			-columnspan 2 -sticky ew -padx $GUIDisplayData("DEZPadx")
	grid configure $ButBox -row $Row -column 3 -sticky w 
    
    $GUITree set $NodeID -key "WindowPath" [list $Label $IntegerSpin $ButBox]
}

proc ::AIEnv::GUIManagement::leaveIntegerEntryIconBuild {NodeID} {
	# Intentionally empty
}


# --- Icon Button Group ------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterIconButtonGroupBuild {NodeID} {
   variable CATRootDir
   variable GUIDisplayData
   variable IconDir

   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]
   set GUITree [TreeStack peek_one]

   set ObjectName [GetObject]
   set Name [$GUITree get $NodeID -key "Name"]
   set Proc [$GUITree get $NodeID -key "Proc"]
 
   set nbuts [$GUITree get $NodeID -key "NumButtons"]
   
   set wp ""
   set Fm [frame $Parent.$NodeID-fm -bd 0 -relief flat]

   set buts ""
   for {set i 0} {$i < $nbuts} {incr i} {
      set rr [$GUITree get $NodeID -key "Button_$i"]
      set key [lindex $rr 0]
      set tip [lindex $rr 1]
      set img [image create photo -format GIF -file \
                [GetFileName [file join $CATRootDir "$IconDir" [lindex $rr 2]]]]
      lappend buts [Button $Fm.b$i -image $img -highlightthickness 0 \
             -takefocus 0 -relief link -borderwidth 1 -padx 1 -pady 1 \
             -helptext $tip -command "$Proc $key"]
   }
   eval pack $buts -anchor [$GUITree get $NodeID -key "Anchor"] \
                   -side   [$GUITree get $NodeID -key "Side"]

   grid configure $Fm -row $Row -column 1 -columnspan 2 -sticky ew
   lappend wp $Fm

   $GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::leaveIconButtonGroupBuild {NodeID} {
}

# --- Text Button ------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterTextButtonBuild {NodeID} {
    variable GUIDisplayData
    set RowParent [DEZInsert 1]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
	set GUITree [TreeStack peek_one]
	
	set ObjectName [GetObject]
	set Proc [$GUITree get $NodeID -key "Proc"] 
	set Button [button $Parent.$NodeID-btn -text [$GUITree get $NodeID -key "Label"] \
					   -command "$ObjectName proc $Proc" \
					   -height $GUIDisplayData("ButtonHeight") \
					   -font $GUIDisplayData("ButtonFont")]

	# The button should span 2 columns since it might be large and nothing
        # else is going there
	grid configure $Button -row $Row -column 0 -columnspan 2 -sticky w \
		 -pady $GUIDisplayData("ButtonPad")

	$GUITree set $NodeID -key "WindowPath" $Button
}

proc ::AIEnv::GUIManagement::leaveTextButtonBuild {NodeID} {
	# Intentionally empty
}

# --- Table ------------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterTableBuild {NodeID} {
	# Intentionally empty
}

proc ::AIEnv::GUIManagement::leaveTableBuild {NodeID} {
	# Intentionally empty
}

# --- Group ------------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterGroupBuild {NodeID} {
	# Intentionally empty
}

proc ::AIEnv::GUIManagement::leaveGroupBuild {NodeID} {
	# Intentionally empty
}

# --- Check Item -------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterCheckItemBuild {NodeID} {
    variable GUIDisplayData
    set RowParent [DEZInsert 1]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
	set GUITree [TreeStack peek_one]
	
	# Create the variable name in the proper namespace
	set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]

	set ObjectName [GetObject]

	set CheckItem [checkbutton $Parent.$NodeID-CheckBox -text [$GUITree get $NodeID -key "Label"] \
				   -offvalue 0 -onvalue 1 -variable $VariableName \
    				   -wraplength $GUIDisplayData("CheckLabelWrapLength") \
				   -font $GUIDisplayData("CheckButtonFont") \
				   -justify left]


	
	set theProc [$GUITree get $NodeID -key "Proc"]
	if { $theProc != "NULL" } {
		$CheckItem configure -command "$ObjectName proc $theProc"
	}

	#grid it in
	grid configure $CheckItem -row $Row -column 0 -columnspan 3 -sticky sw
	#grid configure $CheckItem -row $Row -column 0 -sticky sw

	$GUITree set $NodeID -key "WindowPath" $CheckItem
}

proc ::AIEnv::GUIManagement::leaveCheckItemBuild {NodeID} {
	# Intentionally empty
}

# --- Check Item -------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterCheckItem2Build {NodeID} {
    variable GUIDisplayData
    set RowParent [DEZInsert 1]
    set Row [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]
    set GUITree [TreeStack peek_one]
    
    # Create the variable name in the proper namespace
    set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
    set ObjectName [GetObject]    
#check item
    set CheckItem [checkbutton $Parent.$NodeID-CheckBox -text [$GUITree get $NodeID -key "Label"] \
		       -offvalue 0 -onvalue 1 -variable $VariableName \
		       -wraplength $GUIDisplayData("CheckLabelWrapLength") \
		       -font $GUIDisplayData("CheckButtonFont") \
		       -justify left]    
    set theProc [$GUITree get $NodeID -key "Proc"]
    if { $theProc != "NULL" } {
	$CheckItem configure -command "$ObjectName proc $theProc"
    }

#button 1
    set Proc1 [$GUITree get $NodeID -key "Proc1"]
    set Button1 [button $Parent.$NodeID-btn1 -text [$GUITree get $NodeID -key "Label1"] \
		     -command "$ObjectName proc $Proc1" \
		     -height $GUIDisplayData("ButtonHeight") \
		     -font $GUIDisplayData("ButtonFont")]

    set Proc2 [$GUITree get $NodeID -key "Proc2"]
    set Button2 [button $Parent.$NodeID-btn2 -text [$GUITree get $NodeID -key "Label2"] \
		     -command "$ObjectName proc $Proc2" \
		     -height $GUIDisplayData("ButtonHeight") \
		     -font $GUIDisplayData("ButtonFont")]

    trace variable $VariableName w "::AIEnv::GUIManagement::ToggleGreyCheckItem2 $NodeID $VariableName"

    #grid it in
    grid configure $CheckItem -row $Row -column 0 -sticky sw
    grid configure $Button1   -row $Row -column 1 -sticky sw
    grid configure $Button2   -row $Row -column 2 -sticky sw
    
    $GUITree set $NodeID -key "WindowPath" [list $CheckItem $Button1 $Button2]
}

proc ::AIEnv::GUIManagement::leaveCheckItem2Build {NodeID} {    	
}

proc ::AIEnv::GUIManagement::ToggleGreyCheckItem2 {NodeID varname args} {
    set GUITree [TreeStack peek]
    set on [set $varname]
    set WindowPaths [$GUITree get $NodeID -key "WindowPath"]
    foreach w [lrange $WindowPaths 1 end] {
	if $on {
	    $w configure -state normal
	} else {
	    $w configure -state disabled
	}
    }
}

# --- Pick Screen Coordinate -------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterPickScreenCoordBuild {NodeID} {
    variable GUIDisplayData
    variable BuildContext
    variable CATRootDir
	set RowParent [DEZInsert 1]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
	
	set GUITree [TreeStack peek_one]
	
	set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"] \
										 -font $GUIDisplayData("LabelFont")\
										 -wraplength $GUIDisplayData("LabelWrapLength") \
										 -justify $GUIDisplayData("LabelJustify")]
	
	# Create the variable name in the proper namespace
	set ListVariableName [CreateVariable [$GUITree get $NodeID -key "ListName"]]
	
	set Text [entry $Parent.$NodeID-text -textvariable $ListVariableName \
		-font $GUIDisplayData("EntryFont") -background white \
		-width $GUIDisplayData("TextEntryWidth")]
	
	set Name [$GUITree get $NodeID -key "Name"]
	set AutoApply [$GUITree get $NodeID -key "AutoApply"]
	set MaxNumber [$GUITree get $NodeID -key "MaxNumber"]
	
	# Create the toolbar that will hold the selector tools                                       
	set ButBox [ButtonBox $Parent.$NodeID-buttonbox -spacing [expr $GUIDisplayData("ImageSize") / 4] -padx 1 -pady 1]
	set FileName [GetFileName [file join $CATRootDir "icons" "select_location$icon_size1.gif"]]
	set im1 [image create photo -format GIF -file $FileName]
	set FileName [GetFileName [file join $CATRootDir "icons" "moreButton.gif"]]
	set im2 [image create photo -format GIF -file $FileName]

	set SelectionType [$GUITree get $NodeID -key "ChoiceType"]
#    puts "$Parent.$NodeID  -> $SelectionType"
	set Parent [GetObject]
	BeginTypeDefinition Picker
		BeginObjectDefinition $Name
			$Name set -key variable $ListVariableName
			$Name set -key type $SelectionType
			$Name set -key maxNumber $MaxNumber
			$Name set -key requireExactNumber 1
			$Name set -key parent $Parent
			$Name set -key autoApply $AutoApply
			$Name set -key selectMessage ""
			$Name set -key selectOptions ""
		EndObjectDefinition
	EndTypeDefinition
	
	$ButBox add -image $im1 -highlightthickness 0 -takefocus 0 -relief link \
				-borderwidth 1  -padx 1 -pady 1 -helptext "Choose an item" \
				-command "$Name pick"
	
	set EnableMulti active
		
	$ButBox add -text ". . ." -highlightthickness 0 -takefocus 0 -relief link \
				-borderwidth 1 -padx 1 -pady 1 -helptext "More" -state $EnableMulti \
				-font $GUIDisplayData("DEZTitleFont") -command "$Name showItems"
				
	# Pack everything in
	grid configure $Label -row $Row -column 0 -sticky e 
	grid configure $Text -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
	grid configure $ButBox -row $Row -column 2 -sticky w 

	$GUITree set $NodeID -key "WindowPath" [list $Label $Text $ButBox]
}

proc ::AIEnv::GUIManagement::leavePickScreenCoordBuild {NodeID} {
	# Intentionally empty
}

# TO DO: The table editor is not fully implemented.  This function will need to 
# be revisited to add support for a table editor

proc ::AIEnv::GUIManagement::enterDataTableBuild {NodeID} {
    variable GUIDisplayData
    variable CATRootDir
    set GUITree [TreeStack peek_one]
    
    this code is not used 

    set RowParent [DEZInsert 1]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]

	set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"] \
										 -font $GUIDisplayData("LabelFont")\
										 -wraplength $GUIDisplayData("LabelWrapLength") \
										 -justify $GUIDisplayData("LabelJustify")]
	set TableVariableName [$GUITree get $NodeID -key "TableVariable"]
	
	# TO DO, register this variable
	# AddDEZVariable [GetCurrentDEZName] [$GUITree get $NodeID -key "TableVariable"]

	set Text [entry $Parent.$NodeID-text -textvariable $TableVariableName \
			-font $GUIDisplayData("EntryFont") \
			-width $GUIDisplayData("TextEntryWidth")]

	# Create the toolbar that will hold the table                                       
	set ButBox [ButtonBox $Parent.$NodeID-buttonbox -spacing [expr $GUIDisplayData("ImageSize") / 4] -padx 1 -pady 1]
	set FileName [GetFileName [file join $CATRootDir "icons" "Table.gif"]]
	set im1 [image create photo -format GIF -file $FileName]
	$ButBox add -image $im1 -highlightthickness 0 -takefocus 0 -relief link \
				-borderwidth 1  -padx 1 -pady 1 -helptext "Edit Table" \
				-command "::AIEnv::GUIManagement::TableEditor $NodeID"

	grid configure $Label -row $Row -column 0 -sticky e 
	grid configure $Text -row $Row -column 1 -sticky ew -padx $GUIDisplayData("DEZPadx")
	grid configure $ButBox -row $Row -column 2 -sticky w 

	$GUITree set $NodeID -key "WindowPath" [list $Label $Text $ButBox]
}

proc ::AIEnv::GUIManagement::leaveDataTableBuild {NodeID} {
	# Intentionally empty
}


# --- Dialog Space -----------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterDialogSpaceBuild {NodeID} {
    variable GUIDisplayData
    set GUITree [TreeStack peek_one]
    set Quantity [$GUITree get $NodeID -key "Quantity"]
    set RowParent [DEZInsert $Quantity 0.5]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
	set SpacerFrame [frame $Parent.$NodeID]
	grid configure $SpacerFrame -row $Row -column 0 -columnspan 3 \
								-rowspan $Quantity -sticky nsew

   # $SpacerFrame configure -background blue
}

proc ::AIEnv::GUIManagement::leaveDialogSpaceBuild {NodeID} {
	# Intentionally empty
}

# --- Text Label --------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterTextLabelBuild {NodeID} {
    set GUITree [TreeStack peek_one]
    variable GUIDisplayData
    variable CATRootDir

    set RowParent [DEZInsert 1]
    set Row [lindex $RowParent 0]
    set Parent [lindex $RowParent 1]
    set Label [$GUITree get $NodeID -key "Label"]
    set Image [$GUITree get $NodeID -key "Image"]

    set Label [label $Parent.$NodeID-label \
		   -text $Label \
		   -wraplength $GUIDisplayData("LabelWrapLength") \
		   -font $GUIDisplayData("LabelFont") -justify center]

    if {$Image != "NULL"} {
	set im [image create photo -format GIF -file $CATRootDir/icons/$Image]
        $Label configure -image $im
    }
    grid configure $Label -row $Row -column 0 -columnspan 3 -sticky ew
    
    $GUITree set $NodeID -key "WindowPath" $Label
}

proc ::AIEnv::GUIManagement::leaveTextLabelBuild {NodeID} {
        # Intentionally empty
}


# --- AmpEntry 
proc ::AIEnv::GUIManagement::enterAmpEntryBuild {NodeID} {
   set GUITree [TreeStack peek_one]
   variable GUIDisplayData
   variable CATRootDir
   variable IconDir

   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set Label [label $Parent.$NodeID-label -text [$GUITree get $NodeID -key "Label"]  \
                   -font $GUIDisplayData("LabelFont") \
                   -wraplength $GUIDisplayData("LabelWrapLength") \
                   -justify $GUIDisplayData("LabelJustify") ]
   
   set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
   
   set Text [entry $Parent.$NodeID-text -textvariable $VariableName \
                      -font $GUIDisplayData("EntryFont") \
                      -foreground black \
                      -background white -width $GUIDisplayData("TextEntryWidth")]
   grid configure $Label -row $Row -column 0 -sticky e
   grid configure $Text -row $Row -column 1 -columnspan 2 -sticky ew -padx $GUIDisplayData("DEZPadx")

   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set Proc [$GUITree get $NodeID -key "Proc"]

   set BarVarName [CreateVariable [$GUITree get $NodeID -key "BarVar"]]
   set ScaleFm [frame $Parent.$NodeID-scalefm -bd 0 -relief flat]
   set Scale [scale $Parent.$NodeID-scalefm.sc -label "" -orient h -command "" \
                    -variable $BarVarName -from -1.0 -to 1.0 -showvalue 0 \
                    -resolution 0.001 -length $GUIDisplayData("TextEntryWidth")]
     bind $Scale <ButtonRelease-1> "::AIEnv::GUIManagement::AmpEntryCmd $VariableName $BarVarName \"$Proc\""
   grid configure $Scale -row 0 -column 0 -columnspan 2 -sticky ew \
                      -padx $GUIDisplayData("DEZPadx")
   grid columnconfigure $ScaleFm 0 -weight 100
   grid configure $ScaleFm -row $Row -column 1 -columnspan 2 -sticky ew

   $GUITree set $NodeID -key "WindowPath" [list $Label $Text $ScaleFm]
}

proc ::AIEnv::GUIManagement::leaveAmpEntryBuild {NodeID} {

}

proc ::AIEnv::GUIManagement::AmpEntryCmd {VariableName BarVarName Proc args} {
   set am [set $VariableName]; set bv [set $BarVarName]
   if {![string is double -strict $am] || \
       ![string is double -strict $bv] || ($bv == 0)} {return ""}

   set am [num_get_trunc [expr $am * pow(2, $bv)] 5]
   set $BarVarName 0
   set $VariableName $am
   if {$Proc != ""} { eval $Proc $am }
}


# --- Animator
proc ::AIEnv::GUIManagement::enterAnimatorBuild {NodeID} {
   set GUITree [TreeStack peek_one]
   variable GUIDisplayData
   variable CATRootDir
   variable IconDir

   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
   set MinVal [$GUITree get $NodeID -key "MinVal"]
   set MaxVal [$GUITree get $NodeID -key "MaxVal"]
   set IncVal [$GUITree get $NodeID -key "IncVal"]
   set Proc [$GUITree get $NodeID -key "Proc"]
   set ValOn [$GUITree get $NodeID -key "ValOn"]
   set Length [$GUITree get $NodeID -key "Length"]


   set BoxFm [frame $Parent.$NodeID-boxfm -bd 2 -relief flat]
   set ButBox [ButtonBox $Parent.$NodeID-boxfm.bbx -spacing 1 -padx 1 -pady 1]
   foreach {k f h} {animate play Animate  stop stop Stop \
                    incr forward "Forward step" back backward "Backward step"} {
      set FileName [GetFileName [file join $CATRootDir "$IconDir" "TTK$f.gif"]]
      set im [image create photo -format GIF -file $FileName]
      $ButBox add -image $im -highlightthickness 0 -takefocus 0 \
                  -relief link -borderwidth 1  -padx 1 -pady 1 \
                  -helptext $h -command "$Proc $k $VariableName"
   }
   grid configure $ButBox -row 0 -column 0 -columnspan 2 -sticky w
 
   set Entry [entry $Parent.$NodeID-boxfm.ent -textvariable $VariableName \
                    -font $GUIDisplayData("EntryFont") -foreground black \
                    -background white -width 6]
      bind $Entry <Return> "$Proc instant $VariableName"
   grid configure $Entry -row 0 -column 2 -sticky e -padx 2

   grid columnconfigure $BoxFm 0 -weight 0
   grid columnconfigure $BoxFm 2 -weight 100
   grid configure $BoxFm -row $Row -column 0 -columnspan 3 -sticky ew

   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set ScaleFm [frame $Parent.$NodeID-scalefm -bd 0 -relief flat]
   set Scale [scale $Parent.$NodeID-scalefm.sc -label "" -orient h \
                    -variable $VariableName -command "" \
                    -from $MinVal -to $MaxVal -resolution $IncVal \
                    -length $Length -showvalue 0]
     bind $Scale <ButtonRelease-1> "$Proc instant $VariableName"
   grid configure $Scale -row 0 -column 0 -columnspan 3 -sticky ew \
                      -padx $GUIDisplayData("DEZPadx")
   grid columnconfigure $ScaleFm 0 -weight 100
   grid configure $ScaleFm -row $Row -column 0 -columnspan 3 -sticky ew
   
   $GUITree set $NodeID -key "WindowPath" [list $BoxFm $ScaleFm]
}

proc ::AIEnv::GUIManagement::leaveAnimatorBuild {NodeID} {
   #empty
}


# --- Scale Bar --------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterScaleBarBuild {NodeID} {
   set GUITree [TreeStack peek_one]
   variable GUIDisplayData
   
   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]
   
   set Label [$GUITree get $NodeID -key "Label"]
   set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
   set MinVal [$GUITree get $NodeID -key "MinVal"]
   set MaxVal [$GUITree get $NodeID -key "MaxVal"]
   set IncVal [$GUITree get $NodeID -key "IncVal"]
   set Proc [$GUITree get $NodeID -key "Proc"]
   set ValOn [$GUITree get $NodeID -key "ValOn"]
   set Length [$GUITree get $NodeID -key "Length"]
   set OneRow [$GUITree get $NodeID -key "OneRow"]
   set AddLabel [$GUITree get $NodeID -key "AddLabel"]
   if {$ValOn} {
      set Scale [scale $Parent.$NodeID-scale -label $Label -orient h \
                     -font $GUIDisplayData("LabelFont") \
                     -variable $VariableName -command "" \
                     -from $MinVal -to $MaxVal -resolution $IncVal \
                     -length $Length -showvalue $ValOn]
      grid configure $Label -row $Row -column 0 -columnspan 3 -sticky ew \
                                     -padx $GUIDisplayData("DEZPadx")

      $GUITree set $NodeID -key "WindowPath" $Scale
   } else {
      set Label [label $Parent.$NodeID-label -text $Label \
                     -font $GUIDisplayData("LabelFont") -justify left]

      set nc_scale 1
      set px_scale 0
      if {!$OneRow} {
         grid configure $Label -row $Row -column 0 -columnspan 3 -sticky w

         set RowParent [DEZInsert 1]
         set Row [lindex $RowParent 0]
         set Parent [lindex $RowParent 1]

         set nc_scale 2
         set px_scale $GUIDisplayData("DEZPadx")
      }

      set ScaleFm [frame $Parent.$NodeID-scalefm -bd 0 -relief flat]
      set Entry [entry $Parent.$NodeID-scalefm.ev -textvariable $VariableName \
                    -font $GUIDisplayData("EntryFont") -foreground black \
                    -background white -width 5]
      bind $Entry <KeyRelease> "::AIEnv::GUIManagement::entryScaleBarAfter \
                            1000 $Proc -1 $VariableName"  
      if {$AddLabel != "NULL"} {
          set Label2 [label $Parent.$NodeID-scalefm.label2 -text "$AddLabel" \
                     -font $GUIDisplayData("LabelFont") -justify left]
      }
      set Scale [scale $Parent.$NodeID-scalefm.sc -label "" -orient h \
                    -variable $VariableName -command "" \
                    -from $MinVal -to $MaxVal -resolution $IncVal -sliderlength 6 \
                    -length $Length -showvalue 0]
      grid configure $Entry -row 0 -column 0 -sticky e
      if {$AddLabel != "NULL"} {
          grid configure $Label2 -row 0 -column 1 -sticky ew 
          grid configure $Scale -row 0 -column 2 -columnspan $nc_scale -sticky ew \
                                -padx $px_scale
      } else {
          grid configure $Scale -row 0 -column 1 -columnspan $nc_scale -sticky ew \
                                -padx $px_scale
      }
      grid columnconfigure $ScaleFm 0 -weight 0
      if {$AddLabel != "NULL"} {
          grid columnconfigure $ScaleFm 1 -weight 0
          grid columnconfigure $ScaleFm 2 -weight 100
      } else {
          grid columnconfigure $ScaleFm 1 -weight 100
      }
      if {!$OneRow} {
         grid configure $ScaleFm -row $Row -column 0 -columnspan 3 -sticky new
      } else {
         grid configure $Label -row $Row -column 0 -columnspan 1 -sticky e
         grid configure $ScaleFm -row $Row -column 1 -columnspan 2 -sticky ew \
                                 -padx $GUIDisplayData("DEZPadx")
      }
      if {$AddLabel != "NULL"} {
          $GUITree set $NodeID -key "WindowPath" [list $Label $Label2 $ScaleFm]
      } else {
          $GUITree set $NodeID -key "WindowPath" [list $Label $ScaleFm]
      }
   }
   bind $Scale <ButtonPress-1> "$Proc 1 $VariableName"
   bind $Scale <Button1-Motion> "$Proc 0 $VariableName" 
   bind $Scale <ButtonRelease-1> "$Proc -1 $VariableName"
}

proc ::AIEnv::GUIManagement::entryScaleBarAfter {ms args} {
   variable entry_scalrbar_after_id

   if [info exist entry_scalrbar_after_id] {
      if ![catch {set ss [after info $entry_scalrbar_after_id]}] {
         if {[lindex $ss 0] == $args} {after cancel $entry_scalrbar_after_id}
      }
   }
   set entry_scalrbar_after_id [after $ms $args]
}


proc ::AIEnv::GUIManagement::leaveScaleBarBuild {NodeID} {
        # don't what need to be done
}

# --- List Box --------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterListBoxBuild {NodeID} {
	variable GUIDisplayData

	set GUITree [TreeStack peek_one]
	set Name [$GUITree get $NodeID -key "Name"]
	set Height [$GUITree get $NodeID -key "Height"]

	set MListName [$GUITree get $NodeID -key "ListVariable"]
	set SelectVName [$GUITree get $NodeID -key "SelectionVariable"]
	#[CreateVariable [$GUITree get $NodeID -key "Variable"]]
	set ListVar [CreateVariable $MListName]
	set SeleVar [CreateVariable $SelectVName]

        set Proc [$GUITree get $NodeID -key "Proc"]
        if {$Proc == "NULL"} {set Proc ""}
        set DkProc [$GUITree get $NodeID -key "DkProc"]
        if {$DkProc == "NULL"} {set DkProc ""}
	set MultiFlag [$GUITree get $NodeID -key "MultiSelectFlag"]
	
	set UseYS [$GUITree get $NodeID -key "YScroll"]
	set UseXS [$GUITree get $NodeID -key "XScroll"]

	set RowParent [DEZInsert $Height 0.5]
	set TopRow [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
	
	if { $MultiFlag == 1 } {
		set SelectionMode multiple
	} else {
		set SelectionMode single
	}
	set OuterFrame [frame $Parent.$NodeID]
	set ListBox [listbox $OuterFrame.listbox -height $Height \
	                     -listvar $ListVar -selectmode $SelectionMode \
			     -font $GUIDisplayData("EntryFont") \
	                     -width $GUIDisplayData("TextEntryWidth")] 
	set ParentObject [GetObject]

        set LBVar [CreateVariable listBoxPath]
        set $LBVar $ListBox
        if [info exist $SeleVar] { $ListBox selection set [set $SeleVar] }

        if {$Proc != ""} {
           bind $ListBox <ButtonRelease-1> "::AIEnv::GUIManagement::ListBoxSelectionCmd \
                           $ListBox $NodeID $ParentObject $MListName $SelectVName \"$Proc\""
        }
        if {$DkProc != ""} {
           bind $ListBox <Double-Button-1> "::AIEnv::GUIManagement::ListBoxSelectionCmd \
                           $ListBox $NodeID $ParentObject $MListName $SelectVName \"$DkProc\""
        }
	bind $ListBox <FocusOut> "::AIEnv::GUIManagement::UpdateListBoxSelection $ListBox $NodeID $ParentObject"
	grid $ListBox -row 0 -column 0 -sticky nsew
	lappend wp $ListBox
	
	if {$UseXS} {
	   set XScroll [scrollbar $OuterFrame.xscroll -command "$ListBox xview" -orient horizontal]
	   $ListBox configure -xscrollcommand "$XScroll set"
	   grid $XScroll -row 1 -column 0 -sticky new
	   lappend wp $XScroll
	}

	if {$UseYS} {
	   set YScroll [scrollbar $OuterFrame.yscroll -command "$ListBox yview" -orient vertical]
	   $ListBox configure -yscrollcommand "$YScroll set"
	   grid $YScroll -row 0 -column 1 -sticky nse
	   lappend wp $YScroll           
	}
	
	grid rowconfigure $OuterFrame 0 -weight 10
	grid rowconfigure $OuterFrame 1 -weight 0
	grid columnconfigure $OuterFrame 0 -weight 10
	grid columnconfigure $OuterFrame 1 -weight 0
	
	grid $OuterFrame -row $TopRow -column 0 -columnspan 3 -rowspan [expr $Height/2] -sticky nsew
	
 	grid columnconfigure $Parent 0 -weight 1000

	$GUITree set $NodeID -key "WindowPath" $wp
}

proc ::AIEnv::GUIManagement::ListBoxSelectionCmd {ListBox NodeID ParentObject MListName SelectVName Proc args} {
   set SelectionIndices [$ListBox curselection]
   set MasterList [$ParentObject get $MListName]
   set Selection ""
   foreach Index $SelectionIndices {
      lappend Selection [lindex $MasterList $Index]
   }
   $ParentObject set $SelectVName $SelectionIndices

   if {$Proc != ""} {
      lappend Proc $SelectionIndices $Selection $ListBox
      eval "$Proc $args"
   }
}

proc ::AIEnv::GUIManagement::UpdateListBoxSelection {ListBox NodeID ParentObject} {
	set SelectionIndices [$ListBox curselection]
	set MasterListName [$GUITree get $NodeID -key "ListVariable"]
	set SelectionVarName [$GUITree get $NodeID -key "SelectionVariable"]
	set MasterList [$ParentObject get $MasterListName]
	set Selection ""
	foreach Index $SelectionIndices {
		lappend Selection [lindex $MasterList $Index]
	}
	$ParentObject set $SelectionVarName $Selection
	
}

proc ::AIEnv::GUIManagement::leaveListBoxBuild {NodeID} {
	# Intentionally empty
}

# --- Entity Mover -----------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterEntityMoverBuild {NodeID} {

	variable GUIDisplayData
	variable BuildContext
	variable CATRootDir
	set GUITree [TreeStack peek_one]
	
	set RowParent [DEZInsert 1]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
	
	set Name [$GUITree get $NodeID -key "Name"]
	
	set InvertFlag ${NodeID}Invert
	set CheckBox [checkbutton $Parent.$NodeID-check -text "Allow degenerate elements"  
				-variable $InvertFlag \
				-font GUIDisplayData("CheckButtonFont") \
	            -onvalue 1 -offvalue 0]
	set ButtonBox [ButtonBox $Parent.$NodeID-buttonbox -spacing [expr $GUIDisplayData("ImageSize") / 4]  \
	                                                   -padx 1 -pady 1]
	set FileName [GetFileName [file join $CATRootDir "icons" "offsetNodes.gif"]]
	set im1 [image create photo -format GIF -file $FileName]
	
	BeginTypeDefinition NodeMover
		BeginObjectDefinition $Name
			$Name set -key invertFlag $InvertFlag
		EndObjectDefinition
	EndTypeDefinition
	
	set helpText "Move Nodes"
	$ButtonBox add -image $im1 -highlightthickness 0 -takefocus 0 -relief link \
				-borderwidth 1  -padx 1 -pady 1 -helptext $helpText \
				-command "$Name move"
	
	$GUITree set $NodeID -key "WindowPath" [list $CheckBox $ButtonBox]
	grid $CheckBox -row $Row -column 0 -columnspan 2 -sticky w
	grid $ButtonBox -row $Row -column 2 -sticky e
	
}

proc ::AIEnv::GUIManagement::leaveEntityMoverBuild {NodeID} {
	# Intentionally empty
}

# --- Data Entry Dialog --------------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterDataEntryDialogBuild {NodeID} {
    global dontSaveDEZ

    BeginTypeDefinition DEZ
    set GUITree [TreeStack peek_one]
    set Name [$GUITree get $NodeID -key "Name"]
    set saveFlag [$GUITree get $NodeID -key "saveFlag"]        
    BeginPredefinedObject $Name
    $Name create $NodeID
    
    if !$saveFlag {
        set dontSaveDEZ($Name) 1
    }
}

proc ::AIEnv::GUIManagement::leaveDataEntryDialogBuild {NodeID} {
	EndPredefinedObject
	EndTypeDefinition 
}

#---------------------------------------------------------------------------------------------------
proc ::AIEnv::GUIManagement::enterMultiSelectBuild { NodeID } {
	set GUITree [TreeStack peek_one]
	set Name [$GUITree get $NodeID -key "Name"]
	set ParentObject [GetObject]
	
	# Create a variable in the DEZ's context that we can write to in order
	# to signal that the DEZ is ready for update
	set DirtyFlag [CreateVariable $NodeID-dirty]
	
	BeginTypeDefinition MultiSelect
		BeginObjectDefinition $Name
			$Name set -key "title" [$GUITree get $NodeID -key "Title"]
			$Name set -key "rowLabel" [$GUITree get $NodeID -key "RowLabelList"]
			$Name set -key "columnLabel" [$GUITree get $NodeID -key "ColumnLabelList"]
			$Name set -key "rowExclusive" [$GUITree get $NodeID -key "Exclusive"]
			$Name set -key "parent" $ParentObject
			$Name set -key "nodeID" $NodeID
			$Name set -key "dirtyFlag" $DirtyFlag
		EndObjectDefinition
	EndTypeDefinition
	
	$Name build
}

proc ::AIEnv::GUIManagement::leaveMultiSelectBuild { NodeID } {
	# Intentionally empty	
}

#----------------------------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterMultiSelectRowsBuild { NodeID } {
	# The select rows node is only used as a place holder during parsing
}

proc ::AIEnv::GUIManagement::leaveMultiSelectRowsBuild { NodeID } {
	# The select rows node is only used as a place holder during parsing	
}

#----------------------------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterMultiSelectColumnsBuild { NodeID } {
	# The select columns node is only used as a place holder during parsing	
}

proc ::AIEnv::GUIManagement::leaveMultiSelectColumnsBuild { NodeID } {
	# The select columns node is only used as a place holder during parsing	
}

#----------------------------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterDialogWindowBuild { NodeID } {
	# Intentionally empty
}

proc ::AIEnv::GUIManagement::leaveDialogWindowBuild { NodeID } {
	# Intentionally empty
}

proc ::AIEnv::GUIManagement::enterDialogWindowRootBuild { NodeID }  {
	# Intentionally empty
}

proc ::AIEnv::GUIManagement::leaveDialogWindowRootBuild { NodeID } {
	# Intentionally empty
}



#---------------------------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterGreyGroupBuild {NodeID} {
	# Get all of the children for this item in the tree.  These are
	# the grey groups to be displayed
	set GUITree [TreeStack peek_one]
	set Children [$GUITree children $NodeID]

	set GreyGroupItems ""
	foreach Child $Children {
		if { [$GUITree get $Child -key "Type"] == "GreyGroupItem" } {
			lappend GreyGroupItems $Child
		}
	}

	set NumItems [llength $GreyGroupItems]
	set NumCols 2
	
	set Rows [ceil [expr double($NumItems) / $NumCols]]
	# Add one row for the frame label
	incr Rows
	
	variable GUIDisplayData
    # Create the variable name in the proper namespace
    set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
    $GUITree set $NodeID -key "FullyQualifiedVariable" $VariableName
    variable $VariableName
    set $VariableName 0
	set ObjectName [GetObject]
	set userProc ""
	set Proc [$GUITree get $NodeID -key "Proc"]
	if { $Proc != "NULL" } {
	    set userProc $Proc
	}

	# If the number of grey group items is one,then we just add a check
	# button and a single grey item.  Otherwise we create the radio button
	# group
	if { [llength $GreyGroupItems] == 1} {
		# Compute how many children the one grey Item has so we can get the number of
		# rows we will need in the DEZ
		set GreyGroupItem [lindex $GreyGroupItems 0]


		set RowParent [DEZInsert 1 0.5]
		set TopRow [lindex $RowParent 0]
		set Parent [lindex $RowParent 1]

		set label [$GUITree get $NodeID -key "Label"]
		set GreyCheck [checkbutton $Parent.$NodeID-CheckBox -text $label \
		   	-offvalue 0 -onvalue 1 -variable $VariableName \
			-font $GUIDisplayData("CheckButtonFont") \
    			-wraplength $GUIDisplayData("CheckLabelWrapLength") \
			-command "::AIEnv::GUIManagement::GreyGroupProc $NodeID; $ObjectName proc $userProc" \
			-justify left]	
				   	
		$GUITree set $NodeID -key "WindowPath" $GreyCheck
	   # $Parent configure -background black
		set GIChildren [$GUITree children $GreyGroupItem]
		set Rows [llength $GIChildren]
		set checkEntry 0		
		if {$Rows == 1} {
		    set child0 [lindex $GIChildren 0]
		    if { [$GUITree get $child0 -key "Type"] == "TextEntry" } {
			set text [$GUITree get $child0 -key "Label"]
			# don't wrap if the text string is < 25
			if {[string length "$label$text"] < 25} {
			    set checkEntry 1
			}
		    }
		}
		if {$checkEntry} {
		    grid configure $GreyCheck -row $TopRow -column 0 -sticky nsew
		} else {
		    grid configure $GreyCheck -row $TopRow -column 0 -columnspan 3 -sticky sw
		}

		set trow $TopRow
		# This takes care of the check box
		set RowParent [DEZInsert $Rows 0.5]
		set TopRow [lindex $RowParent 0]
		set Parent [lindex $RowParent 1]
		# Create the interior frame
		set InteriorFrame [frame $Parent.$NodeID-iFrame]
		if {$checkEntry} {
		    grid configure $InteriorFrame -row $trow -column 1 -columnspan 2 -sticky nsew
		} else {
		    grid configure $InteriorFrame -row $TopRow -column 0 -columnspan 3 -sticky nsew -rowspan $Rows
		}

		# configure the Interior frame
		grid columnconfigure $InteriorFrame 0 -weight 0
		grid columnconfigure $InteriorFrame 1 -weight 1
		grid columnconfigure $InteriorFrame 2 -weight 0


		WindowPathStack push $InteriorFrame
		DEZRowCountStack push 0

	} elseif { [llength $GreyGroupItems] > 1} {
		set RowParent [DEZInsert $Rows 1]
		set TopRow [lindex $RowParent 0]
		set Parent [lindex $RowParent 1]
		set LabFrame [TitleFrame $Parent.$NodeID-tf -text [$GUITree get $NodeID -key "Label"] \
				-font $GUIDisplayData("DEZTitleFont")]
		set InteriorFrame [$LabFrame getframe]
		
		lappend WindowPaths $LabFrame
		# Configure the interior frame
		for {set i 0} {$i < $NumCols} {incr i} {
			grid columnconfigure $InteriorFrame $i -weight 0
		}
		grid columnconfigure $InteriorFrame $NumCols -weight 1

		# grid in the radio button group frame
		grid configure $LabFrame -row $TopRow -column 0 -columnspan 3 -rowspan $Rows -sticky nsew -pady $GUIDisplayData("DEZPady")

		# Create the actual radio items
		set Col 0
		set Row 0
		set index 0
		foreach ItemNodeID $GreyGroupItems {
			set Label [$GUITree get $ItemNodeID -key "Label"]
			set Radio [radiobutton $InteriorFrame.$ItemNodeID -variable $VariableName \
				   -value $index -text $Label -font $GUIDisplayData("RadioButtonFont") \
				       -command "::AIEnv::GUIManagement::GreyGroupProc $NodeID; $ObjectName proc $userProc"]		
			if {$Col < $NumCols} {
				grid $Radio -row $Row -column $Col -sticky w -padx $GUIDisplayData("DEZPadx")
			} else {
				set Col 0
				incr Row
				grid $Radio -row $Row -column $Col -sticky w -padx $GUIDisplayData("DEZPadx")
			}
			incr Col
			lappend WindowPaths $Radio
			incr index
		}

		$GUITree set $NodeID -key "WindowPath" $WindowPaths
		# grid in the radio button group frame
		grid configure $LabFrame -row $TopRow -column 0 -columnspan 3 -rowspan $Rows -sticky nsew -pady $GUIDisplayData("DEZPady")
	}
}


proc ::AIEnv::GUIManagement::GreyGroupProc {NodeID {Update 1}} {
	ToggleGreyByNodeID $NodeID -1
	if {$Update == 1} {
		update
	}
}

proc ::AIEnv::GUIManagement::leaveGreyGroupBuild {NodeID} {
	
	set GUITree [TreeStack peek_one]
	set Children [$GUITree children $NodeID]
	set GreyGroupItems ""
	foreach Child $Children {
		if { [$GUITree get $Child -key "Type"] == "GreyGroupItem" } {
			lappend GreyGroupItems $Child
		}
	}
	
	if {[llength $GreyGroupItems] == 1} {
		# Toggle all of the items other than the first to grey
		set First [lindex $GreyGroupItems 0]
		set VariableName [GetFullyQualifiedVariableName [$GUITree get $NodeID -key "Variable"]]
		# Pop the frame off of the stack
		WindowPathStack pop
		DEZRowCountStack pop
		if { [info exists $VariableName] } {
			if { [subst $[subst $VariableName]] == 1 } {
				ToggleGreyByNodeID $First 0
			} else {
				ToggleGreyByNodeID $First 1
			}
		} else {
			ToggleGreyByNodeID $First 1
		}
	} else {
		# Toggle all of the items other than the first to grey
		set First [lindex $GreyGroupItems 0]
		ToggleGreyByNodeID $First 0
		for {set i 1} {$i < [llength $GreyGroupItems]} {incr i} {
			ToggleGreyByNodeID [lindex $GreyGroupItems $i] 1
		}
   	}
}

#---------------------------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterGreyGroupItemBuild {NodeID} {
	# Intentionally empty
}

proc ::AIEnv::GUIManagement::leaveGreyGroupItemBuild {NodeID} {
	# Intentionally empty
}

#---------------------------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterExclusiveGroupBuild {NodeID} {
	set GUITree [TreeStack peek_one]
	
	set ExclusiveType [string tolower [$GUITree get $NodeID -key "ExclusiveType"]]
	set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]
	set ProcName [$GUITree get $NodeID -key "Proc"]
	set Parent [GetObject]
	set ChildNodes [$GUITree children $NodeID]
	set Name [$GUITree get $NodeID -key "Name"]
	BeginTypeDefinition ExclusiveGroup
		BeginObjectDefinition $Name
			$Name set -key "type" $ExclusiveType
			$Name set -key "variable" $VariableName
			$Name set -key "selectProc" $ProcName
			$Name set -key "parent" $Parent
			$Name set -key "numCols" [$GUITree get $NodeID -key "NumCols"]
			$Name set -key "nodeID" $NodeID
			$Name set -key "dropDownLabel" [$GUITree get $NodeID -key "DropDownLabel"]
			$Name set -key "frameLabel" [$GUITree get $NodeID -key "FrameLabel"]
			foreach Node $ChildNodes {
				if { [$GUITree get $Node -key "Type"] == "ExclusiveGroupItem" } {
					$Name insertItem [$GUITree get $Node -key "Name"] \
									 [$GUITree get $Node -key "Label"] \
									 [$GUITree get $Node -key "Icon"]
				}
			}
		EndObjectDefinition
	EndTypeDefinition
	
	$Name buildInit
}

proc ::AIEnv::GUIManagement::leaveExclusiveGroupBuild {NodeID} {
	set GUITree [TreeStack peek_one]
	set Name [$GUITree get $NodeID -key "Name"]
	$Name buildFinal
}

#---------------------------------------------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterExclusiveGroupItemBuild {NodeID} {
	variable GUIDisplayData
	set GUITree [TreeStack peek_one]
	set ParentNodeID [$GUITree parent $NodeID]
	set ParentName [$GUITree get $ParentNodeID -key "Name"]
	set ThisName [$GUITree get $NodeID -key "Name"]
	set InnerFrame [$ParentName getItemFrame $ThisName]
	if [aie_wb2_is_running] {
	    if [aie_wb2_is_input_parameter $ThisName [GetObject] ""] {
	        aie_set_global current_wb_input_name $ThisName
            aie_set_global current_wb_input_parameter [$GUITree get $NodeID -key "Label"]
            
        }
    }
	DEZRowCountStack push 0
	WindowPathStack push $InnerFrame
}

proc ::AIEnv::GUIManagement::leaveExclusiveGroupItemBuild {NodeID} {
	DEZRowCountStack pop
	WindowPathStack pop
    if [aie_wb2_is_running] {
        if {[aie_get_global current_wb_input_parameter] == "[[TreeStack peek_one] get $NodeID -key "Label"]"} {
            aie_unset_global current_wb_input_name
            aie_unset_global current_wb_input_parameter
        }
    }
}


proc ::AIEnv::GUIManagement::enterColumnMultiSelectBuild {NodeID} {
	set GUITree [TreeStack peek_one]
	set ParentNodeID [$GUITree parent $NodeID]
	set ParentName [$GUITree get $ParentNodeID -key "Name"]
	set Name [$GUITree get $NodeID -key "Name"]
	set Title [$GUITree get $NodeID -key "Title"]
	BeginTypeDefinition ColumnMultiSelect
	BeginObjectDefinition $Name
	
	$Name create
	$Name set -key "nodeID" $NodeID
	$Name set -key "parent" $ParentName
	$Name set -key "title"  $Title
		
			
		
}

proc ::AIEnv::GUIManagement::leaveColumnMultiSelectBuild {NodeID} {
	
	set GUITree [TreeStack peek_one]
	set Name [$GUITree get $NodeID -key "Name"]
	$Name build
	EndObjectDefinition
	EndTypeDefinition
}

proc ::AIEnv::GUIManagement::enterCMSColumnBuild {NodeID} {
	set GUITree [TreeStack peek_one]
	set ColLabel [$GUITree get $NodeID -key "Label"]
	WindowPathStack push $ColLabel
}

proc ::AIEnv::GUIManagement::leaveCMSColumnBuild {NodeID} {
	
	WindowPathStack pop
}

proc ::AIEnv::GUIManagement::enterCMSItemBuild {NodeID} {
	set GUITree [TreeStack peek_one]
	set RowLabel [$GUITree get $NodeID -key "Label"]
	set ParentObject [GetObject]
	set ColLabel [WindowPathStack peek]
	$ParentObject set -key "rowCol" $RowLabel $ColLabel
}

proc ::AIEnv::GUIManagement::leaveCMSItemBuild {NodeID} {
	
}

proc ::AIEnv::GUIManagement::enterRFChooserBuild {NodeID} {
   variable GUIDisplayData
   variable CATRootDir
   set GUITree [TreeStack peek_one]

   set RowParent [DEZInsert 1]
   set Row [lindex $RowParent 0]
   set Parent [lindex $RowParent 1]

   set Name [$GUITree get $NodeID -key "Name"]
   set Label [$GUITree get $NodeID -key "Label"]

   set Label [label $Parent.$NodeID-label -text $Label  \
                      -font $GUIDisplayData("LabelFont") \
                      -wraplength $GUIDisplayData("LabelWrapLength") \
                      -justify $GUIDisplayData("LabelJustify") ]

   set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]

   set Text [entry $Parent.$NodeID-text -textvariable $VariableName \
                 -font $GUIDisplayData("EntryFont") \
                 -foreground black \
                 -background white -width $GUIDisplayData("TextEntryWidth")]

   set BBox [ButtonBox $Parent.$NodeID-buttonbox -spacing [expr $GUIDisplayData("ImageSize") / 4]  \
                                                           -padx 1 -pady 1]

   set FileName [GetFileName [file join $CATRootDir "icons" "openProject.gif"]]
   set im1 [image create photo -format GIF -file $FileName]

   $BBox add -image $im1 -highlightthickness 0 -takefocus 0 -relief link \
               -borderwidth 1  -padx 1 -pady 1 -helptext "Browse..." \
               -command "::AIEnv::GUIManagement::RFChooserSelect $VariableName $NodeID $GUITree $Text"

   grid $Label -row $Row -column 0 -sticky e
   grid $Text -row $Row -column 1  -sticky ew -padx $GUIDisplayData("DEZPadx")
   grid $BBox -row $Row -column 2 -sticky e

   $GUITree set $NodeID -key "WindowPath" [list $Label $Text $BBox]
   set ParentDEZ [GetObject]
   $ParentDEZ addloadproc "::AIEnv::GUIManagement::RightJustifyEntry $Text" AFTER_ON_LOAD
}

proc ::AIEnv::GUIManagement::leaveRFChooserBuild {NodeID} {

}

proc ::AIEnv::GUIManagement::RFChooserSelect {PathVar NodeID GUITree Entry} {
   set Newflag    [$GUITree get $NodeID -key "Newflag"]
   set Multiflag  [$GUITree get $NodeID -key "Multiflag"]
   set GetDir     [$GUITree get $NodeID -key "GetDirflag"]
   set OkFunc     [$GUITree get $NodeID -key "OkFunc"]
   set FileTypes  [$GUITree get $NodeID -key "FileTypes"]
   if {$OkFunc == "NULL"} {set OkFunc ""}
   if {$FileTypes == "NULL"} {set FileTypes ""}

   set DirVar [$GUITree get $NodeID -key "DirVar"]
   set def [set $PathVar]

   if {$GetDir} {
      set title "Directory selection"
   } else {
      set title "File selection"
   }

   if {[info exist $DirVar] && ($def == "")} {
      set def [uplevel \#0 subst [list [set $DirVar]]]
   }

   set Path [aie_resfile_select $title $def $title $GetDir \
                     $Newflag $OkFunc "" "" "" "" $Multiflag \
                     "ok to select" 1 0 $FileTypes]

   if { $Path != "" } {
      set $PathVar $Path
      set Proc  [$GUITree get $NodeID -key "Proc"]
      if {$Proc != "NULL"} { eval $Proc $Path }
      if [string match ::?* $DirVar] {
         if {$Multiflag == 0} {
            set $DirVar [file dirname [lindex $Path 0]]
         } else {
            set $DirVar [file dirname [lindex [lindex $Path 0] 0]]
         }
      }
      if [winfo exist $Entry] { ::AIEnv::GUIManagement::RightJustifyEntry $Entry }
   }
}
#---------------------------------------------------------------------------------------------------


proc ::AIEnv::GUIManagement::enterFileChooserBuild {NodeID} {
	variable GUIDisplayData
	variable CATRootDir
	set GUITree [TreeStack peek_one]
	
	set RowParent [DEZInsert 1]
	set Row [lindex $RowParent 0]
	set Parent [lindex $RowParent 1]
		
	set Name [$GUITree get $NodeID -key "Name"]
		
	set Label [$GUITree get $NodeID -key "Label"]
	
	# Create the label
	set Label [label $Parent.$NodeID-label -text $Label  \
			 -font $GUIDisplayData("LabelFont") \
			 -wraplength $GUIDisplayData("LabelWrapLength") \
			 -justify $GUIDisplayData("LabelJustify") ]

	# Create the variable name in the proper namespace
	set VariableName [CreateVariable [$GUITree get $NodeID -key "Variable"]]

	set Text [entry $Parent.$NodeID-text -textvariable $VariableName \
			-font $GUIDisplayData("EntryFont") \
		        -foreground black \
			-background white -width $GUIDisplayData("TextEntryWidth")]
	set BBox [ButtonBox $Parent.$NodeID-buttonbox -spacing [expr $GUIDisplayData("ImageSize") / 4]  \
	                                                   -padx 1 -pady 1]

	set FileName [GetFileName [file join $CATRootDir "icons" "openProject.gif"]]
	set im1 [image create photo -format GIF -file $FileName]

        set ParentDEZ [GetObject]
	$BBox add -image $im1 -highlightthickness 0 -takefocus 0 -relief link \
				-borderwidth 1  -padx 1 -pady 1 -helptext "Browse..." \
	    -command "::AIEnv::GUIManagement::FileChooserCmd $Name $VariableName $NodeID $GUITree $ParentDEZ"
					
	grid $Label -row $Row -column 0 -sticky e 
	grid $Text -row $Row -column 1  -sticky ew -padx $GUIDisplayData("DEZPadx")
	grid $BBox -row $Row -column 2 -sticky e
	
	$GUITree set $NodeID -key "WindowPath" [list $Label $Text $BBox]
    

	$ParentDEZ addloadproc "::AIEnv::GUIManagement::RightJustifyEntry $Text" AFTER_ON_LOAD
}

proc ::AIEnv::GUIManagement::FileChooserCmd {Name VarName NodeID GUITree ParentDEZ} {
    ::AIEnv::GUIManagement::FileChooserBrowse $VarName $NodeID $GUITree
    if {$VarName != ""} { 
	$ParentDEZ proc on${Name}Finish
    }
}

proc ::AIEnv::GUIManagement::RightJustifyEntry {entry} {
    $entry icursor end
    $entry xview end
}

proc ::AIEnv::GUIManagement::leaveFileChooserBuild {NodeID} {
	
}

proc ::AIEnv::GUIManagement::FileChooserBrowse {PathVariableName NodeID GUITree} {
   # variable $PathVariableName 
   #      ---- PathVariableName should be a fully qulified variable name

    set FileTypes [$GUITree get $NodeID -key "FileTypes"]
    set Newflag [$GUITree get $NodeID -key "Newflag"]

    if {$Newflag == "TRUE"} {
	set proc tk_getSaveFile
    } elseif {$Newflag == "DIR"} {
        set proc tk_chooseDirectory
        set FileTypes ""
    } else { 
	set proc tk_getOpenFile
    }
    if { $FileTypes == "" } {
	set Path [$proc -title "Choose File" -initialdir [pwd]]
    } else {
	set Path [$proc -title "Choose File" -filetypes $FileTypes -initialdir [pwd]]
    }
    if { $Path != "" } {
	set $PathVariableName $Path
    }
}
#----------------------------------------------------------------

proc ::AIEnv::GUIManagement::DEZInsert {RowsRequested {PercentRowSize 1}} {
    variable GUIDisplayData
    
    set InnerFrame [WindowPathStack peek_one]
    set CurrentRow [DEZRowCountStack peek_one]
        
    set Row $CurrentRow
    set RowHeight [expr int([expr $PercentRowSize * $GUIDisplayData("DEZRowHeight")])]
    
    for { set Count 0 } { $Count < $RowsRequested } {incr Count} {
        grid rowconfigure $InnerFrame $Row -minsize $RowHeight -weight 0
        incr Row
    }
    grid rowconfigure $InnerFrame $Row -weight 1
    set ReturnData [list $CurrentRow $InnerFrame]
    
    # Update the dez row count data.  Since you can't modify the top element on the
    # stack, pop it off... Modify it... and push it back on.
    
    #DEZRowCountStack pop
    #DEZRowCountStack push $Row
    DEZRowCountStack replace $Row
    
    return $ReturnData
}

#----------------------------------------------------------------

proc ::AIEnv::GUIManagement::enterHotKeyBuild {NodeID} {
    set GUITree [TreeStack peek_one]
    
    if [catch {set key [$GUITree get $NodeID -key "Key"]}] return
    
    set cmd [$GUITree get $NodeID -key "Command"]
    set help [$GUITree get $NodeID -key "Help"]
    set tab [$GUITree get $NodeID -key "Tab"]
    
    if {$tab == "ALL"} {
	tdv_set_key_command $key $cmd $help
    } else {
	tdv_set_key_command $key $cmd $help \
	    ::AIEnv::GUIManagement::CurrentVisibleTab $tab
    }
}

proc ::AIEnv::GUIManagement::leaveHotKeyBuild {NodeID} {
}

proc ::AIEnv::GUIManagement::enterHotKeyZoneBuild {NodeID} {
}

proc ::AIEnv::GUIManagement::leaveHotKeyZoneBuild {NodeID} {
}















