#!./tclsh
# $Id: compose 1266 2009-07-14 18:39:12Z hubert@u.washington.edu $
# ========================================================================
# Copyright 2008 University of Washington
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# ========================================================================

#  compose
#
#  Purpose:  CGI script template for Web Alpine 2.0 pages
#
#  Input:    PATH_INFO: [/<col_number>]/<folder_name>[/<uid_of_viewed_msg>
#            along with possible search parameters:
set compose_args {
  {pop		{}	browse/0/INBOX}
  {repqstr	""	"_NONE_SET_"}
  {contacts	""	""}
}

# inherit global config
source ./alpine.tcl
source ./foldercache.tcl
source ./common.tcl

set script_base "$_wp(serverpath)/$_wp(appdir)/$_wp(ui2dir)/"

# TEST
proc cgi_suffix {args} {
  return ""
}

if {[info exists debugging]} {
  # WHILE TESTING/DEBUGGING
  set dmsgs ""
  proc dm {s} {
    global dmsgs

    lappend dmsgs $s
  }
}

# On input failure, redirect to home page "browse"
proc browse_redirect {} {
  cgi_http_head {
    cgi_redirect browse
  }
}

proc url {d} {
  global _wp

  return [file join / $_wp(urlprefix) $_wp(appdir) $_wp(ui2dir) $d]
}

proc leave_test {d} {
  return "return cancelComposition('[url $d]');"
}

proc fieldname {name} {
  regsub -all -- {-} [string tolower $name] {_} fieldname
  return $fieldname
}

proc default_fcc {itemval} {
  global fccdefault f_name f_colid

  if {[catch {WPCmd PEFolder collections} collections]} {
    set collections ""
  }

  # fcc's itemval should be a list of collection-id and folder-name
  if {[llength $itemval] == 2} {
    set fcccol [lindex $itemval 0]
    set fccname [lindex $itemval 1]
  } elseif {[info exists f_name] && [string length $f_name]} {
    set fcccol $f_colid
    set fccname $f_name
  } elseif {[info exists fccdefault] || [catch {WPCmd PECompose fccdefault} fccdefault] == 0} {
    set fcccol [lindex $fccdefault 0]
    set fccname [lindex $fccdefault 1]
    unset fccdefault
  } else {
    set fccname sent-mail
    if {[llength $collections] > 1} {
      set fcccol 1
    } else {
      set fcccol 0
    }
  }

  return [list $fccname $fcccol $collections]
}

set firstheader 1
proc rowfield {item itemval} {
  global _wp addrheaders firstheader compose_mode

  if {0 == [string compare [string tolower $item] attach]} {
    return
  }

  set isaddr [lsearch -exact $addrheaders [string tolower $item]]

  cgi_table_row {
    cgi_table_data class="spc" colspan="3" {}
  }
  cgi_table_row {
    cgi_table_data class="wap lbl" {
      cgi_anchor_name "to"
      if {$isaddr >= 0} {
	cgi_button "${item}..." title="Select email addresses from Contacts or Directory" "onClick=return pickContact('$item','field${item}');"
      } elseif {0 == [string compare [string tolower $item] fcc]} {
	cgi_button "Fcc..." title="Carbon Copy to Folder" "onClick=this.blur(); return pickFolder('folderList','Set Fcc','[WPCmd PEFolder defaultcollection]',pickFccDone);"
      } else {
	cgi_put "<label for=\"[string tolower $item]\">$item:</label>"

      }
    }
    cgi_table_data class="wap mid" {
      if {$isaddr >= 0} {
	cgi_textarea [string tolower $item]=$itemval class="mid" id="field$item"
	cgi_division id="container$item" class="yui-skin-sam" {}
      } else {
	switch -- [string tolower $item] {
	  fcc {
	    set deffcc [default_fcc $itemval]

	    set fccname [lindex $deffcc 0]
	    set fcccol [lindex $deffcc 1]

	    cgi_text "[fieldname $item]=$fccname" id="field$item" class="mid" "onBlur=fccExists(false);"
	    cgi_text "colid=$fcccol" type=hidden "notab" id="fieldFccCollection"
	  }
	  default {
	    cgi_text "[fieldname $item]=$itemval" id="field$item" class="mid"
	  }
	}
      }
    }
    cgi_table_data class="wap rgt" {
      if {$firstheader} {
	set firstheader 0
	cgi_put "[cgi_span id="moreComposeHeaderText" [cgi_url "More Headers" "#" "onClick=showMoreComposeHeaders(); return false;" title="Show Bcc:, Fcc:, ..."]]"
	cgi_put "[cgi_span id="lessComposeHeaderText" [cgi_url "Fewer Headers" "#" "onClick=showLessComposeHeaders(); return false;"]]"
      }
      if {0 && 0 == [string compare [string tolower $item] fcc]} {
	cgi_puts [cgi_url "[cgi_nbspace]Select Folder" "#" "onClick=this.blur(); pickFolder('folderList','Set Fcc','[WPCmd PEFolder defaultcollection]',pickFccDone); return false;"]
      } elseif {0 == [string compare [string tolower $item] subject]} {
	if {[string compare -nocase rich $compose_mode]} {
	  set flipto Rich
	} else {
	  set flipto Plain
	}
	cgi_put [cgi_url "$flipto Text" "" id=flipRich "onClick=return flipRichText();"]
      }
    }
  }
}

