#
# Widget scrollbar toggle module
#

# Adds a scrollbar to w, or removes scrollbar if one already exists. $XY should
# be "x" for a horizontal scrollbar, or "y" for a vertical scrollbar. If w is 
# managed by the packer, side indicates which side of w the scrollbar should
# be packed.
proc th_toggle_scrollbar {w xy side} {
  global TH
  set wrap_flag 0
  if {$xy == "x"} {
    if {[winfo class $w] == "Text"} {set wrap_flag 1}
    set scrollcommand "xscrollcommand"
    set view "xview"
    set orient "horizontal"
  } else {
    if {[winfo class $w] == "Entry"} {
      set TH(Scrollbar,Y,$w) 0
      bell ; return}
    set scrollcommand "yscrollcommand"
    set view "yview"
    set orient "vertical"
  }

  if {[winfo exists [set s [lindex [$w cget -$scrollcommand] 0]]]} {
# Remove scrollbar
    set TH(Scrollbar,[string toupper $xy],$w) 0
    $w configure -$scrollcommand {}
    if {[winfo children [winfo parent $s]] == "$s"} {destroy [winfo parent $s]
    } else {destroy $s}
    if {$wrap_flag && ![catch "set TH(Wrap,Old,$w)" result]} {
      $w configure -wrap $result}
  } elseif {[$w cget -$scrollcommand] != ""} {bell} else {
# Add scrollbar
    set TH(Scrollbar,[string toupper $xy],$w) 1
    if {[winfo manager $w] == "pack"} {
      set s "[set w]_scrollbar_$xy"
    } else {
      set tl "[set w]_scrollbar_$xy"
      toplevel $tl
      set s "$tl.s"
    }
    scrollbar $s -orient $orient -command "$w $view"
    if {[winfo manager $w] != "pack"} {
      pack $s -fill both -expand yes
    } else {
      set w_side [lindex [pack info $w] end]
      eval pack $s [lrange [pack info $w] 6 15] -expand 0 -fill $xy -side $side -before $w
      switch [list $w_side $side] {
        {top bottom} - {left right} - {bottom top} - {right left} {
          pack $s -after $w -side $w_side
    }}}

    $w configure -$scrollcommand "$s set"
    if $wrap_flag {
      set TH(Wrap,Old,$w) [$w cget -wrap]
      $w configure -wrap none
    }
    eval $s set [$w $view]
}}
