if {[winfo exists .menu]} {
    destroy .menu
}

# set currentFile ""

namespace eval global {
    array set value {
	file ""
	justOpened no
	fontSize 9
	verticalAddressAlign \\centeraddress
	addressRules \\windowrules
	backAddressRules \\backaddressrule
	paperFoldMarks \\windowtics
	pdflatex pdflatex
	pdfViewer xpdf
	smartQuotes C
	list-O-matic deep
	numberAlign right
	... \\ldots
	windowGeometry 550x550+20+20
	language ngerman
	refLineOverFold 1
	addressPos \\addressstd
	1000.dezimal, {. ,}
	lastSearchString ""
    }
    variable defaultDir\
	[file dirname [file dirname [file normalize [info script]]]]
    after idle [list cd $defaultDir]
    variable valueFile [file join $defaultDir global.vars]
    set value(defaultFile) [file join $defaultDir default.dinbrief]
    if {[file exists $valueFile]} {
	array set value [cat $valueFile]
    }
    wm geometry . $value(windowGeometry)
    option add *Entry.font		"Helvetica $value(fontSize)"
    option add *Label.font		"Helvetica $value(fontSize)"
    option add *Button.font		"Helvetica $value(fontSize)"
    option add *Menubutton.font		"Helvetica $value(fontSize)"
    option add *Checkbutton.font	"Helvetica $value(fontSize)"
    option add *Labelframe.font		"Helvetica $value(fontSize)"
    option add *Text.font		"Helvetica $value(fontSize)" 
}



proc global::globalSetting {args} {
    variable value
    if {[llength $args] > 1} {
	array set value $args
    } elseif {[llength $args] == 0} {
	array get value
    } else {
	set value([lindex $args 0])
    }
}

proc global::storeGlobalSettings {} {
    variable value
    variable valueFile
    globalSetting windowGeometry [wm geometry .]
    saveString [array get value] $valueFile
}

namespace eval global {
    namespace export *
}

namespace import -force global::*

after idle {::Richtext::setQuotes [globalSetting smartQuotes]}

wm protocol . WM_DELETE_WINDOW {
    .menu.file invoke Ende
}

[menu .menu] add cascade\
    -label Datei\
    -menu [menu .menu.file -tearoff 0]

.menu.file add command\
    -label Neu\
    -command [lambda {} {
	. configure -cursor watch
	update
	set defaultFile [globalSetting defaultFile]
	set failure 0
	if {[file exists $defaultFile]} {
	    if {[catch {
		putContents [cat $defaultFile]
	    } err]} {
		set failure 1
	    }
	} else {
	    set failure 1
	}
	if {$failure} {
	    foreach entry [winfo children .] {
		switch [winfo class $entry] {
		    Entry {
			$entry delete 0 end
		    }
		    Text - Richtext - Scrolledtext - Scrolledrichtext {
			$entry delete 1.0 end
		    }
		}
	    }
	}
	wm title . "DIN-Brief"
	globalSetting file ""
	. configure -cursor ""
    }]

.menu.file add command\
    -label {Öffnen ...}\
    -command [lambda {} {
	set f [tk_getOpenFile -filetypes {
	    {{DIN-Brief} {.dinbrief .DIN-Brief}}
	    {{Alle} *}
	}]
	if {$f ne ""} {
	    loadContents $f
	    # globalSetting file [file normalize $f]
	    globalSetting file [relPathFromTo [pwd] $f]
	    wm title . "DIN-Brief: [file rootname [file tail $f]]"
	    globalSetting justOpened yes
	} else {
	    globalSetting justOpened no
	}
	after idle [list initTabTags .maintext]
    }]

.menu.file add command\
    -label {Erneut öffnen}\
    -command [lambda {} {
	set currentFile [globalSetting file]
	if {$currentFile eq ""} {
	    .menu.file invoke Neu
	} else {
	    loadContents $currentFile
	    wm title . "DIN-Brief: [file rootname [file tail $currentFile]]"
	    after idle [list initTabTags .maintext]
	}
    }]

after idle [list .menu.file invoke {Erneut öffnen}]

.menu.file add command\
    -label {Öffnen als Vorlage ...}\
    -command [lambda {} {
	.menu.file invoke {Öffnen ...}
	if {[globalSetting justOpened]} {
	    globalSetting file ""
	    wm title . Din-Brief
	}
    }]