set c -1
set f ""
set u 0
set p ""
set body ""
set defaultheaders {to cc subject}
set addrheaders {to cc bcc}
set entryfocus fieldTo
set title Compose

WPEval $compose_args {

  set compose_mode plain

  # figure out compose mode and collect necessary stuff
  if {[regexp {/(reply|replyall|forward|resume|mailto)$} $env(SCRIPT_NAME) dummy mode]} {
    if {0 == [string compare resume $mode]} {
      if {[info exists env(PATH_INFO)]} {
	if {[regexp {^/([0-9]+)$} $env(PATH_INFO) dummy u]} {
	  set title "Resume Draft"
	  set c [WPCmd PEFolder defaultcollection]
	  set f Drafts
	  if {[catch {WPCmd PEPostpone extract $u {html}} postponed]} {
	    WPCmd PEInfo statmsg "Cannot get Draft: $postponed"
	  } else {
	    foreach h [lindex $postponed 0] {
	      append hdrvals([fieldname [lindex $h 0]]) [lindex $h 1]
	    }

	    # return to message's edit mode
	    set compose_mode plain

	    foreach opt [lindex $postponed 3] {
	      switch [lindex $opt 0] {
		charset {
		  set charset [lindex $opt 1]
		}
		subtype {
		  if {0 == [string compare -nocase [lindex $opt 1] html]} {
		    set compose_mode rich
		  }
		}
	      }
	    }

	    set body [join [lindex $postponed 1] "\r\n"]
	    set attachments [lindex $postponed 2]

	    unset postponed

	    catch {WPCmd set help_context compose}
	    if {[catch {WPCmd set pre_draft_folder} curfold]} {
	      set pop "browse/0/INBOX"
	    } else {
	      set pop "browse/[lindex $curfold 0]/[wpSpecialFolder [lindex $curfold 0] [lindex $curfold 1]]"
	    }
	  }
	} else {
	  WPCmd PEInfo statmsg "Invalid Draft UID: $env(PATH_INFO)"
	  browse_redirect
	  cgi_exit
	}
      } else {
	WPCmd PEInfo statmsg "Missing Draft UID"
	browse_redirect
	cgi_exit
      }
    } elseif {0 == [string compare mailto $mode]} {
      set title "Compose"

      if {[catch {cgi_import to}] == 0} {
	set hdrvals(to) $to
      }

      if {[catch {cgi_import cc}] == 0} {
	set hdrvals(to) $cc
      }

      if {[catch {cgi_import subject}] == 0} {
	set hdrvals(subject) $subject
      }

      catch {cgi_import body}
    } else {
      if {!([info exists env(PATH_INFO)] && [regexp {^/([0-9]+)/(.+)/([0-9]+)[/]?([\.0-9]*)*} $env(PATH_INFO) dummy c f u p])} {
	WPCmd PEInfo statmsg "Invalid Invocation: $env(SCRIPT_NAME) (info = $env(PATH_INFO)"
	browse_redirect
	cgi_exit
      }

      # process action specified by compose_args
      switch $mode {
	reply -
	replyall {
	  set title "Reply to Message [WPCmd PEMessage $u number]"
	  if {[string length $p]} {
	    append title ", part $p"
	  }

	  foreach h [WPCmd PEMessage $u replyheaders $p] {
	    set hdrvals([fieldname [lindex $h 0]]) [lindex $h 1]
	  }

	  if {[string compare $mode replyall]} {
	    catch {unset hdrvals(cc)}
	  }

	  if {[WPCmd PEInfo feature quell-format-flowed] == 0} {
	    set flowed 1
	  }

	  if {0 == [string compare $repqstr "_NONE_SET_"]} {
	    set repqstr [WPCmd PEMessage $u replyquote]
	  }

	  set replytext [WPCmd PEMessage $u replytext $repqstr $p]

	  if {[string compare $compose_mode plain]} {
	    set replytext [cgi_quote_html $replytext]
	    set body [join [lindex $replytext 0] "<br />"]
	  } else {
	    set body [join [lindex $replytext 0] "\n"]
	  }

	  if {[WPCmd PEInfo feature include-attachments-in-reply]} {
	    set attachments [lindex $replytext 1]
	  }

	  catch {WPCmd set help_context reply}
	  set cuid $u
	  set entryfocus composeText
	}
	forward {
	  set title "Forward [WPCmd PEMessage $u number]"
	  if {[string length $p]} {
	    append title ", part $p"
	  }

	  foreach h [WPCmd PEMessage $u forwardheaders $p] {
	    set hdrvals([fieldname [lindex $h 0]]) [lindex $h 1]
	  }

	  foreach line [WPCmd PEInfo signature] {
	    append body "$line\r\n"
	  }

	  if {[WPCmd PEInfo feature quell-format-flowed] == 0} {
	    set flowed 1
	  }

	  set forwardtext [WPCmd PEMessage $u forwardtext $p]
	  
	  if {[string compare $compose_mode plain]} {
	    set forwardtext [cgi_quote_html $forwardtext]
	    append body [join [lindex $forwardtext 0] "<br />"]
	  } else {
	    append body [join [lindex $forwardtext 0] "\r\n"]
	  }

	  set attachments [lindex $forwardtext 1]
	  catch {WPCmd set help_context forward}
	  set cuid $u
	}
      }
    }
  } else {
    foreach line [WPCmd PEInfo signature] {
      append body "$line\r\n"
    }

    if {[string length $contacts] && [regexp {^[0-9\.,]+$} $contacts]} {
      set hdrvals(to) ""
      foreach c [split $contacts ","] {
	if {[regexp {^([0-9]+)\.([0-9]+)$} $c dummy abook aindex]} {
	  # compose to address book entry
	  if {0 == [catch {WPCmd PEAddress entry $abook "" $aindex} entryval]} {
	    if {[string length $hdrvals(to)]} {
	      append hdrvals(to) ", "
	    }

	    append hdrvals(to) [lindex $entryval 0]
	    set newfcc [lindex $entryval 1]
	    if {[string length $newfcc]} {
	      global fccdefault
	      if {[string compare $newfcc "\"\""] == 0} {
		set newfcc ""
	      }
	      if {[catch {WPCmd PEFolder collections} collections]} {
		set collections ""
	      }
	      set fccdefault [list [expr {[llength $collections] > 1 ? 1 : 0}] $newfcc]
	    }
	  }
	}
      }
    }

    WPCmd PECompose noattach
  }

  if {[catch {WPCmd PECompose userhdrs} headers]} {
    error [list _action "Header Retrieval Failure" $headers]
  }

  if {![info exists charset]} {
    set charset UTF-8
  }

  cgi_http_head {
    WPStdHttpHdrs "text/html; charset=\"$charset\""
  }

  cgi_html {
    cgi_head {
      cgi_http_equiv Content-Type "text/html; charset=$charset"
      cgi_title [wpPageTitle "$title"]
      cgi_base "href=$script_base"
      # yui css
      cgi_stylesheet "$_wp(yui)/build/autocomplete/assets/skins/sam/autocomplete.css"
      cgi_stylesheet "$_wp(yui)/build/tabview/assets/tabview-core.css"
      cgi_stylesheet "$_wp(yui)/build/button/assets/skins/sam/button.css"
      cgi_stylesheet "$_wp(yui)/build/container/assets/skins/sam/container.css"
      cgi_stylesheet "$_wp(yui)/build/editor/assets/skins/sam/simpleeditor.css"
      # local css
      cgi_stylesheet css/cbn/screen.css
      cgi_stylesheet css/menu.css
      cgi_stylesheet css/cbn/folderdialog.css
      cgi_stylesheet css/cbn/contactdialog.css
      cgi_puts "<style type='text/css'>"
      cgi_puts ".yui-skin-sam .yui-ac-content{ width:70%; }"
      cgi_puts ".yui-navset .yui-nav li { margin-right:0.16em; padding-top:1px; zoom:1; }"
      cgi_puts ".yui-navset .yui-nav .selected { margin-bottom:-1px; }"
      cgi_puts ".yui-navset .yui-nav a { background:#dadbdb url($_wp(yui)/build/assets/skins/sam/sprite.png) repeat-x; border:solid #a3a3a3; border-width:0 1px; color:#000; text-decoration:none; }"
      cgi_puts ".yui-navset .yui-nav li a em { border-top:solid 1px #a3a3a3;  border-bottom:0;  cursor:hand;  padding:0.2em 0.5em; top:-1px; position:relative; }"
      cgi_puts ".yui-navset .yui-nav .selected a, .yui-navset .yui-nav a:focus, .yui-navset .yui-nav a:hover { background:#214197 url($_wp(yui)/build/assets/skins/sam/sprite.png) repeat-x left -1400px; color:#fff; }"
      cgi_puts ".yui-navset .yui-nav .selected a em { padding:0.3em 0.5em; }"
      cgi_puts ".yui-navset .yui-nav .selected a, .yui-navset .yui-nav a:hover, .yui-navset .yui-nav a:focus { border-color:#243356; }"
      cgi_puts ".yui-navset .yui-nav a:hover em, .yui-navset .yui-nav a:focus em, .yui-navset .yui-nav .selected a em { border-color:#233356 #406ed9; }"
      cgi_puts ".yui-navset .yui-nav { border-bottom:1px solid #243356; position:relative; zoom:1; }"
      cgi_puts ".yui-navset .yui-content { border-top:5px solid #214095; }"
      cgi_puts "</style>"
      # Yahoo UI Libraries
      cgi_script type=text/javascript language="JavaScript" src="$_wp(yui)/build/utilities/utilities.js" {}
      cgi_script type=text/javascript language="JavaScript" src="$_wp(yui)/build/container/container-min.js" {}
      cgi_script type=text/javascript language="JavaScript" src="$_wp(yui)/build/datasource/datasource-min.js" {}
      cgi_script type=text/javascript language="JavaScript" src="$_wp(yui)/build/get/get-min.js" {}
      cgi_script type=text/javascript language="JavaScript" src="$_wp(yui)/build/autocomplete/autocomplete-min.js" {}
      cgi_script type=text/javascript language="JavaScript" src="$_wp(yui)/build/button/button-min.js" {}
      cgi_script type=text/javascript language="JavaScript" src="$_wp(yui)/build/tabview/tabview-min.js" {}
      cgi_script type=text/javascript language="JavaScript" src="$_wp(yui)/build/editor/simpleeditor-min.js" {}
      # local libraries
      cgi_script language="JavaScript" src="lib/common.js" {}
      cgi_script language="JavaScript" src="lib/compose.js" {}
      # page/content specific 
      cgi_javascript {
	cgi_puts "YAHOO.alpine.cgi_root = '$_wp(serverpath)';"
	cgi_puts "YAHOO.alpine.cgi_base = '$script_base';"
	if {0 == [catch {WPCmd PEFolder current} curfold]} {
	  cgi_puts "YAHOO.alpine.current.c = [lindex $curfold 0];"
	  cgi_puts "YAHOO.alpine.current.f = \"[lindex $curfold 1]\";"
	}
	cgi_puts "var gRichState = ('$compose_mode' == 'rich');"
	cgi_puts "var gRichtextEditor, gRichtextRendered = false;"
	cgi_puts "var gFieldHeight = 0;"
	cgi_puts "var gDefCol = [WPCmd PEFolder defaultcollection];"
	cgi_puts "var gDraftFolder = '[var_value postponed-folder]';"

	# set up contacts dialog
	set markup [cgi_buffer {
	  cgi_division id="contactsDialogFramework" {
	    set dirs [catch {WPCmd PELdap directories} directories]
	    if {0 == $dirs} {
	      set class "class=yui-navset"
	    } else {
	      set class ""
	    }

	    cgi_division id="contactDialog" $class {
	      if {0 == $dirs} {
		cgi_bullet_list class="yui-nav" {
		  cgi_li class="selected" [cgi_url [cgi_emphasis Contacts] "#contactList" "onClick=this.blur();"]
		  cgi_li [cgi_url [cgi_emphasis Directory] "#directoryQuery" "onClick=this.blur();"]
		}
		cgi_division class=yui-content {
		  cgi_division id="contactList" class="contactContent" {
		    cgi_put "Loading..."
		  }
		  cgi_division id="directoryQuery" class=contactContent {
		    cgi_division class="clistContext" "style=\"text-align: center;\"" {
		      cgi_form $_wp(appdir)/$_wp(ui2dir)/conduit/query.tcl method=get target=formResponse {
			if {[llength $directories] > 1} {
			  cgi_select dir class=wap {
			    for {set i 0} {$i < [llength $directories]} {incr i} {
			      set dname [lindex [lindex $directories $i] 0]
			      if {0 == [string length $dname]} {
				set dname "Directory [expr {$i + 1}]"
			      }
			      cgi_option $dname value=$i
			    }
			  }
			} else {
			  if {[string length [lindex [lindex $directories 0] 0]]} {
			    cgi_put [cgi_span [lindex [lindex $directories 0] 0]]
			  }

			  cgi_text "dir=0" type=hidden "notab"
			}
			
			cgi_text "query=" size="20" length="40" id="dirQuery"
			cgi_submit_button go=Search
		      }
		    }
		    cgi_division id="dirResult" class="clistContacts" {
		      cgi_put [cgi_span "Search results appear here..."]
		    }
		  }
		}
	      } else {
		cgi_division id="contactList" class="contactContent" {
		  cgi_put "Loading..."
		}
	      }
	    }
	  }
	}]

	regsub -all {'} $markup {\'} markup
	regsub -all {\n} $markup {} markup
	cgi_puts "YAHOO.alpine.pickcontact.markup = '$markup';"
	cgi_puts "function bodyOnLoad() {"
	cgi_puts " initMenus();"
	cgi_puts " if(gRichState){ initSimpleEditor([expr {0 == [string compare $entryfocus composeText]}]); if(gRichtextEditor){ gRichtextEditor.render(); gRichtextRendered = true; }}"
	cgi_puts " autoSizeAddressField('fieldTo');"
	cgi_puts " autoSizeAddressField('fieldCc');"
	cgi_puts " autoSizeAddressField('fieldBcc');"
	cgi_puts " setCheckMailFunction('gCheck', newMailCheck);"
	cgi_puts " setNewMailCheckInterval([WPCmd PEInfo inputtimeout]);"
	if {[info exists _wp(autodraft)]} {
	  cgi_puts " setAutoDraftInterval($_wp(autodraft));"
	}
	wpStatusAndNewmailJavascript
	cgi_puts " setCursorPosition('$entryfocus',0);"
	cgi_puts " fccExists(true);"
        cgi_puts "}"

	cgi_puts "browserDetect();"
      }
    }

    cgi_body class="wap" "onLoad=bodyOnLoad()" {
      cgi_division  id="skip" {
	cgi_put [cgi_url "Skip to Compose Body" "#to"]
	cgi_put [cgi_url "Skip to Message List" "browse#messages"]
	cgi_put [cgi_url "Skip to Folders" "#folders"]
      }

      cgi_puts {<iframe name="formResponse" id="formResponse" src="img/cbn/spritelib.gif"></iframe>}

      wpCommonPageLayout compose "$c" "$f" "$u" \
	  $title \
	  [list [cgi_cgi "$_wp(appdir)/$_wp(ui2dir)/browse/${c}/${f}"] Composition 0] \
	  leave_test\
	  {
	    cgi_division class=hdrBtns {
	      cgi_javascript {
		cgi_put "if(window.print) document.write('[cgi_buffer {cgi_put [cgi_url "[cgi_span "class=sp hdrBtnImg hbi1" ""][cgi_span "class=hdrBtnText" Print]" "print" "onClick=return printContent()"]}]');"
	      }

	      cgi_put [cgi_url "[cgi_span "class=sp hdrBtnImg hbi3" ""][cgi_span "class=hdrBtnText" Help]" "javascript:openHelpWindow('compose.html');" class=wap]
	      cgi_put [cgi_url "[cgi_span "class=sp hdrBtnImg hbi4" ""][cgi_span "class=hdrBtnText" "Sign out"]" "" "onClick=[leave_test "../../session/logout.tcl?cid=[WPCmd PEInfo key]&sessid=${sessid}"]"]
	    }
	  } {
	    cgi_anchor_name "toolbar"
	    cgi_table class="toolbarTbl" cellpadding="0" cellspacing="0" {
	      cgi_puts "<tbody>"
	      cgi_table_row  {
		cgi_table_data class="wap" {
		  cgi_put [cgi_url [cgi_span "class=sp spmbi spmb9" "Send"] "post" "onClick=return sendComposition();"]
		}
		cgi_table_data class="wap" {
		  cgi_put [cgi_url [cgi_span "class=sp spmbi spmb11" "Attach File"] "" "onClick=this.blur(); return addAttachField();"]
		}
		cgi_table_data class="wap" {
		  cgi_put [cgi_url [cgi_span "class=sp spmbi spmb10" "Save Draft"] post/draft "onClick=return saveDraft();"]
		}
		cgi_table_data  class="wap dv1" {
		  cgi_put [cgi_img  "img/cbn/div.gif"]
		}
		cgi_table_data class="wap yui-skin-sam yuimenu" id="priorityButtonContainer" {
		  cgi_bullet_list class="wap menu" {
		    cgi_put "<li class=\"menuHdr\">[cgi_url "Priority [cgi_img "img/cbn/menu.gif" class="wap menuDn menuImg"]" "#" "onClick=return false;"]"
		    cgi_division {
		      cgi_bullet_list class=priority {
			cgi_li [cgi_url "[cgi_span "class=sp spfcl blank" ""]Highest" "" id="pri5" "onClick=return setPriority(this,'highest')"]
			cgi_li [cgi_url "[cgi_span "class=sp spfcl blank" ""]High" "" id="pri4" "onClick=return setPriority(this,'high')"]
			cgi_li [cgi_url "[cgi_span "class=sp spfcl blank" ""]Normal" "" id="pri3" "onClick=return setPriority(this,'normal')"]
			cgi_li [cgi_url "[cgi_span "class=sp spfcl blank" ""]Low" "" id="pri2" "onClick=return setPriority(this,'low')"]
			cgi_li [cgi_url "[cgi_span "class=sp spfcl blank" ""]Lowest" "" id="pri1" "onClick=return setPriority(this,'lowest')"]
			cgi_li "<hr />[cgi_url "[cgi_span "class=sp spfcl spfcl3" ""]No[cgi_nbspace]Priority" "" id="pri0" "onClick=return setPriority(this,'')"]"
		      }
		    }
		    cgi_put "</li>"
		  }
		}
		cgi_table_data  class="wap dv1" {
		  cgi_put [cgi_img "img/cbn/div.gif"]
		}
		cgi_table_data class="wap" {
		  cgi_put [cgi_url [cgi_span "class=sp spmbi spmb12" "Cancel"] "$pop" "onClick=return cancelComposition('[url $pop]');" title="Cancel Compose and lose unsaved changes"]
		}
		cgi_table_data class="wap" width="100%" {
		  cgi_put [cgi_nbspace]
		}
		cgi_table_data class="wap tbPad" align="right" {
		  cgi_put [cgi_nbspace]
		}
	      }
	      cgi_puts "</tbody>"
	    }
	  } {
	    cgi_form $_wp(appdir)/$_wp(ui2dir)/conduit/post.tcl "enctype=multipart/form-data" id=composeForm target=formResponse {
	      cgi_table width="100%" height="100%" cellpadding="0" cellspacing="0" id=compositionBody {
		cgi_puts "<tbody>"
		cgi_table_row {
		  cgi_table_data {
		    cgi_table class="compose" cellpadding="0" cellspacing="0" {
		      cgi_puts "<tbody>"
		      cgi_table_row {
			cgi_table_data class="spc" colspan="3" {
			  # various bits of what we need to pass on
			  cgi_text "cid=[WPCmd PEInfo key]" type=hidden "notab"
			  cgi_text "sessid=$sessid" type=hidden "notab"
			  cgi_text "postpost=$pop" type=hidden "notab"
			  cgi_text "subtype=plain" type=hidden id=contentSubtype notab
			  cgi_text "priority=0" type=hidden id=priority "notab"

			  # TEST stuff we have to feed post.tcl to get it working
			  cgi_text "action=OK" type=hidden "notab"
			  cgi_text "send=1" type=hidden "notab"
			  cgi_text "sendop=send" type=hidden id=sendOp notab
			  cgi_text "autodraftuid=0" type=hidden id=autoDraftUid notab

			  if {[string length $repqstr]} {
			    cgi_text "repqstr=$repqstr" type=hidden "notab"
			  }

			  if {[info exists flowed]} {
			    cgi_text "form_flowed=yes" type=hidden "notab"
			  }

			  foreach field [WPCmd PECompose syshdrs] {
			    set hdr [fieldname [lindex $field 0]]
			    if {[info exists hdrvals($hdr)]} {
			      cgi_text "${hdr}=$hdrvals($hdr)" type=hidden "notab"
			    }
			  }
			}
		      }

		      set extrahdrs {}

		      foreach field $headers {
			set item [lindex $field 0]

			if {[string length $item] == 0} {
			  continue
			}

			set itemvaldef [lindex $field 1]
			set litem [string tolower $item]
			set fn [fieldname $item]

			if {[info exists hdrvals($fn)]} {
			  set itemval $hdrvals($fn)
			} elseif {[info exists $litem] && [string length [subst $$litem]]} {
			  set itemval [subst $$litem]
			} elseif {[string length $itemvaldef]} {
			  set itemval $itemvaldef
			} else {
			  set itemval ""
			}

			if {[catch {WPCmd PECompose composehdrs} h] == 0 && [llength $h] > 0} {
			  set display_headers [string tolower $h]
			} else {
			  set display_headers $defaultheaders
			}

			if {![info exists extrahdrs]} {
			  if {[info exists postoption(fcc-set-by-addrbook)]} {
			    if {[lsearch -exact $display_headers fcc] < 0} {
			      lappend display_headers fcc
			    }
			  }
			}

			if {[lsearch -exact $display_headers [string tolower $item]] >= 0} {
			  rowfield $item $itemval
			} elseif {[info exists extrahdrs]} {
			  lappend extrahdrs [list $item $itemval]
			} else {
			  switch -- [string tolower $item] {
			    fcc {
			      set deffcc [default_fcc $itemval]

			      set fccname [lindex $deffcc 0]
			      set fcccol [lindex $deffcc 1]

			      cgi_text [fieldname $item]=$fccname type=hidden "notab"
			      cgi_text "colid=$fcccol" type=hidden "notab"
			    }
			    default {
			      cgi_text "[fieldname $item]=$itemval" type=hidden "notab"
			    }
			  }
			}
		      }

		      cgi_puts "</tbody>"
		    }

		    if {[info exists extrahdrs]} {
		      cgi_division id="moreComposeHeaders" {
			cgi_table class="wap compose" cellpadding="0" cellspacing="0" {
			  cgi_puts "<tbody>"

			  foreach pb $extrahdrs {
			    rowfield [lindex $pb 0] [lindex $pb 1]
			  }

			  cgi_puts "</tbody>"
			}
		      }
		    }

		    cgi_division id="composeAttachments" {
		      cgi_table class="wap compose" cellpadding="0" cellspacing="0" {
			cgi_puts "<tbody>"
			cgi_table_row {
			  cgi_table_data  class="wap spc" colspan="2" {}
			}
			cgi_table_row {
			  cgi_table_data class="wap lbl" {
			    cgi_puts "<label>Attachments: </label>"
			  }
			  cgi_table_data class="wap attach"  {
			    cgi_text "attachments=" type=hidden id=attachments notab
			    cgi_division id=attachList {
			    }
			    cgi_division id=fileUpload {
			    }
			  }
			}
			cgi_table_row {
			  cgi_table_data class="wap spc" colspan="2" {

			    if {[info exists postoption(fcc-without-attachments)]} {
			      if {$postoption(fcc-without-attachments)} {
				set checked ""
			      } else {
				set checked checked
			      }
			    } elseif {[WPCmd PEInfo feature "fcc-without-attachments"]} {
			      set checked ""
			    } else {
			      set checked checked
			    }

			    cgi_checkbox fccattach=1 $checked id="fcc_attachment"
			    cgi_puts "<label for='fcc_attachment'>Include attachments in copy of message saved to Fcc (i.e. sent-mail)</label>"
			  }
			}
		      }
		    }
		    cgi_javascript {
		      if {[info exists attachments]} {
			set comma ""
			cgi_puts "drawAttachmentList({attachments:\["
			foreach a $attachments {
			  # {4137457288 bunny.gif 2514 Image/GIF}
			  cgi_puts "${comma}{id:'[lindex $a 0]',fn:'[lindex $a 1]',size:'[lindex $a 2]',type:'[lindex $a 3]'}"
			  set comma ","
			}
			cgi_puts "\]});"
		      }
		    }
		  }
		}
		cgi_table_row {
		  cgi_table_data height="100%" {
		    cgi_table class="composeBody" cellpadding="0" cellspacing="0" {
		      cgi_puts "<tbody>"
		      cgi_table_row {
			cgi_table_data class="yui-skin-sam textBody" {
			  cgi_textarea body=$body id=composeText title="Message Body" rows="25"
			}
		      }
		      cgi_puts "</tbody>"
		    }
		  }
		}
		cgi_puts "</tbody>"
	      }
	    }
	  } {
	    cgi_table class="wap toolbarTbl" cellpadding="0" cellspacing="0" {
	      cgi_puts "<tbody>"
	      cgi_table_row  {
		cgi_table_data id=lastAutoDraft  class="wap pageText" {
		}
		cgi_table_data class=wap width="100%" {
		  cgi_put [cgi_nbspace]
		}
		cgi_table_data  class="wap tbPad" align="right" {
		  cgi_put [cgi_nbspace]
		}
	      }
	      cgi_puts "</tbody>"
	    }
	  }

      # autosize and autocompletion
      cgi_javascript {
	cgi_puts "var gACDataServer = '$_wp(serverpath)/$_wp(appdir)/$_wp(ui2dir)/conduit/complete.tcl';"
	cgi_puts {
	  gACDataSource = new YAHOO.widget.DS_XHR(gACDataServer,['Result','Email','Nickname','Fcc']);
	  gACDataSource.responseType = YAHOO.widget.DS_XHR.TYPE_XML;
	}
	if {[info exists cuid] || [regexp {view/.*/([0-9]+)$} $pop dummy cuid]} {
	  cgi_puts "    gACDataSource.scriptQueryAppend = 'uid=$cuid';"
	}
	cgi_puts {
	  var gAutoCompleteTo = new YAHOO.widget.AutoComplete('fieldTo','containerTo',gACDataSource);
	  autoCompleteDefaults(gAutoCompleteTo);
	  var gAutoCompleteCc = new YAHOO.widget.AutoComplete('fieldCc','containerCc',gACDataSource);
	  autoCompleteDefaults(gAutoCompleteCc);
	  var gAutoCompleteBcc = new YAHOO.widget.AutoComplete('fieldBcc','containerBcc',gACDataSource);
	  autoCompleteDefaults(gAutoCompleteBcc);
	}
      }

      if {[info exists debugging]} {
	# any debugging info to insert?
      
	foreach dmsg $dmsgs {
	  cgi_html_comment "DEBUG: $dmsg"
	  cgi_puts ""
	}
      }
    }
  }
}