.menu.file add separator

.menu.file add command\
    -label Speichern\
    -command [lambda {} {
	. configure -cursor watch
	update
 	set currentFile [globalSetting file]
 	if {$currentFile ne ""} {
 	    saveContents $currentFile
 	    wm title . "DIN-Brief: [file rootname [file tail $currentFile]]"
 	} else {
 	    .menu.file invoke {Speichern als ...}
 	}
	. configure -cursor ""
    }]

.menu.file add command\
    -label {Speichern als ...}\
    -command [lambda {} {
	. configure -cursor watch
	update
 	set f [tk_getSaveFile\
		   -defaultextension .dinbrief\
		   -filetypes {
		       {{DIN-Brief}
			   {.dinbrief .DIN-Brief}}
		       {{Alle}
			   *}
		   }]
 	if {$f ne ""} {
 	    saveContents $f
 	    globalSetting file [file normalize $f]
 	    wm title . "DIN-Brief: [file rootname [file tail $f]]"
 	}
	. configure -cursor ""
    }]

.menu.file add command\
    -label {Speichern als Default-Brief}\
    -command [lambda {} {
	. configure -cursor watch
	update
	set defaultFile [globalSetting defaultFile]
	saveContents $defaultFile
	globalSetting file ""
	wm title . DIN-Brief
	. configure -cursor ""
    }]

.menu.file add separator

.menu.file add command\
    -label {Export nach LaTeX}\
    -command [lambda {} {
	. configure -cursor watch
	update
	set currentFile [globalSetting file]
	if {$currentFile eq ""} {
	    set f default
	} else {
	    set workingDir [file dirname $currentFile]
	    set workingFile [string map {" " _} [file tail $currentFile]]
	    set f [file join $workingDir [file rootname $workingFile]]
	}
	saveString [formular2tex] $f.tex
	. configure -cursor ""
    }]

.menu.file add command\
    -label {Export nach PDF}\
    -command [lambda {} {
	set currentFile [globalSetting file]
	.menu.file invoke {Export nach LaTeX}
	if {$currentFile eq ""} {
	    set rootname default
	} else {
# 	    set workingDir [file dirname $currentFile]
# 	    set workingFile [string map {" " _} [file tail $currentFile]]
# 	    set rootname\
# 		[file join $workingDir [file rootname $workingFile]]
	    set rootname [string map {" " _} [file rootname $currentFile]]
	}
	if {![file executable [globalSetting pdflatex]]} {
	    .menu.external invoke {Pfad von pdflatex}
	} else {
	    globalSetting justOpened yes
	}
	if {[globalSetting justOpened]} {
	    set cmd [list\
			 exec [globalSetting pdflatex]\
			 --interaction nonstopmode\
			 $rootname.tex]
	    if {[catch $cmd err]} {
		puts $err
		echo But don't worry,\
		    possibly just changed language,\
		    just another try ...
		eval $cmd
	    }
	}
    }]

.menu.file add separator

.menu.file add command\
    -label Ende\
    -command {
	if {[globalSetting file] ne ""} {
	    .menu.file invoke Speichern
	}
	storeGlobalSettings
	exit
    }

.menu add cascade\
    -label Bearbeiten\
    -menu [menu .menu.edit -tearoff no]

.menu.edit add command\
    -label Ausschneiden\
    -command {
	event generate [focus] <<Cut>>
	event generate [focus] <<Change>>
    }\
    -accelerator Ctrl-x

.menu.edit add command\
    -label Kopieren\
    -command {
	event generate [focus] <<Copy>>
    }\
    -accelerator Ctrl-c

.menu.edit add command\
    -label Einfügen\
    -command {
	event generate [focus] <<Paste>>
	event generate [focus] <<Change>>
    }\
    -accelerator Ctrl-v

.menu.edit add separator

.menu.edit add command\
    -label "Datum ([clock format [clock seconds] -format {%d.%m.%y}])"\
    -command [lambda {} {
	set window [focus]
	switch [winfo class $window] {
	    Text - Richtext - Scrolledtext - Scrolledrichtext {
		foreach {to from} [lreverse [$window tag ranges sel]] {
		    $window delete $from $to
		}
		$window insert insert\
		    [clock format [clock seconds] -format {%d.%m.%y}]
	    }
	    Entry {
		catch {
		    $window delete sel.first sel.last
		}
		$window insert insert\
		    [clock format [clock seconds] -format {%d.%m.%y}]
	    }
	}
    }]

.menu.edit add command\
    -label Seitenwechsel\
    -command {tk::TextInsert [focus] \n\u000c\n}\
    -accelerator Ctrl-l

.menu.edit add separator

.menu.edit add command\
    -label Suche\
    -command {
	focus .maintext.text
	after idle {
	    toggleSearchMode .maintext
	}
    }\
    -accelerator F3

.menu.edit add command\
    -label Rückgängig\
    -command {
	event generate [focus] <<Undo>>
    }\
    -accelerator Ctrl-z

.menu.edit add command\
    -label Wiederholen\
    -command {
	event generate [focus] <<Redo>>
    }\
    -accelerator Ctrl-y

proc switchMenuEdit {state args} {
    foreach i $args {
	.menu.edit entryconfigure $i -state $state
    }
}

bind Entry <FocusIn> {
    switchMenuEdit normal 0 1 2 4 5 7 8 9
    switchMenuEdit disabled 5 7 8 9
}

bind Richtext <FocusIn> {
    switchMenuEdit normal 0 1 2 4 5 7 8 9
    switchMenuEdit disabled 5 7
}

bind Richtext <Button-3> {
    focus %W
    tk_popup .menu.edit %X %Y
}

menu .menu.editEntry -tearoff 0

[lambda {menu1 menu2 args} {
    foreach i $args {
	$menu2 add command\
	    -label [$menu1 entrycget $i -label]\
	    -command [$menu1 entrycget $i -command]
    }
}] .menu.edit .menu.editEntry 0 1 2 4

bind Entry <Button-3> {
    focus %W
    tk_popup .menu.editEntry %X %Y
}

.menu add cascade\
    -label Ansicht\
    -menu [menu .menu.view -tearoff no]

.menu.view add cascade\
    -label Schriftgröße\
    -menu [menu .menu.view.fontsize]

foreach i {9 10 11 12 13 14 15} {
    .menu.view.fontsize add radiobutton\
	-label $i\
	-variable ::global::value(fontSize)\
	-command [list setFontSize $i]
}

.menu.view add separator

.menu.view add command\
    -label Vorschau\
    -command [lambda {} {
	set currentFile [globalSetting file]
	.menu.file invoke {Export nach PDF}
	if {[globalSetting justOpened]} {
	    if {$currentFile eq ""} {
		set rootname default
	    } else {
# 		set dirname [file dirname $currentFile]
# 		set tailname [string map {" " _} [file tail $currentFile]]
# 		set rootname [file rootname $dirname/$tailname]
		set rootname [string map {" " _} [file rootname $currentFile]]
	    }
	    if {![file executable [globalSetting pdfViewer]]} {
		.menu.external invoke {PDF-Betrachter}
	    }
	    if {[globalSetting justOpened]} {
		exec [globalSetting pdfViewer] $rootname.pdf
	    }
	}
    }]

.menu add cascade -label Einstellungen -menu [menu .menu.settings]

.menu.settings add checkbutton\
    -label {Typografischer Gedankenstrich}\
    -variable ::Richtext::typoDashRequired\

.menu.settings add cascade\
    -label {Anführungszeichen}\
    -menu [menu .menu.settings.smartquotes]

.menu.settings.smartquotes add radiobutton\
    -label Schreibmaschine\
    -command [list ::Richtext::setQuotes C]\
    -variable ::global::value(smartQuotes)\
    -value C

.menu.settings.smartquotes add radiobutton\
    -label Deutsch\
    -command [list ::Richtext::setQuotes de]\
    -variable ::global::value(smartQuotes)\
    -value de

.menu.settings.smartquotes add radiobutton\
    -label Englisch\
    -command [list ::Richtext::setQuotes en]\
    -variable ::global::value(smartQuotes)\
    -value en

.menu.settings.smartquotes add radiobutton\
    -label Französisch\
    -command [list ::Richtext::setQuotes fr]\
    -variable ::global::value(smartQuotes)\
    -value fr

.menu.settings.smartquotes add radiobutton\
    -label Schweiz\
    -command [list ::Richtext::setQuotes ch]\
    -variable ::global::value(smartQuotes)\
    -value ch

.menu.settings add cascade\
    -label {Typografische Zeichenersetzung}\
    -menu [menu .menu.settings.typographicalChars -tearoff 0]

.menu.settings.typographicalChars add checkbutton\
    -label {Punkte (...)}\
    -variable ::global::value(...)\
    -onvalue \\ldots\
    -offvalue ...

.menu.settings add separator

.menu.settings add checkbutton\
    -label {Absenderzeile mit Unterstrich}\
    -variable ::global::value(backAddressRules)\
    -onvalue \\backaddressrule\
    -offvalue \\nobackaddressrule

.menu.settings add checkbutton\
    -label {Adressfeld mit Strichen umrandet}\
    -variable ::global::value(addressRules)\
    -onvalue \\windowrules\
    -offvalue \\nowindowrules

.menu.settings add checkbutton\
    -label {Adressfeld vertikal zentriert}\
    -variable ::global::value(verticalAddressAlign)\
    -onvalue \\centeraddress\
    -offvalue \\normaladdress

.menu.settings add checkbutton\
    -label {Nutztext verlängert}\
    -variable ::global::value(addressPos)\
    -onvalue \\addresshigh\
    -offvalue \\addressstd

.menu.settings add checkbutton\
    -label {Falzmarkierungen}\
    -variable ::global::value(paperFoldMarks)\
    -onvalue \\windowtics\
    -offvalue \\nowindowtics

.menu.settings add checkbutton\
    -label {Bezugszeile immer über dem Falz}\
    -variable ::global::value(refLineOverFold)

.menu.settings add separator

.menu.settings add checkbutton\
    -label {Zahlenspalten rechts- bzw. kommabündig}\
    -variable ::global::value(numberAlign)\
    -onvalue right\
    -offvalue left

.menu.settings add checkbutton\
    -label {Deutsches Dezimalkomma}\
    -variable ::global::value(1000.dezimal,)\
    -onvalue {. ,}\
    -offvalue {, .}

.menu.settings add separator

.menu.settings add cascade\
    -label Listenformat\
    -menu [menu .menu.settings.listOmatic -tearoff 0]

.menu.settings.listOmatic add radiobutton\
    -label Aus\
    -variable ::global::value(list-O-matic)\
    -value none

.menu.settings.listOmatic add radiobutton\
    -label Einfach\
    -variable ::global::value(list-O-matic)\
    -value flat

.menu.settings.listOmatic add radiobutton\
    -label Verschachtelt\
    -variable ::global::value(list-O-matic)\
    -value deep

.menu.settings add cascade\
    -label {Silbentrennung Sprache}\
    -menu [menu .menu.settings.lang -tearoff 0]

[lambda {list} {
    foreach {lang label} $list {
	.menu.settings.lang add radiobutton\
	    -label $label\
	    -value $lang\
	    -variable ::global::value(language)
    }
}] {
    ngerman Deutsch
    UKenglish {Englisch (Vereinigtes Königreich)}
    USenglish {Englisch (Vereinigte Staaten)}
    francais Französisch
    italian Italienisch
    spanish Spanisch
    portuges Portugiesisch
    swedish Schwedisch
    polish Polnisch
    esperanto Esperanto
    german {Deutsch (Alte Rechtschreibung)}
}

.menu.settings add command\
    -label {Silbentrennung Ausnahmen ...}\
    -command editHyphenations

.menu add cascade\
    -label {Externe Hilfsprogramme}\
    -menu [menu .menu.external]

.menu.external add command\
    -label {Pfad von pdflatex}\
    -command [lambda {} {
	globalSetting pdflatex\
	    [tk_getOpenFile -title "Genauer Pfad für PDFlatex"]
	if {[file executable [globalSetting pdflatex]]} {
	    globalSetting justOpened yes
	} else {
	    globalSetting justOpened no
	}
    }]

.menu.external add command\
    -label {PDF-Betrachter}\
    -command [lambda {} {
	globalSetting pdfViewer\
	    [tk_getOpenFile -title {PDF-Betrachter auswählen}]
	if {[file executable [globalSetting pdfViewer]]} {
	    globalSetting justOpened yes
	} else {
	    globalSetting justOpened no
	}
    }]

.menu add cascade -label ? -menu [menu .menu.help -tearoff 0]

.menu.help add command\
    -label "Über dinbrief"\
    -command {
	tk_dialog .info Info\
	    "dinbrief V.1.0\n(c) 2005 Wolf-Dieter Busch"\
	    info 0 Ok
    }

. configure -menu .menu
