Background: #fff
Foreground: #000
PrimaryPale: #8cf
PrimaryLight: #18f
PrimaryMid: #04b
PrimaryDark: #014
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
<!--{{{-->
<div class='toolbar' macro='toolbar [[ToolbarCommands::EditToolbar]]'></div>
<div class='title' macro='view title'></div>
<div class='editor' macro='edit title'></div>
<div macro='annotations'></div>
<div class='editor' macro='edit text'></div>
<div class='editor' macro='edit tags'></div><div class='editorFooter'><span macro='message views.editor.tagPrompt'></span><span macro='tagChooser excludeLists'></span></div>
<!--}}}-->
To get started with this blank [[TiddlyWiki]], you'll need to modify the following tiddlers:
* [[SiteTitle]] & [[SiteSubtitle]]: The title and subtitle of the site, as shown above (after saving, they will also appear in the browser title bar)
* [[MainMenu]]: The menu (usually on the left)
* [[DefaultTiddlers]]: Contains the names of the tiddlers that you want to appear when the TiddlyWiki is opened
You'll also need to enter your username for signing your edits: <<option txtUserName>>
<<importTiddlers>>
<!--{{{-->
<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml' />
<!--}}}-->
These [[InterfaceOptions]] for customising [[TiddlyWiki]] are saved in your browser

Your username for signing your edits. Write it as a [[WikiWord]] (eg [[JoeBloggs]])

<<option txtUserName>>
<<option chkSaveBackups>> [[SaveBackups]]
<<option chkAutoSave>> [[AutoSave]]
<<option chkRegExpSearch>> [[RegExpSearch]]
<<option chkCaseSensitiveSearch>> [[CaseSensitiveSearch]]
<<option chkAnimate>> [[EnableAnimations]]

----
Also see [[AdvancedOptions]]
<!--{{{-->
<div class='header' role='banner' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
<div class='headerShadow'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
<div class='headerForeground'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
</div>
<div id='mainMenu' role='navigation' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
<div id='sidebarOptions' role='navigation' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' role='complementary' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea' role='main'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
/*{{{*/
body {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}

a {color:[[ColorPalette::PrimaryMid]];}
a:hover {background-color:[[ColorPalette::PrimaryMid]]; color:[[ColorPalette::Background]];}
a img {border:0;}

h1,h2,h3,h4,h5,h6 {color:[[ColorPalette::SecondaryDark]]; background:transparent;}
h1 {border-bottom:2px solid [[ColorPalette::TertiaryLight]];}
h2,h3 {border-bottom:1px solid [[ColorPalette::TertiaryLight]];}

.button {color:[[ColorPalette::PrimaryDark]]; border:1px solid [[ColorPalette::Background]];}
.button:hover {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::SecondaryLight]]; border-color:[[ColorPalette::SecondaryMid]];}
.button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::SecondaryDark]];}

.header {background:[[ColorPalette::PrimaryMid]];}
.headerShadow {color:[[ColorPalette::Foreground]];}
.headerShadow a {font-weight:normal; color:[[ColorPalette::Foreground]];}
.headerForeground {color:[[ColorPalette::Background]];}
.headerForeground a {font-weight:normal; color:[[ColorPalette::PrimaryPale]];}

.tabSelected {color:[[ColorPalette::PrimaryDark]];
	background:[[ColorPalette::TertiaryPale]];
	border-left:1px solid [[ColorPalette::TertiaryLight]];
	border-top:1px solid [[ColorPalette::TertiaryLight]];
	border-right:1px solid [[ColorPalette::TertiaryLight]];
}
.tabUnselected {color:[[ColorPalette::Background]]; background:[[ColorPalette::TertiaryMid]];}
.tabContents {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::TertiaryPale]]; border:1px solid [[ColorPalette::TertiaryLight]];}
.tabContents .button {border:0;}

#sidebar {}
#sidebarOptions input {border:1px solid [[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel {background:[[ColorPalette::PrimaryPale]];}
#sidebarOptions .sliderPanel a {border:none;color:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:hover {color:[[ColorPalette::Background]]; background:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:active {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::Background]];}

.wizard {background:[[ColorPalette::PrimaryPale]]; border:1px solid [[ColorPalette::PrimaryMid]];}
.wizard h1 {color:[[ColorPalette::PrimaryDark]]; border:none;}
.wizard h2 {color:[[ColorPalette::Foreground]]; border:none;}
.wizardStep {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];
	border:1px solid [[ColorPalette::PrimaryMid]];}
.wizardStep.wizardStepDone {background:[[ColorPalette::TertiaryLight]];}
.wizardFooter {background:[[ColorPalette::PrimaryPale]];}
.wizardFooter .status {background:[[ColorPalette::PrimaryDark]]; color:[[ColorPalette::Background]];}
.wizard .button {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryLight]]; border: 1px solid;
	border-color:[[ColorPalette::SecondaryPale]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryPale]];}
.wizard .button:hover {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Background]];}
.wizard .button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::Foreground]]; border: 1px solid;
	border-color:[[ColorPalette::PrimaryDark]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryDark]];}

.wizard .notChanged {background:transparent;}
.wizard .changedLocally {background:#80ff80;}
.wizard .changedServer {background:#8080ff;}
.wizard .changedBoth {background:#ff8080;}
.wizard .notFound {background:#ffff80;}
.wizard .putToServer {background:#ff80ff;}
.wizard .gotFromServer {background:#80ffff;}

#messageArea {border:1px solid [[ColorPalette::SecondaryMid]]; background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]];}
#messageArea .button {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::SecondaryPale]]; border:none;}

.popupTiddler {background:[[ColorPalette::TertiaryPale]]; border:2px solid [[ColorPalette::TertiaryMid]];}

.popup {background:[[ColorPalette::TertiaryPale]]; color:[[ColorPalette::TertiaryDark]]; border-left:1px solid [[ColorPalette::TertiaryMid]]; border-top:1px solid [[ColorPalette::TertiaryMid]]; border-right:2px solid [[ColorPalette::TertiaryDark]]; border-bottom:2px solid [[ColorPalette::TertiaryDark]];}
.popup hr {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::PrimaryDark]]; border-bottom:1px;}
.popup li.disabled {color:[[ColorPalette::TertiaryMid]];}
.popup li a, .popup li a:visited {color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:active {background:[[ColorPalette::SecondaryPale]]; color:[[ColorPalette::Foreground]]; border: none;}
.popupHighlight {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
.listBreak div {border-bottom:1px solid [[ColorPalette::TertiaryDark]];}

.tiddler .defaultCommand {font-weight:bold;}

.shadow .title {color:[[ColorPalette::TertiaryDark]];}

.title {color:[[ColorPalette::SecondaryDark]];}
.subtitle {color:[[ColorPalette::TertiaryDark]];}

.toolbar {color:[[ColorPalette::PrimaryMid]];}
.toolbar a {color:[[ColorPalette::TertiaryLight]];}
.selected .toolbar a {color:[[ColorPalette::TertiaryMid]];}
.selected .toolbar a:hover {color:[[ColorPalette::Foreground]];}

.tagging, .tagged {border:1px solid [[ColorPalette::TertiaryPale]]; background-color:[[ColorPalette::TertiaryPale]];}
.selected .tagging, .selected .tagged {background-color:[[ColorPalette::TertiaryLight]]; border:1px solid [[ColorPalette::TertiaryMid]];}
.tagging .listTitle, .tagged .listTitle {color:[[ColorPalette::PrimaryDark]];}
.tagging .button, .tagged .button {border:none;}

.footer {color:[[ColorPalette::TertiaryLight]];}
.selected .footer {color:[[ColorPalette::TertiaryMid]];}

.error, .errorButton {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Error]];}
.warning {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryPale]];}
.lowlight {background:[[ColorPalette::TertiaryLight]];}

.zoomer {background:none; color:[[ColorPalette::TertiaryMid]]; border:3px solid [[ColorPalette::TertiaryMid]];}

.imageLink, #displayArea .imageLink {background:transparent;}

.annotation {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border:2px solid [[ColorPalette::SecondaryMid]];}

.viewer .listTitle {list-style-type:none; margin-left:-2em;}
.viewer .button {border:1px solid [[ColorPalette::SecondaryMid]];}
.viewer blockquote {border-left:3px solid [[ColorPalette::TertiaryDark]];}

.viewer table, table.twtable {border:2px solid [[ColorPalette::TertiaryDark]];}
.viewer th, .viewer thead td, .twtable th, .twtable thead td {background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::Background]];}
.viewer td, .viewer tr, .twtable td, .twtable tr {border:1px solid [[ColorPalette::TertiaryDark]];}

.viewer pre {border:1px solid [[ColorPalette::SecondaryLight]]; background:[[ColorPalette::SecondaryPale]];}
.viewer code {color:[[ColorPalette::SecondaryDark]];}
.viewer hr {border:0; border-top:dashed 1px [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::TertiaryDark]];}

.highlight, .marked {background:[[ColorPalette::SecondaryLight]];}

.editor input {border:1px solid [[ColorPalette::PrimaryMid]];}
.editor textarea {border:1px solid [[ColorPalette::PrimaryMid]]; width:100%;}
.editorFooter {color:[[ColorPalette::TertiaryMid]];}
.readOnly {background:[[ColorPalette::TertiaryPale]];}

#backstageArea {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::TertiaryMid]];}
#backstageArea a {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstageArea a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; }
#backstageArea a.backstageSelTab {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
#backstageButton a {background:none; color:[[ColorPalette::Background]]; border:none;}
#backstageButton a:hover {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstagePanel {background:[[ColorPalette::Background]]; border-color: [[ColorPalette::Background]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]];}
.backstagePanelFooter .button {border:none; color:[[ColorPalette::Background]];}
.backstagePanelFooter .button:hover {color:[[ColorPalette::Foreground]];}
#backstageCloak {background:[[ColorPalette::Foreground]]; opacity:0.6; filter:alpha(opacity=60);}
/*}}}*/
/*{{{*/
* html .tiddler {height:1%;}

body {font-size:.75em; font-family:arial,helvetica; margin:0; padding:0;}

h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;}
h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;}
h4,h5,h6 {margin-top:1em;}
h1 {font-size:1.35em;}
h2 {font-size:1.25em;}
h3 {font-size:1.1em;}
h4 {font-size:1em;}
h5 {font-size:.9em;}

hr {height:1px;}

a {text-decoration:none;}

dt {font-weight:bold;}

ol {list-style-type:decimal;}
ol ol {list-style-type:lower-alpha;}
ol ol ol {list-style-type:lower-roman;}
ol ol ol ol {list-style-type:decimal;}
ol ol ol ol ol {list-style-type:lower-alpha;}
ol ol ol ol ol ol {list-style-type:lower-roman;}
ol ol ol ol ol ol ol {list-style-type:decimal;}

.txtOptionInput {width:11em;}

#contentWrapper .chkOptionInput {border:0;}

.externalLink {text-decoration:underline;}

.indent {margin-left:3em;}
.outdent {margin-left:3em; text-indent:-3em;}
code.escaped {white-space:nowrap;}

.tiddlyLinkExisting {font-weight:bold;}
.tiddlyLinkNonExisting {font-style:italic;}

/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */
a.tiddlyLinkNonExisting.shadow {font-weight:bold;}

#mainMenu .tiddlyLinkExisting,
	#mainMenu .tiddlyLinkNonExisting,
	#sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;}
#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;}

.header {position:relative;}
.header a:hover {background:transparent;}
.headerShadow {position:relative; padding:4.5em 0 1em 1em; left:-1px; top:-1px;}
.headerForeground {position:absolute; padding:4.5em 0 1em 1em; left:0; top:0;}

.siteTitle {font-size:3em;}
.siteSubtitle {font-size:1.2em;}

#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;}

#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;}
#sidebarOptions {padding-top:0.3em;}
#sidebarOptions a {margin:0 0.2em; padding:0.2em 0.3em; display:block;}
#sidebarOptions input {margin:0.4em 0.5em;}
#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;}
#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;}
#sidebarOptions .sliderPanel input {margin:0 0 0.3em 0;}
#sidebarTabs .tabContents {width:15em; overflow:hidden;}

.wizard {padding:0.1em 1em 0 2em;}
.wizard h1 {font-size:2em; font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em;}
.wizard h2 {font-size:1.2em; font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em;}
.wizardStep {padding:1em 1em 1em 1em;}
.wizard .button {margin:0.5em 0 0; font-size:1.2em;}
.wizardFooter {padding:0.8em 0.4em 0.8em 0;}
.wizardFooter .status {padding:0 0.4em; margin-left:1em;}
.wizard .button {padding:0.1em 0.2em;}

#messageArea {position:fixed; top:2em; right:0; margin:0.5em; padding:0.5em; z-index:2000; _position:absolute;}
.messageToolbar {display:block; text-align:right; padding:0.2em;}
#messageArea a {text-decoration:underline;}

.tiddlerPopupButton {padding:0.2em;}
.popupTiddler {position: absolute; z-index:300; padding:1em; margin:0;}

.popup {position:absolute; z-index:300; font-size:.9em; padding:0; list-style:none; margin:0;}
.popup .popupMessage {padding:0.4em;}
.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0;}
.popup li.disabled {padding:0.4em;}
.popup li a {display:block; padding:0.4em; font-weight:normal; cursor:pointer;}
.listBreak {font-size:1px; line-height:1px;}
.listBreak div {margin:2px 0;}

.tabset {padding:1em 0 0 0.5em;}
.tab {margin:0 0 0 0.25em; padding:2px;}
.tabContents {padding:0.5em;}
.tabContents ul, .tabContents ol {margin:0; padding:0;}
.txtMainTab .tabContents li {list-style:none;}
.tabContents li.listLink { margin-left:.75em;}

#contentWrapper {display:block;}
#splashScreen {display:none;}

#displayArea {margin:1em 17em 0 14em;}

.toolbar {text-align:right; font-size:.9em;}

.tiddler {padding:1em 1em 0;}

.missing .viewer,.missing .title {font-style:italic;}

.title {font-size:1.6em; font-weight:bold;}

.missing .subtitle {display:none;}
.subtitle {font-size:1.1em;}

.tiddler .button {padding:0.2em 0.4em;}

.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;}
.isTag .tagging {display:block;}
.tagged {margin:0.5em; float:right;}
.tagging, .tagged {font-size:0.9em; padding:0.25em;}
.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;}
.tagClear {clear:both;}

.footer {font-size:.9em;}
.footer li {display:inline;}

.annotation {padding:0.5em; margin:0.5em;}

* html .viewer pre {width:99%; padding:0 0 1em 0;}
.viewer {line-height:1.4em; padding-top:0.5em;}
.viewer .button {margin:0 0.25em; padding:0 0.25em;}
.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;}
.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;}

.viewer table, table.twtable {border-collapse:collapse; margin:0.8em 1.0em;}
.viewer th, .viewer td, .viewer tr,.viewer caption,.twtable th, .twtable td, .twtable tr,.twtable caption {padding:3px;}
table.listView {font-size:0.85em; margin:0.8em 1.0em;}
table.listView th, table.listView td, table.listView tr {padding:0 3px 0 3px;}

.viewer pre {padding:0.5em; margin-left:0.5em; font-size:1.2em; line-height:1.4em; overflow:auto;}
.viewer code {font-size:1.2em; line-height:1.4em;}

.editor {font-size:1.1em;}
.editor input, .editor textarea {display:block; width:100%; font:inherit;}
.editorFooter {padding:0.25em 0; font-size:.9em;}
.editorFooter .button {padding-top:0; padding-bottom:0;}

.fieldsetFix {border:0; padding:0; margin:1px 0px;}

.zoomer {font-size:1.1em; position:absolute; overflow:hidden;}
.zoomer div {padding:1em;}

* html #backstage {width:99%;}
* html #backstageArea {width:99%;}
#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em;}
#backstageToolbar {position:relative;}
#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em;}
#backstageButton {display:none; position:absolute; z-index:175; top:0; right:0;}
#backstageButton a {padding:0.1em 0.4em; margin:0.1em;}
#backstage {position:relative; width:100%; z-index:50;}
#backstagePanel {display:none; z-index:100; position:absolute; width:90%; margin-left:3em; padding:1em;}
.backstagePanelFooter {padding-top:0.2em; float:right;}
.backstagePanelFooter a {padding:0.2em 0.4em;}
#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;}

.whenBackstage {display:none;}
.backstageVisible .whenBackstage {display:block;}
/*}}}*/
/***
StyleSheet for use when a translation requires any css style changes.
This StyleSheet can be used directly by languages such as Chinese, Japanese and Korean which need larger font sizes.
***/
/*{{{*/
body {font-size:0.8em;}
#sidebarOptions {font-size:1.05em;}
#sidebarOptions a {font-style:normal;}
#sidebarOptions .sliderPanel {font-size:0.95em;}
.subtitle {font-size:0.8em;}
.viewer table.listView {font-size:0.95em;}
/*}}}*/
/*{{{*/
@media print {
#mainMenu, #sidebar, #messageArea, .toolbar, #backstageButton, #backstageArea {display: none !important;}
#displayArea {margin: 1em 1em 0em;}
noscript {display:none;} /* Fixes a feature in Firefox 1.5.0.2 where print preview displays the noscript content */
}
/*}}}*/
<!--{{{-->
<div class='toolbar' role='navigation' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></div>
<div class='title' macro='view title'></div>
<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
/***
|''Name''|RefreshTiddlerCommand|
|''Version''|0.3.0|
***/
//{{{
(function($) {

var cmd = config.commands.refreshTiddler = {
	text: "refresh",
	locale: {
		refreshing: "Refreshing tiddler..."
	},
	tooltip: "refresh this tiddler to be the one on the server",
	handler: function(ev, src, title) {
		var tiddler = store.getTiddler(title);
		if(!tiddler) {
			tiddler = new Tiddler(title);
			merge(tiddler.fields, config.defaultCustomFields);
		}
		$(story.getTiddler(title)).find(".viewer").
			empty().text(cmd.locale.refreshing);
		var dirtyStatus = store.isDirty();
		story.loadMissingTiddler(title, {
			"server.workspace": tiddler.fields["server.recipe"]  ? "recipes/" + tiddler.fields["server.recipe"] :
				tiddler.fields["server.workspace"] || "bags/"+tiddler.fields["server.bag"],
			"server.host": tiddler.fields["server.host"],
			"server.type": tiddler.fields["server.type"]
		}, function() {
			store.setDirty(dirtyStatus);
		});
	}
};

})(jQuery);
//}}}
CACHE MANIFEST

CACHE:
/_offline
/bags/common/tiddlers/profile.css
/_offline.css
/bags/common/tiddlers/jquery.js
/twikifier.js
/_offline.js

# VERSION 0.2.5

NETWORK:
*
<!--{{{-->
<div macro="tiddlerGender">
<div class='toolbar' 
	macro='toolbar [[ToolbarCommands::ViewToolbar]] icons:yes height:16 width:16 more:popup'>
</div>
<div class='heading'>
	<span class='spaceSiteIcon' 
		macro='tiddlerOrigin label:no spaceLink:yes height:48 width:48 preserveAspectRatio:yes'>
	</span>
	<span class="titleBar">
		<div class='title' macro='view title text'></div>
		<div class="subtitle" macro='viewRevisions page:5'>
			last modified on
			<span macro="view modified date"></span>
			by <span macro="view modifier spaceLink"></span>
		</div>
	</span>
	<div class='tagClear'></div>
</div>
<div class='content'>
        <div class="viewer">
		<div class='personImage' macro="aet if:image">
			<div macro="view image image height:200"></div>
			<div class='caption' macro="view image-caption wikified"></div>
		</div>
<h3>Facts</h3>
		<div class='factbox'>
			<div>
				<span macro='aet if:!dob&!placeofbirth&!occupation&!dod&!placeofdeath'>
					No facts.
				</span>
				<span macro='aet if:dob'>
					Born <span class='emphasise' macro='view dob date'></span>
					<span macro="aet if:dob-accuracy">
						(<span macro="view dob-accuracy text"></span>)
					</span>

				</span>
				<span macro='aet if:dobaptism'>
					Baptised <span class='emphasise' macro='view dobaptism date'></span>
					<span macro="aet if:placebaptism"> at 
						<span class='emphasise' macro='view placeofbaptism text'></span>
					</span>
				</span>
				<span macro='aet if:placeofbirth'>in</span>
				<span class='emphasise' macro='view placeofbirth link'></span>
			</div>
			<div>
				<span macro='aet if:occupation'>occupation </span>
				<span class='emphasise' macro='view occupation'></span>
			</div>
			<div>
				<span macro='aet if:dod'>died </span>
				<span macro="aet if:dod-accuracy">
					(<span macro="view dod-accuracy text"></span>)
				</span>
				<span macro='view dod date' class='emphasise'></span>
				<span macro='aet if:placeofdeath'> in </span>
				<span macro='view placeofdeath link' class='emphasise'></span>
				<span macro='aet if:dod&dob'> 
					aged <span macro='age' class='emphasise'></span>
				</span>
				<span macro="aet if:doburial|placeofburial">
					buried
					<span macro='aet if:doburial'>
						on <span macro='view doburial date' class='emphasise'></span>
					</span>
					<span macro="aet if:placeofburial">
						in <span macro='view placeofburial text' class='emphasise'></span>
					</span>
				</span>
			</div>
		</div>
		<div class='subtitle'>
			<span macro='aet if:mother|father'>Child of</span>
			<span macro='view father link'></span>
			<span macro="viewFieldTiddler father dob date YYYY"></span>
			<span macro='aet if:father&mother'>and</span>
			<span macro='view mother link'></span>
			<span macro="viewFieldTiddler mother dob date YYYY"></span><br/>
			<span macro='aet if:spouse'>Spouse(s): </span>
			<span macro='view spouse bracketedlist'></span>
<span macro="aet if:dom">married <span macro="view dom date"></span></span>
		</div>
		<h3>Children of <span macro='view title'></span></h3>
		<div macro='listchildren sort:dob'></div>
		<div class='tagging' macro='tagging'></div>
		<div class='tagged' macro='tags'></div>
		<h3>About</h3>
		<div  macro='view text wikified'></div>
		
	    </div>
</div>
<div class='tagInfo'>
	<div class='tidTags' macro='tags'></div>
	<div class='tagging' macro='tagging'></div>
<div macro="view title permalink"></div>
</div>

</div>

<!--}}}-->
A [[SiteIcon|SiteIcon tiddler]]@glossary helps provide some identity to your space.  Ideally it'd be a square and a minimum of 48*48 pixels size.  You can upload your site icon using the uploader below.

<<binaryUploadPublic title:SiteIcon>>
//{{{
if(config.extensions.tiddlyspace.currentSpace.name === "familytree") {
	var tiddler = new Tiddler("Dad");
	merge(tiddler.fields, {image: "homer.png", spouse: "Mum", sex: "M", placeofbirth: "Springfield", dob: "195500000000" });
	tiddler.tags = ["rootTree", "teacher"];
	store.addTiddler(tiddler);
	tiddler = new Tiddler("Mum");
	tiddler.fields = { dob: "195303140000", sex: "F", spouse: "Dad" };
	store.addTiddler(tiddler);
	tiddler = new Tiddler("Son");
	tiddler.fields = { dob: "198502020000", sex: "M", father:"Dad", mother: "Mum" };
	store.addTiddler(tiddler);
	tiddler = new Tiddler("Daughter");
	tiddler.fields = { dob: "198709220000", sex: "F", father: "Dad", mother: "Mum" };
	store.addTiddler(tiddler);
}
//}}}
/***
TiddlySpace extensions for [[chrjs]]
***/
//{{{
(function($) {

tiddlyweb.routes.spaces = "{host}/spaces";
tiddlyweb.routes.space = "{host}/spaces/{name}";
tiddlyweb.routes.members = "{host}/spaces/{name}/members";
tiddlyweb.routes.member = "{host}/spaces/{name}/members/{username}";

tiddlyweb.Space = function(name, host) {
	tiddlyweb.Resource.apply(this, ["space", host]);
	this.name = name;
};
tiddlyweb.Space.prototype = new tiddlyweb.Resource();
$.extend(tiddlyweb.Space.prototype, {
	create: function(callback, errback) { // API wrapper
		this.put.apply(this, arguments);
	},
	members: function() {
		return new MemberCollection(this);
	},
	includes: function() {
		return new IncludesCollection(this);
	}
});

var Member = function(username, space) {
	tiddlyweb.Resource.apply(this, ["member", space.host]);
	this.name = space.name;
	this.username = username;
};
Member.prototype = new tiddlyweb.Resource();

var MemberCollection = function(space) {
	tiddlyweb.Collection.apply(this, ["members", space.host, {
		name: space.name
	}]);
};
MemberCollection.prototype = new tiddlyweb.Collection();
$.extend(MemberCollection.prototype, {
	add: function(username, callback, errback) {
		var member = new Member(username, this);
		member.put(callback, errback);
	},
	remove: function(username, callback, errback) {
		var member = new Member(username, this);
		member["delete"](callback, errback);
	}
});

var IncludesCollection = function(space) {
	tiddlyweb.Collection.apply(this, ["space", space.host, {
		name: space.name
	}]);
};
IncludesCollection.prototype = new tiddlyweb.Collection();
$.extend(IncludesCollection.prototype, {
	get: function(callback, errback) {
		var self = this;
		var recipe = new tiddlyweb.Recipe(this.name + "_public", this.host);
		recipe.get(function(recipe, status, xhr) {
			var inclusions = $.map(recipe.recipe, function(item, i) {
				var arr = item[0].split("_public");
				return (arr[0] != self.name && arr[1] === "") ? arr[0] : null;
			});
			callback(inclusions, status, xhr);
		}, function(xhr, error, exc) {
			errback(xhr, error, exc, self);
		});
	},
	add: function(name, callback, errback) {
		var self = this;
		var names = typeof(name) === "string" ? [ name ] : name;
		$.ajax({
			type: "post",
			url: this.route(),
			contentType: "json",
			data: $.toJSON({ "subscriptions": names }),
			success: function(response, status, xhr) {
				callback(self, status, xhr);
			},
			errback: function(xhr, error, exc) {
				errback(xhr, error, exc, self);
			}
		});
	},
	remove: function(name, callback, errback) {
		var self = this;
		var names = typeof(name) === "string" ? [ name ] : name;
		$.ajax({
			type: "post",
			contentType: "json",
			url: this.route(),
			data: $.toJSON({ "unsubscriptions": names }),
			success: function(response, status, xhr) {
				callback(self, status, xhr);
			},
			errback: function(xhr, error, exc) {
				errback(xhr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HzG5XJ9mDci9vT0XOCL1G/ARDF5t8Tv9yv3vIXmpKYWAnP7LeFJRkdHVV1gsQQuDvspcLyaq5uas9RmT+Lt6+sL8qQTsF702lAYoKGyUxIMBunmzZuZXAbNSPYY3xXUFhscHPyD6zJYzlNYaG5ujqqqqqQWVrEFdACP5ZaB1IRkHp8uuJcna3yYgVtE8wYaRy5gMpny9qK1CtIF0GFqaiqjYX66Z9G0572TRe1PI4dGi8HhcDxQBxX+1+v10vT0dFZWWbT+tMIVdshvArqUZT7eAMCfg/P5IiiAhkIhyahBhw0p8F8wfja6K0V7E6Bsm231zkUUoagxAV68c0FRgcwRH8FZheCdyxkefyFfE31boJXg+fIyb4jOz1E128gheLt1nsF+w2BDhe5fjPeITtbg8+ibyG0IpyiSFRURcvUppL887nutL4QeykN5APkflX09TZ+Q7fwAAAAASUVORK5CYII=
<!DOCTYPE html>
<html manifest="/manifest.mf">
	<head>
		<title>takenote</title>
		<link rel="stylesheet" href="/notabene.css" />
		<link rel="apple-touch-icon" href="/touchicon_takenote.png"/>
		<link rel="apple-touch-icon-precomposed" href="/touchicon_takenote.png"/>
		<meta name="viewport" content="width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=0,initial-scale=1.0">
	</head>
	<body>
		<ul id="backstage">
			<!-- no not add a newline between li elements or you will get a margin with inline blocks -->
			<li><a href="/dashboard">dashboard</a></li><li><a href="/takenote">takenote</a></li>
			<li><a class='connectionStatus'></a></li>
		</ul>
		<div class="takenotecontainer">
			<div class='messageArea'></div>
			<div id="note">
				<div class="toolbar">
					<a id="cancelnote" title="cancel this note">cancel</a>
					<a id="deletenote" title="delete this note">delete</a>
					<a id="newnote" title="complete this note">complete</a>
				</div>
				<div class="note_title_container">
					<textarea class="note_title" placeholder="Note Title"></textarea>
				</div>
				<div id="notebody">
					<span class="notedate"></span> 
					<textarea class="note_text" placeholder="Write here..."></textarea>
				</div>
				<div id="tips">
				<div>Tips for cleverer notes:
				''<span class="boldTip">bold</span>'' //<span class="italicTip">italic</span>// _<span class="underlineTip">underline</span>_ #tag</div>
				<div>[[<a href="http://tiddlyspace.com">Link Name</a>|http://tiddlyspace.com]]
				[[<a href="/Note title">Note title</a>]] <span class="imageTip">[img[/SiteIcon<img src="/SiteIcon" />]]</span></div>
				</div>
				<div id="notemeta"></div>
				<div style="display:none">
				  <a class="syncButton"></a>
				</div>
			</div>
		</div>
		<noscript>
			Takenote requires javascript to work correctly. Sorry!
		</noscript>
		<script src="/bags/common/tiddlers/backstage.js" type="text/javascript" charset="utf-8"></script>
		<script src="/bags/common/tiddlers/bookmark_bubble.js" type="text/javascript" charset="utf-8"></script>
		<script src="/bags/common/tiddlers/jquery.js" type="text/javascript" charset="utf-8"></script>
		<script src="/bags/tiddlyspace/tiddlers/chrjs" type="text/javascript" charset="utf-8"></script>
		<script src="/bags/common/tiddlers/chrjs-store.js" type="text/javascript" charset="utf-8"></script>
		<script src="/bags/common/tiddlers/jquery-json.js" type="text/javascript" charset="utf-8"></script>
		<script src="/notabene.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			var takenote, space = window.location.hostname.split(".")[0];
			takenote = notes($(".takenotecontainer")[0], {
				bag: space + "_public",
				host: "/"
			});
		</script>
	</body>
</html>
/***
|''Name''|TiddlyFileImporter|
|''Version''|0.3.8|
|''Author''|Ben Gillies|
|''Type''|plugin|
|''Description''|Upload a TiddlyWiki file to TiddlyWeb, and import the tiddlers.|
!Usage
Upload a TiddlyWiki file to TiddlyWeb, and import the tiddlers.
!Requires
tiddlyweb
tiddlywebplugins.reflector
!Code
***/
//{{{
(function($){
if(!version.extensions.TiddlyFileImporter)
{ //# ensure that the plugin is only installed once
	version.extensions.TiddlyFileImporter = { installed: true };
}

config.macros.fileImport = {
	reflectorURI: '/reflector?csrf_token=%0',
	incorrectTypeError: 'Incorrect File Type. You must upload a TiddlyWiki',
	uploadLabel: 'Upload',
	uploadLabelPrompt: 'Import tiddlers from this TiddlyWiki',
	step1FileText: 'File:',
	step1PostText: 'In the next screen you will select the tiddlers to import.',
	step1Title: 'Step 1: Pick a TiddlyWiki to import',
	step1TypeChooser: 'Import From:',
	step3Html: ['<input type="hidden" name="markList" />',
		'<input type="hidden" checked="true" name="chkSync" />',
		'<input type="hidden" name="chkSave" />',
		'<input type="hidden" name="txtSaveTiddler" />'].join(),

	handler: function(place, macroName, params, wikifier, paramString) {
		var wizard = new Wizard();
		wizard.createWizard(place, 'Import a TiddlyWiki');
		this.restart(wizard);
	},

	restart: function(wizard) {
		var me = config.macros.fileImport;
		wizard.addStep(me.step1Title, ['<input type="hidden" ',
			'name="markList" />'].join(""));
		var markList = wizard.getElement('markList');
		var uploadWrapper = document.createElement('div');
		markList.parentNode.insertBefore(uploadWrapper, markList);
		uploadWrapper.setAttribute('refresh', 'macro');
		uploadWrapper.getAttribute('macroName', 'fileImport');
		var iframeName = 'reflectorImporter' + Math.random().toString();
		me.createForm(uploadWrapper, wizard, iframeName);
		$(uploadWrapper).append('<p>' + me.step1PostText + '</p>');
		wizard.setValue('serverType', 'tiddlyweb');
		wizard.setValue('adaptor', new config.adaptors.file());
		wizard.setValue('host', config.defaultCustomFields['server.host']);
		wizard.setValue('context', {});
		var iframe = $(['<iframe name="' + iframeName + '" ',
			'style="display: none" />'].join("")).appendTo(uploadWrapper);
		var onSubmit = function(ev) {
			var uploadType = $('select[name=uploadtype]', wizard.formElem).val();
			if (uploadType == "file") {
				// set an onload ready to hijack the form
				me.setOnLoad(uploadWrapper, wizard, iframe[0]);
				wizard.importType = 'file';
				wizard.formElem.submit();
			} else {
				var csrf_token = config.extensions.tiddlyspace.getCSRFToken();
				$.ajax({
					url: "%0/reflector?csrf_token=%1".format(
						config.defaultCustomFields["server.host"], csrf_token),
					type: "POST",
					dataType: "text",
					data: {
						uri: $("input", ".importFrom", wizard.formElem).val()
					},
					success: function(data, txtStatus, xhr) {
						wizard.POSTResponse = data;
						me.importTiddlers(uploadWrapper, wizard);
					},
					error: function(xhr, txtStatus, error) {
						displayMessage(["There was an error fetching the ",
							'url: ', txtStatus].join(""));
						me.restart(wizard);
					}
				});
				return false;
			}
		};
		wizard.setButtons([{
			caption: me.uploadLabel,
			tooltip: me.uploadLabelPrompt,
			onClick: onSubmit
		}]);
		$(wizard.formElem).submit(function(ev) {
			onSubmit(ev);
			ev.preventDefault();
		});
	},

	createForm: function(place, wizard, iframeName) {
		var form = wizard.formElem;
		var me = config.macros.fileImport;
		form.action = me.reflectorURI.format(
			config.extensions.tiddlyspace.getCSRFToken());
		form.enctype = 'multipart/form-data';
		form.encoding = 'multipart/form-data';
		form.method = 'POST';
		form.target = iframeName;
		onSelectChange = function(e) {
			var changeTo = $(this).val();
			if (changeTo == "file") {
				$(".importFrom").html('%0 <input type="file" name="file" />'.
					format(me.step1FileText));
			} else {
				$(".importFrom").html('URL: <input type="text" name="uri" />'
					+ ' Do you want <a target="_blank" href="http://faq.tiddlyspace.com/How%20do%20I%20include%2Fexclude%20spaces%3F">inclusion</a> instead?');
			}
		};
		$(place).append('<span>%0</span>'.format(me.step1TypeChooser)).
			append($(['<select name="uploadtype"><option value="file" selected="selected">file',
				'<option value="uri">url</select>'].join("")).change(onSelectChange)).
			append('<div class="importFrom">%0<input type="file" name="file" /></div>'.
					format(me.step1FileText));
	},

	setOnLoad: function(place, wizard, iframe) {
		var me = config.macros.fileImport;
		var loadHandler = function() {
			me.importTiddlers.apply(this, [place, wizard, iframe]);
		};
		iframe.onload = loadHandler;
		completeReadyStateChanges = 0;
		iframe.onreadystatechange = function() {
			if (++(completeReadyStateChanges) == 5) {
				loadHandler();
			}
		};
	},

	importTiddlers: function(place, wizard, iframe) {
		var tmpStore = new TiddlyWiki();
		var POSTedWiki = "";
		if (wizard.importType == "file") {
			try {
				POSTedWiki= iframe.contentWindow
					.document.documentElement.innerHTML;
			} catch(e) {
				displayMessage(config.macros.fileImport.incorrectTypeError);
				config.macros.fileImport.restart(wizard);
				return;
			}
			// now we are done, so remove the iframe
			$(iframe).remove();
		} else {
			POSTedWiki = wizard.POSTResponse;
		}

		tmpStore.importTiddlyWiki(POSTedWiki);
		var newTiddlers = tmpStore.getTiddlers();
		var workspace = config.defaultCustomFields['server.workspace'];
		var context = {
			status: true,
			statusText: 'OK',
			httpStatus: 200,
			adaptor: wizard.getValue('adaptor'),
			tiddlers: newTiddlers
		};
		context.adaptor.store = tmpStore;
		wizard.setValue('context', context);
		wizard.setValue('workspace', workspace);
		wizard.setValue('inFileImport', true);
		config.macros.importTiddlers.onGetTiddlerList(context, wizard);
	}
};

var _onGetTiddler = config.macros.importTiddlers.onGetTiddler;
config.macros.importTiddlers.onGetTiddler = function(context, wizard) {
	if (wizard.getValue('inFileImport')) {
		var me = config.macros.importTiddlers;
		if(!context.status)
			displayMessage("Error in importTiddlers.onGetTiddler: " + context.statusText);
		var tiddler = context.tiddler;
		var fields = tiddler.fields;
		merge(fields, config.defaultCustomFields);
		fields["server.workspace"] = wizard.getValue('workspace');
		delete fields['server.permissions'];
		delete fields['server.bag'];
		fields['server.page.revision'] = 'false';
		delete fields['server.recipe'];
		fields.changecount = 1;
		store.suspendNotifications();
		store.saveTiddler(tiddler.title, tiddler.title, tiddler.text,
			tiddler.modifier, tiddler.modified, tiddler.tags, tiddler.fields,
			false, tiddler.created);
		store.resumeNotifications();
		var remainingImports = wizard.getValue("remainingImports")-1;
		wizard.setValue("remainingImports",remainingImports);
		if(remainingImports === 0) {
			if(context.isSynchronous) {
				store.notifyAll();
				refreshDisplay();
			}
			wizard.setButtons([
					{caption: me.doneLabel, tooltip: me.donePrompt, onClick: me.onClose}
				],me.statusDoneImport);
			autoSaveChanges();
		}
	} else {
		_onGetTiddler.apply(this, arguments);
	}
};

var _onCancel = config.macros.importTiddlers.onCancel;
config.macros.importTiddlers.onCancel = function(e)
{
	var wizard = new Wizard(this);
	if (!wizard.getValue('inFileImport')) {
		return _onCancel.apply(this, arguments);
	}
	var place = wizard.clear();
	config.macros.fileImport.restart(wizard);
	return false;
};

var _step3Html = config.macros.importTiddlers.step3Html;
var _onGetTiddlerList = config.macros.importTiddlers.onGetTiddlerList;
config.macros.importTiddlers.onGetTiddlerList = function(context, wizard) {
	var fileImport = config.macros.fileImport;
	var importTiddlers = config.macros.importTiddlers;
	if (wizard.getValue('inFileImport')) {
		importTiddlers.step3Html = fileImport.step3Html;
	} else {
		importTiddlers.step3Html = _step3Html;
	}
	_onGetTiddlerList.apply(this, arguments);
};
})(jQuery);
//}}}
/*{{{*/
body {
	font-size: 1em;
	font-family: helvetica, arial, sans-serif;
	background-color: #fff;
	color: [[ColorPalette::Foreground]];
}

body ul { margin: 0; }

#popup {
	background-color: [[ColorPalette::TertiaryPale]];
}

#popup.confirmationPopup, .followList {
	font-size: 0.8em;
	padding: 1em;
	border: solid 1px [[ColorPalette::SecondaryMid]];
	background-color: [[ColorPalette::SecondaryPale]];
}

.followList .listTitle {
	text-decoration: underline;
}

#popup .followTiddlersList a {
	display: inline;
	padding: 0;
}

#popup li a {
	color: [[ColorPalette::PrimaryMid]];
	font-weight: bold;
}

#popup li a:hover {
	color: [[ColorPalette::PrimaryPale]];
	background: [[ColorPalette::PrimaryMid]];
}

#popup li.listTitle {
	border-bottom: 1px solid #000;
	font-weight: bold;
	margin-bottom: 10px;
}

#popup.followList {
	margin-left: 50px;
	margin-top: -30px;
}

.followTiddlersList .label {
	display: block;
	left: 10px;
	top: 0px;
	line-height: 16px;
	position: relative;
}

#popup .followTiddlersList .siteIcon{
	height: auto;
}

#popup .followTiddlersList li{
	clear: both;
	display: block;
	height: 48px;
	margin-bottom: 8px;
	position: relative;
}

#popup .followTiddlersList a{
	display: inline;
}

#displayArea {
	margin: 0;
	top: 0px;
	left: 0px;
	width: 100%;
	position: relative;
}

.revisionCloak {
	position: absolute;
	position: fixed !important;
	height: 100%;
	width: 100%;
	top: 0;
	left: 0;
	border: 0;
	margin: 0;
	padding: 0;
	opacity: 0.5;
	filter: alpha(opacity=50);
	background-color: #000;
}

/* *** Header *** */
.header {
	position: relative;
	background-color: [[ColorPalette::PrimaryMid]];
	_width: 100%; /* ie 6 demands */
}

.headerForeground {
	background-color: [[ColorPalette::PrimaryMid]];
	float: left;
	margin: 24px 16px 0px 72px;
	padding: 0;
	position: relative;
	top: 0;
	_width: 70%; /*ie6: needed for the background to actually be transparent*/
	_background-color: transparent; /*ie6: needed to show the search box*/
}

.clearFloat {
	clear: both;
}

#contentWrapper {
	position: relative;
	padding-top: 1px;
	top: -1px;
}

#tiddlerDisplay {
	_position: relative; /* ie 6*/
}

.siteTitle {
	clear: both;
	display: block;
	font-size: 32px;
	font-weight: bold;
	line-height: 32px;
}

.siteSubtitle {
	display: block;
	font-size: 14px;
	height: 16px;
	margin-bottom: 8px;
}

#sidebarSearch {
	padding: 0;
	position: absolute;
	right: 80px;
	top: 8px;
	width: 176px;
}

#sidebarSearch .txtOptionInput {
	width: 100%;
	margin-top: 5px;
	_color: #bbb; /* ie6 danger */
}

#sidebarSearch .txtOptionInput:focus {
	color: #000;
}

#sidebarSearch .searchButton {
	display: none;
}

/* *** Menu Bar *** */

#mainMenu {
	position: static;
	text-align: left;
	margin-left: 72px;
	float: left;
	width: auto;
	padding: 0;
	font-size: 1em;
	line-height: normal;
}

#mainMenu a {
	color: #fff;
	padding: 8px;
	font-size: 0.9em;
	margin-right: 16px;
}

#mainMenu a:hover {
	background-color: [[ColorPalette::PrimaryMid]];
	color: [[ColorPalette::Background]]
}

#sidebarOptions {
	margin-right: 72px;
	float: right;
	font-size: 1.1em;
	line-height: 1.6em;
	min-height: 1em;
	padding-top: 0;
}

#sidebarOptions a {
	margin-right: 8px;
}

.confirmationPopup .button,
#sidebarOptions .button {
	cursor: pointer;
	line-height: 1.4em;
	text-align: center;
	margin-right: 8px;
	margin-left:-2px;
}

.confirmationPopup .button {
	font-size: 0.9em;
	padding: 2px;
}

#sidebarOptions .button {
	font-size: 0.7em;
	float: left;
	width: 80px;
	padding: 0px;
        color: #fff;
}

.confirmationPopup a.button,
#sidebarOptions a {
	border: none;
	margin: 0 0.2em;
	padding: 0.6em 0.25em;
	display: inline;
	color: #666;
}

.confirmationPopup a.button:hover,
#sidebarOptions a:hover {
	color: #000;
}

.confirmationPopup a.button:active,
#sidebarOptions a:active {
	border: solid 1px [[ColorPalette::PrimaryMid]];
	background-color: #fff;
	background: -webkit-gradient( linear, left bottom, left top, color-stop(0.1,rgb(200,200,200)), color-stop(1, rgb(100,100,100)));
	background: -moz-linear-gradient(center bottom , rgb(200,200,200) 10%,rgb(100,100,100) 100%) repeat scroll 0 0 transparent;
}
/* *** Sidebar *** */

#sidebar .wizard table {
	margin: 0px;
}

.tabContents .listTitle:first-child {
	margin-top: 0px;
}

#menuBar {
	background: [[ColorPalette::PrimaryLight]];
	left: 0;
	right: 0;
	position: relative;
	margin: 0;
	padding: 0.5em 0 0.5em 0;
	min-height: 1em;
	overflow: hidden;
	_width: 100%; /* for ie 6 */
}

#sidebarOptions a.button:hover {
	color: [[ColorPalette::PrimaryPale]];
    background: [[ColorPalette::PrimaryMid]];
}

#tiddlerDisplay, #searchResults {
	margin: 16px 448px 0 72px;
}

#sidebarTabs {
	position: absolute;
	right: 72px;
	width: 352px;
	top: 0;
}

#sidebarTabs .tabsetWrapper .tabset {
	width: 87px;
	border-top: 1px solid [[ColorPalette::PrimaryPale]];
	border-left: 1px solid [[ColorPalette::PrimaryPale]];
	border-bottom: 1px solid [[ColorPalette::PrimaryPale]];
	height: auto;
	float: left;
	word-wrap: break-word;
	top: 0;
	padding: 0;
}

#sidebarTabs .tabsetWrapper .tabContents {
	background-color: [[ColorPalette::PrimaryPale]];
	border: 3px solid [[ColorPalette::PrimaryMid]];
	width: 242px;
	_width: 238px;
	left: -3px;
	_left: -5px;
	position: relative;
	min-height: 34em;
	padding: 8px;
	font-size: 0.8em;
}

/* ---- Side style --- */

#sidebarTabs .tabsetWrapper .tabset .tab {
	font-size: 0.9em;
	padding: 0.7em 8px 0.5em;
	color: #fff;
	background: [[ColorPalette::PrimaryLight]];
	border: none;
	line-height: 16px;
	position: relative;
	display: block;
	margin: 0;
}

#sidebarTabs .tabsetWrapper .tabset .tabSelected {
	color: [[ColorPalette::PrimaryMid]];
	background: [[ColorPalette::PrimaryPale]];
	border-top: 3px solid [[ColorPalette::PrimaryMid]];
	border-bottom: 3px solid [[ColorPalette::PrimaryMid]];
	border-left: 3px solid [[ColorPalette::PrimaryMid]];
	z-index: 10;
	margin-top: -1px;
	font-weight: bold;
}

#sidebarTabs .tabContents li {
	border: none;
	margin-left: 0;
	word-wrap: break-word;
}

.tabContents .timeline {
	background: [[ColorPalette::PrimaryPale]];
	margin-bottom: 8px;
}

#sidebarTabs .timeline li.listTitle {
	color: #132E43;
	margin-left: 8px 0;
	padding: 0.3em 0.11em;
	font-size: 1em;
	border-bottom: none;
}

#sidebarTabs .tabContents li a {
	display: block;
	text-align: left;
	margin: 0 0 1px 0;
	padding: 0.3em 1em;
	background: [[ColorPalette::PrimaryPale]];
}

#sidebarTabs .tabsetWrapper .tabset a:hover,
#sidebarTabs .tabContents li a:hover {
	color: [[ColorPalette::PrimaryPale]];
	background: [[ColorPalette::PrimaryMid]];
}

/* Activity Stream */
#sidebarTabs .tabContents .activityStream .feedItem a {
	display: inline-block;
	padding: 0;
	background: none;
}

/* ---- Tagging box --- */
.tagInfo {
	border: 1px solid #cccccc;
	padding: 10px 15px;
	-moz-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
	box-shadow: 0 2px 2px rgba(0,0,0,0.2);
	color: [[ColorPalette::TertiaryMid]];
	background: -moz-linear-gradient(100% 100% 90deg, #f4f4f4, #e5e5e5);
	background: -webkit-gradient(linear, left top, right top, from(#e5e5e5), to(#f4f4f4));
	margin-top: 1em;
	font-size: 13px;
	margin: 0 0 0 56px;
}

.tagInfo ul {
	list-style: none;
	padding-left: 2.2em;
}

.tagInfo ul li {
	display: inline;
}

.tagInfo ul li.listTitle,
.tagInfo .tagging ul li.listTitle {
	color: [[ColorPalette::PrimaryMid]];
	font-size: 13px;
}

.tagInfo ul li a {
	border: none;
}

.tagInfo .tagging ul li {
	float: none;
	display: inline-block;
}

.tagInfo .tagging {
	padding: 0;
}

.viewRevision .toolbar {
	right: 48px;
	top: 8px;
}

.viewRevision .modifierIcon img,
.viewRevision .modifierIcon svg {
	margin-right: 8px;
}

.viewRevision .toolbar svg {
	width: 32px;
	height: 32px;
}

/* --- IE hacks from lattice --- */

/* ie hacks */
* html #menuBar {
	margin-bottom: 8px;
}
.toolbar .svgIconText {
	*display: inline;
}

div.tiddler .toolbar a {
	cursor: pointer;
	float: left\9;
	display: inline\9;
}

* html .toolbar {
	right: 8px;
}
* html .followButton a {
	margin-top: 0px;
	margin-right: 8px;
}
* html #tiddlerDisplay {
	margin-top: 0px;
}

/* for printing purposes */
@media print {
	#mainMenu,
	#sidebar,
	#messageArea,
	.toolbar,
	.followPlaceHolder,
	#backstageButton,
	#backstageArea,
	#sidebarTabs,
	#sidebarSearch .txtOptionInput,
	#sidebarOptions {
		display: none !important;
	}
	#displayArea {
		margin: 1em 1em 0em;
	}
	noscript {
		display:none; /* Fixes a feature in Firefox 1.5.0.2 where print preview displays the noscript content */
	}
	#tiddlerDisplay {
		margin: 16px 16px;
	}
}

@media all and (max-width: 960px){
	#tiddlerDisplay,
	#searchResults {
		margin: 16px 366px 0 16px;
	}

	#mainMenu {
		margin-left: 16px;
	}

	.headerForeground {
		margin-left: 16px;
	}

	#sidebarSearch {
		right: 16px;
	}

	#sidebarOptions {
		margin-right: 16px;
	}

	#sidebarTabs {
		right: 16px;
		width: 326px;
	}

	#sidebarTabs .tabsetWrapper .tabset {
		font-size: 0.9em;
		width: 77px;
	}

	#sidebarTabs .tabsetWrapper .tabContents {
		width: 226px;
		_width: 222px;
	}

	#sidebarTabs .tabContents li a {
		font-size: 0.9em;
	}
}
/*}}}*/
[[StyleSheetTiddler]]
[[StyleSheetCaspian]]
<<familytreelist sex:F>>
/***
|''Name''|TiddlySpaceInstaller|
|''Version''|0.6.0|
|''Requires''|GUID|
|''Source''|https://github.com/jdlrobson/TiddlyWiki/raw/master/plugins/TiddlySpaceInstaller/TiddlySpaceInstaller.js|
!Usage
{{{<<showInstall bar Foo>>}}}
Opens the tiddler Foo to visitors of the bar space. 
In a space that is not bar, nothing happens.

{{{<<install foo bar>>}}}
Provides a ui for installing a space that includes foo and bar taking into account whether the user is new or currently logged in.
optional parameters:
* label - change the label of the button that is clicked to install.
* header - provide alternative text to show for "choose a website address"
* choice - allow a user to install a choice of various spaces
* choiceLabel - control the label presents for each space that is installable
* privateSpace - specifies that the newly created space should be private.
* addMember - specifies that a certain member should be added to the created space - note multiple members can be added to a new space
e.g.
{{{
<<install choice:foo choiceLabel:'install foo' choice:bar choiceLabel:'install bar'>>
}}}
provides an interface to install foo or bar space.
***/
//{{{
(function($) {

var tweb = config.extensions.tiddlyweb;
var tiddlyspace = config.extensions.tiddlyspace;
config.macros.showInstall = {
	handler: function(place, macroName, params) {
		if(config.extensions.tiddlyspace.currentSpace.name == params[0]) {
			story.displayTiddler(null, params[1] || "Install");
		}
	}
};
var macro = config.macros.install = {
	locale: {
		spaceName: "Choose a website address (note this will also be your tiddlyspace username):",
		identity: "Logged in as %0.",
		spaceCreationError: "Failed to create space %0",
		password: "Enter a password:",
		passwordAgain: "Enter password again:",
		setup: "create",
		passwordError: "your passwords do not match.. please try entering them again.",
		nameError: "The name %0 is taken or is invalid. Please try another.",
		loginRequired: "You must be logged in to use this.",
		inputLabel: {
			choice: "Select a space to install:"
		},
		choiceError: "No space has been selected to be installed."
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var args = paramString.parseParams("anon")[0];
		params = args.anon || [];
		var locale = macro.locale;
		var mustBeLoggedIn = args.loggedInOnly ? args.loggedInOnly[0] != "no" : false;
		var options = {
			headerTxt: args.header ? args.header[0] : locale.spaceName,
			setupLabel: args.label ? args.label[0] : locale.setup,
			loginTiddler: args.loginTiddler ? args.loginTiddler[0] : false,
			inputs: args.input ? args.input : [],
			paramifierName: args.pname ? args.pname[0] : "install",
			choices: args.choice,
			choiceLabels: args.choiceLabel,
			privateSpace: args.privateSpace ? true : false,
			addMember: args.addMember ? args.addMember.join(",") : false
		};
		tweb.getStatus(function(r) {
			options.identity = tweb.status.identity;
			var host = r.server_host.host;
			if(params.length === 0) {
				params = [ tiddlyspace.currentSpace.name ];
			}
			options.includeSpaces = params;
			var container = $("<div />").appendTo(place)[0];
			tweb.getUserInfo(function(userInfo) {
				var disabled = userInfo.anon && mustBeLoggedIn && !options.identity;
				if(!disabled) {
					var form = $("<form />").addClass("spaceInstaller").appendTo(container)[0];
					macro._fillForm(form, host, userInfo, options);
				} else {
					var c = $("<span />").addClass("annotation").appendTo(container)[0];
					if(options.loginTiddler) {
						wikify(store.getTiddlerText(options.loginTiddler), c);
					} else {
						$(c).text(macro.locale.loginRequired);
					}
				}
			});
		});
	},
	_fillForm: function(form, host, userInfo, options) {
		var locale = macro.locale;
		$("<div />").text(options.headerTxt).appendTo(form);
		var user = $("<input />").addClass("reqInput input").attr("name", "username").attr("type", "text").appendTo(form);
		$("<span />").text("." + host).addClass("reqInputLabel inputLabel").appendTo(form);
		var identity = options.identity;
		if(userInfo.anon && !identity) {
			$("<div />").addClass("reqInputLabel inputLabel").text(locale.password).appendTo(form);
			var pass1 = $("<input />").addClass("reqInput input").attr("name", "pass1").attr("type", "password").appendTo(form);
			$("<div />").addClass("reqInputLabel inputLabel").text(locale.passwordAgain).appendTo(form);
			var pass2 = $("<input />").addClass("reqInput input").attr("name", "pass2").attr("type", "password").appendTo(form);
		} else if(userInfo.anon && identity) {
			$("<input />").attr("type", "hidden").attr("name", "identity").val(identity).appendTo(form);
			$("<div />").text(locale.identity.format(identity)).appendTo(form);
		}
		var inputs = options.inputs;
		for(var i = 0; i < inputs.length; i++) {
			var name = inputs[i];
			if(!["pass1", "pass2", "username"].contains(name)) {
				$("<div />").addClass("inputLabel optInputLabel").text(locale.inputLabel[name] || name).appendTo(form);
				$("<input />").addClass("input optInput").attr("input", "user").attr("name", name).appendTo(form);
			}
		}
		if(options.choices) {
			var labels = options.choiceLabels || [];
			$("<div />").addClass("inputLabel optInputLabel").text(locale.inputLabel.choice).appendTo(form);
			for(var i = 0; i < options.choices.length; i++) {
				var choice = options.choices[i];
				var radio = $("<input type='radio' />").addClass("input optInput choice").attr("name", "choice").val(choice).appendTo(form)[0];
				if(i === 0) {
					$(radio).attr("checked", true);
				}
				var label = labels[i] ? labels[i] : choice;
				$("<span />").text(label).appendTo(form);
			}
		}
		$("<input />").addClass("installButton").attr("type", "submit").val(options.setupLabel).appendTo(form);
		options.formEl = form;
		$("<div />").addClass("messageArea annotation").hide().prependTo(form.parentNode);
		$(form).submit(function(ev) {
			ev.preventDefault();
			var paramifier = [];
			$("[input=user]", ev.target).each(function(i, el) {
				paramifier.push("%0:%1".format($(el).attr("name"), $(el).val()));
			});
			if(paramifier.length === 0) {
				paramifier = false;
			} else {
				paramifier = paramifier.join(" ");
			}
			var user = $("[name=username]", ev.target).val();
			var pass = $("[name=pass1]", ev.target).val();
			var pass2 = $("[name=pass2]", ev.target).val();
			options.paramifier = paramifier;
			var choices = $("[name=choice]", form);
			var includes = options.includeSpaces;
			if(choices.length > 0) {
				includes = [];
				var space = $("[name=choice]:checked").val();
				if(space) {
					includes.push(space);
				}
			}
			if(includes.length === 0) {
				macro.updateUserMessage(form, 3);
				return;
			}
			$(form).hide();
			macro.updateUserMessage(form, 4, true);
			if(userInfo.anon && identity) {
				pass = macro.generatePassword();
				macro.installNewUser(user, pass, includes, options);
			} else if(userInfo.anon && pass != pass2) {
				macro.updateUserMessage(form, 2);
			} else if(userInfo.anon && user && pass == pass2) {
				macro.installNewUser(user, pass, includes, options);
			} else if(!userInfo.anon && user) {
				macro.setup(user, includes, options)
			} else {
				macro.updateUserMessage(form, 1);
			}
		});
	},
	updateUserMessage: function(form, code, keephidden) {
		var locale = macro.locale;
		var container = form.parentNode;
		var username = $("[name='username']", form).text();
		var msg = "";
		switch(code) {
			case 1:
				msg = "Please enter a website address";
				break;
			case 2:
				msg = locale.passwordError;
				break;
			case 3:
				msg = locale.choiceError;
				break;
			case 4:
				msg = "Installing your new space...";
				break;
			case 5:
				msg = macro.locale.nameError.format(username);
				break;
			case 6:
				msg = macro.locale.spaceCreationError.format(username);
		}
		$(".messageArea", container).text(msg).show();
		if(!keephidden) {
			$(form).show();
		}
	},
	generatePassword: function() {
		var guid = config.extensions.GuidPlugin;
		return guid ? guid.guid.generate() + "_" + guid.guid.generate() :
			"" + Math.random() * 1000;
	},
	login: function(username, password, callback, errback, challenger) {
		challenger = challenger ? challenger : "tiddlywebplugins.tiddlyspace.cookie_form";
		var uri = "%0/challenge/%1".format([tweb.host, challenger]);
		ajaxReq({ url: uri, type: "POST", success: callback,
			data: {
				user: username,
				password: password,
				csrf_token: tiddlyspace.getCSRFToken(),
				tiddlyweb_redirect: tweb.serverPrefix + "/status" // workaround to marginalize automatic subsequent GET
			},
			error: function(xhr, error, exc) {
				if(errback) {
					errback.apply(this, arguments);
				} else {
					displayMessage(admin.locale.loginError.format(username, error));
				}
			}
		});
	},
	installNewUser: function(username, password, includes, options) {
		username = username.toLowerCase();
		var user = new tiddlyweb.User(username, password, tweb.host);
		user.create(
			function() {
				macro.login(username, password, function() {
					macro.setup(username, includes, options);
				});
			},
			function() {
				macro.updateUserMessage(options.formEl, 5);
				$(options.formEl).show();
			}
		);
	},
	setup: function(spacename, includes, options) {
		var identity = options.identity;
		var space = new tiddlyweb.Space(spacename, tweb.host);
		tweb.getStatus(function(status) {
			var url = tiddlyspace.getHost(status.server_host, spacename);
			var newLocation = "%0/tiddlers.wiki#".format(url);
			if(identity) {
				newLocation += "auth:OpenID=%0".format(identity);
			}
			if(options.paramifier) {
				newLocation += "%0:[[%1]]".format(options.paramifierName, options.paramifier);
			}
			if(options.addMember) {
				newLocation += "addMember:[[%0]]".format(options.addMember);
			}
			if(options.privateSpace) {
				newLocation += "privacyMode:[[private]]";
			}
			space.create(function() {
				$.ajax({
					url: tweb.host + "/spaces/"+ spacename,
					type: "POST",
					contentType: "application/json",
					data: jQuery.toJSON({
						"subscriptions": includes
					}),
					success: function() {
						window.location = newLocation;
					},
					error: function() {
						window.location = newLocation;
					}
				});
			}, function() {
				macro.updateUserMessage(options.formEl, 6);
			});
		});
	}
};

var p = config.paramifiers.addMember = {
	onstart: function(members) {
		try {var space = config.extensions.tiddlyspace.currentSpace.name;
		var host = config.extensions.tiddlyweb.host;
		space = new tiddlyweb.Space(space, host); // XXX: singleton
		p.add(space, members.split(",")); } catch(e) {};
	},
	add: function(space, members) {
		var _dirty = story.isDirty();
		for(var i = 0; i < members.length; i++) {
			var username = members[i];
			space.members().add(username, function(){
				story.setDirty(false);
			}, function(){
				story.setDirty(false);
			});
		}
	}
};
var p2 = config.paramifiers.privacyMode = {
	onstart: function(mode) {
		if(mode == 'private') {
			config.options.chkPrivateMode = true;
			store.getTiddler("SystemSettings").fields['server.page.revision'] = 'false';
			saveSystemSetting("chkPrivateMode", true);
		}
	}
};

})(jQuery);
//}}}
body {
	font-family: "helvetica neue";
	font-size: 16px;
}

#TSbar {
	background: #000;
	background: -moz-linear-gradient(center bottom,#222 0%, #333 50%, #555 100%);
	background: -webkit-gradient(linear,left bottom,left top,color-stop(0, #222),color-stop(0.5, #333),color-stop(1, #555));
	border-bottom: 1px solid black;
	height: 24px;
}

#main-content {
	margin: 0 auto;
	padding-top: 2em;
	width: 960px;
}

#space-details {
	height: 100px;
	margin: 0 0 5em;
}

#space-details img {
	border-radius: 2px;
	float: left;
	margin-right: 2em;
}

#title-subtitle {
	color: #79757A;
}

.spaceaddress {
	height: 62px;
	line-height: 62px;
}

#title-subtitle p {
	font-size: 1.3em;
	line-height: 38px;
}

.managespaces {
	background: #D0D5D6;
	color: #F0F4F8;
	border-radius: 4px;
	float: right;
	padding: 0 0.7em;
	text-decoration: none;
	-webkit-transition: all 0.4s ease-in-out;
	-moz-transition: all 0.4s ease-in-out;
	-o-transition: all 0.4s ease-in-out;
	-ms-transition: all 0.4s ease-in-out;
	transition: all 0.4s ease-in-out;
}

#space-details:hover .managespaces {
	background: #ADD1DD;
}

#space-details .managespaces:hover {
	background: #0082AF;
}

h1 {
	color: #B8B6BD;
	font-size: 2em;
}

h1 span {
	color: #0059AF;
	color: #0082AF;
	font-size: 1.5em;
}

#holder {
	background: #DCE7F1;
	border-radius: 2px;
	border: 1px solid #ADD1DD;
	box-shadow: 1px 2px 3px 0px rgba(0,0,0,0.25);
}

#appswitcher {
	background: #F0F4F8;
	border-radius: 2px;
	box-shadow: 1px 2px 3px 0px rgba(0,0,0,0.25), -1px 0px 3px 0px rgba(0,0,0,0.25);
	margin-top: -40px;
	margin-right: 10px;
	margin-bottom: -10px;
	float: right;
	width: 60%;
}

#appswitcher h2 {
	color: #4C4A54;
	color: #8C9DA7;
	font-size: 2em;
	font-weight: 500;
	line-height: 1.8em;
	text-shadow: 0 1px 0 #fff;
	margin-left: 1em;
}

#app-list {
	background: #F0F4F8;
}

#app-list li {
	background: url('http://colmjude.tiddlyspace.com/double_angle_lightblue_42x42.png') no-repeat 88% #F0F4F8;
	border-top: 1px solid #fff;
	border-bottom: 1px solid #C3D3DD;
	height: 4.25em;
	line-height: 3.125em;
	-webkit-transition: background 0.4s linear;
	-moz-transition: background 0.4s linear;
	-o-transition: background 0.4s linear;
	-ms-transition: background 0.4s linear;
	transition: background 0.4s linear;
}

#app-list li:hover {
	background: url('http://colmjude.tiddlyspace.com/double_angle_darkpink_bevel_42x42.png') no-repeat 90% #F3F9FF;
	border-top: 1px solid #F0F4F8;
	cursor: pointer;
	line-height: 3.25em;
}

#app-list li:hover:last-child {
	line-height: 3.125em;
}

#app-list li a {
	display: block;
	color: #BC4378;
	font-size: 2.5em;
	text-decoration: none;
	height: 100%;
	width: 100%;
	-webkit-transition: color 0.4s linear;
	-moz-transition: color 0.4s linear;
	-o-transition: color 0.4s linear;
	-ms-transition: color 0.4s linear;
	transition: color 0.4s linear;
}

#app-list li:hover a {
	color: #E56AA0;
}

#app-list li a img {
	position: relative;
	top: 0.2125em;
	margin: 0 1em;
	height: 1.25em;
	width: 1.25em;
}

#app-list li a span.comingsoon {
	color: #B8B6BD;
	font-size: 0.5em;
}

#app-list li a span.comingsoon.highlight {
	color: #BC4378;
}

#app-desc {
	float: left;
	width: 35%;
}

#app-desc ul {
	/* use as faded color ? */
	color: #C3D3DD;
	color: #8C9DA7;
	font-size: 0.9em;
	font-style: italic;
	margin-top: 18px;
	margin-right: -1em;
	text-align: right;
}

#app-desc ul li {
	display: table;
	border-bottom: 1px dashed #F0F4F8;
	height: 70px;
	padding-left: 1em;
	-webkit-transition: color 0.4s linear;
	-moz-transition: color 0.4s linear;
	-o-transition: color 0.4s linear;
	-ms-transition: color 0.4s linear;
	transition: color 0.4s linear;
}

#app-desc ul li.highlightdesc {
	color: #D65C8C;
}

#app-desc ul li:first-of-type {
	border-top: 1px dashed #F0F4F8;
}

#app-desc ul li p {
	display: table-cell;
	vertical-align: middle;
}

#addapp {
	margin: 1.5em 0 1em;
	padding: 10px;
	text-align: center;
}

#addapp button {
	background: #E7DFE3;
	background: rgba(206,199,203, 0.8);
	color: #F0F4F8;
	border: none;
	border-radius: 4px;
	font-size: 2em;
	padding: 16px 24px 12px;
	-webkit-transition: all 0.4s ease-in-out;
	-moz-transition: all 0.4s ease-in-out;
	-o-transition: all 0.4s ease-in-out;
	-ms-transition: all 0.4s ease-in-out;
	transition: all 0.4s ease-in-out;
}

#addapp:hover button {
	background: #BC4378;
}

#addapp button:hover {
	cursor: pointer;
}

#footer {
	background: #1A1F1E;
	margin-top: 3em;
	padding: 0.3em 0;
	clear: both;
}

#footer-content {
	color: #B2AAA4;
	font-size: 0.8em;
	line-height: 1.3em;
	margin: 0 auto;
	width: 960px;
}

#footer .links {
	float: right;
}

#footer .links a {
	margin-left: 10px;
}

#footer-content a {
	color: #B2AAA4;
	text-decoration: none;
}

#footer-content a:hover {
	color: #80a7c1;
	text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>Reply</title>
	<link rel="stylesheet" href="//tiddlyspace.com/bags/benspa_public/tiddlers/bootvelcro.css">
	<style>
		html,
		body {
			overflow: hidden;
			background-color: transparent;
		}

		#container {
			/* prevent a fouc if no images present */
			display: none;
		}

		.modal-header {
			border-bottom: none;
			padding: 5px 0 0;
			position: absolute;
			width: 100%;
			background-color: #e0e0e0;
			-webkit-border-radius: 6px 6px 0 0;
			-moz-border-radius: 6px 6px 0 0;
			border-radius: 6px 6px 0 0;
			cursor: move;
		}

		.form-actions {
			position: absolute;
			bottom: 0;
			box-sizing: border-box;
			-moz-box-sizing: border-box;
			width: 100%;
			margin: 0;
			border-radius: 0 0 6px 6px;
			background-color: #e0e0e0;
			border-top: 1px solid gray;
		}

		.form-actions input.btn {
			width: auto;
			float: right;
			margin: 0 0.2em;
		}

		.closeBtn {
			background-color: #DCE7F1 !important;
		}

		.primary {
			background-color: #09F !important;
		}

		h1 {
			margin-bottom: 9px;
			margin-top: 9px;
		}

		body {
			width: 100%;
			height: 100%;
			position: absolute;
		}

		.modal {
			margin: 10px;
			top: 0;
			left: 0;
			bottom: 0;
			width: 510px;
			position: absolute;
			box-shadow: #444 0px 0px 10px 2px;
			border-radius: 6px;
			background-color: white;
			border: 1px solid gray;
			background-color: #F0F4F8;
		}

		label em {
			cursor: pointer;
		}

		.modal-body {
			overflow: auto;
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			margin: 65px 20px 67px;
			background-color: transparent;
		}

		.nav-tabs {
			padding-left: 1%;
			margin: 0;
			width: 99%;
			border-color: gray;
		}

		.nav-tabs > li {
			cursor: pointer;
		}

		.nav-tabs > li > a {
			line-height: 2.4em;
			font-weight: bold;
			font-size: 100%;
		}

		.nav-tabs > li.active > a{
			background-color: #F0F4F8;
			border-color: gray;
			border-bottom-color: #F0F4F8;
		}

		.active {
			display: block;
		}

		input,
		textarea,
		select,
		.uneditable-input {
			color: #606060;
		}

		.imagePicker {
			-moz-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
			-webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
			box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
			border: 1px solid #CCC;
			height: 110px;
			overflow: auto;
			-webkit-border-radius: 3px;
			-moz-border-radius: 3px;
			border-radius: 3px;
			margin-left: 0;
		}

		.imagePicker img {
			margin: 5px;
			border: 2px solid transparent;
		}

		.imagePicker .current {
			border: 2px dotted #555;
		}

		label {
			font-weight: bold;
		}

		.form-actions label {
			float: left;
			margin-top: 0.75em;
		}

		fieldset input,
		fieldset textarea {
			width: 90%;
			border-color: gray;
		}

		@media all and (max-width: 550px) {
			.modal {
				width: 95%;
			}
		}

		#help {
			position: absolute;
			border: 0;
			right: 4px;
			top: 5px;
			text-indent: -9999px;
			color: transparent;
			height: 16px;
			width: 16px;
			background: none;
			background-image: url(/bags/common/tiddlers/help.png);
			background-repeat: no-repeat;
			background-color: white;
			z-index: 2;
			border-radius: 10px;
		}

		#help-info {
			padding: 0;
			border: 1px solid gray;
			width: 60%;
			height: 50px;
			color: #404040;
			background-color: white;
			position: absolute;
			top: 5px;
			right: 5px;
			z-index: 1;
			cursor: auto;
			border-radius: 5px;

		}

		#help-info p {
			padding: 10px 25px;
			margin-bottom: 0;
		}
	</style>
</head>
<body>
	<div id="container">
		<form action="#" class="modal">
			<div class="modal-header">
				<button id="help">help</button>
				<div id="help-info" style="display:none;"><p>
				Found something interesting? Write about it in your own space. <a href="//docs.tiddlyspace.com/Reply to this Tiddler" target="_blank">Find out more</a>
				</p></div>
				<ul class="nav nav-tabs" data-tabs="tabs">
					<li class="active" data-tab-name="post"><a href="#postForm">Reply</a></li>
				</ul>
			</div>


			<fieldset id="postForm" class="modal-body">
				<label>Title
					<input type="text" name="title">
				</label>
				<input type="hidden" name="url">
				<label>Post
					<textarea name="text" rows="8"></textarea>
				</label>
				<label>Tags
					<input type="text" name="tags" value="">
				</label>
			</fieldset>


			<div class="form-actions">
				<label class="checkbox">
					<input type="checkbox" name="private" val="private">
					keep private
				</label>
				<input type="submit" class="btn primary btn-large" value="Done">
				<input type="button" class="btn btn-large closeBtn" value="Cancel">
			</div>
		</form>
	</div>

	<script type="text/javascript"
            src="/bags/common/tiddlers/jquery.js"></script>
	<script type="text/javascript" src="/bags/tiddlyspace/tiddlers/chrjs"></script>
	<script type="text/javascript" src="/bags/common/tiddlers/_reply.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
	<title>Account</title>
	<link href="/bags/common/tiddlers/profile.css" type='text/css' rel='stylesheet' >
	<link href="/bags/common/tiddlers/admin.css" type='text/css' rel='stylesheet' >
	<link href="/bags/common/tiddlers/jquery-ui.custom.css" type='text/css' rel='stylesheet' >
</head>
<body>

<div id="container">
	<div class="main section">
		<a class="app" href="/">home</a>
		<div class="left">
		<div id="siteiconArea">
		<h2>User Icon</h2>
		<div>
			<img id="siteicon" class="siteicon">
			<form id="upload" method="POST" enctype="multipart/form-data">
				<input type="hidden" name="title" value="SiteIcon" />
				<input type="hidden" name="tags" value="excludeLists">
				<input type="hidden" name="csrf_token" class="csrf" />
				<input type="file" name="file" accept="image/*" />
				<input type="submit" value="upload" />
			</form>
			<div id="dropzone">Drop file here
				<img class="notloading" src="/bags/common/tiddlers/ajax-loader.gif" alt="submitting SiteIcon" />
			</div>
		</div>
		</div>
		<h2>Find Space</h2>
		<form class="spaceSearch">
			<input class="inputBox" type="text" placeholder="find space" />
			<a href="http://docs.tiddlyspace.com/What%20is%20a%20Space%3F" class="help"
				title="What is a space?">What is a space?</a>
			<button>view all</button>
		</form>
		<div class='list-container'>
			You are a member of the following spaces:
			<ul class='ts-space-search'>
			</ul>
		</div>
		<h2>Create New Space</h2>
		<form class="ts-spaces">
			<input class="inputBox" type="text" name="spacename" placeholder="space name"><span class="hostSuffix">.tiddlyspace.com</span>
			<input type="submit" value="Create Space" />
		</form>
		</div>
		<div class="right">
		<h2>Change Password</h2>
		<form class="ts-password">
			<input class="inputBox" placeholder="existing password" type="password" name="password">
			<input class="inputBox" placeholder="new password" type="password" name="new_password">
			<input class="inputBox" placeholder="new password"	type="password" name="new_password_confirm">
			<input type="submit" value="Change password">
		</form>
		<h2>OpenID</h2>
		<h3>Why OpenID?</h3>
		<a href="http://openid.net/"><img src="/bags/common/tiddlers/openid.png" alt="openid" ></a><br />
		Use just one username and password across hundreds of OpenID-enabled sites.<br />
		It's an open standard.<br />
		<a href="http://openid.net/what/">learn more</a>
		<ul class="ts-identities"></ul>
		<form class="ts-openid" target="_top">
			<div>
				Add an openid:
			</div>
			<input class="inputBox" type="text" name="openid" placeholder="your openid" />
			<input type="submit" value="Register" />
			<a href="http://openid.net/get-an-openid/" class="help"
			title="What is an open id?">What is an open id?</a>
		</form>
		</div>
		<div class="clear"></div>
	</div>
</div>
<script src="/bags/common/tiddlers/backstage.js"></script>
<script src='/bags/common/tiddlers/jquery.js'></script>
<script src='/bags/tiddlyspace/tiddlers/chrjs'></script>
<script src='/bags/common/tiddlers/chrjs.space'></script>
<script src='/bags/common/tiddlers/chrjs.users'></script>
<script src='/bags/common/tiddlers/chrjs.identities'></script>
<script src="/bags/common/tiddlers/jquery-ui.custom.js"></script>
<script src='/bags/common/tiddlers/jquery-form.js'></script>
<script src="/bags/common/tiddlers/siteiconupload.js"></script>
<script src='/bags/common/tiddlers/ts.js'></script>
<script src="/status.js"></script>
<script type="text/javascript">
/*
 * jQuery UI Autocomplete HTML Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 */
(function( $ ) {

var proto = $.ui.autocomplete.prototype,
	initSource = proto._initSource;

function filter( array, term ) {
	var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
	return $.grep( array, function(value) {
		return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
	});
}

$.extend( proto, {
	_initSource: function() {
		if ( this.options.html && $.isArray(this.options.source) ) {
			this.source = function( request, response ) {
				response( filter( this.options.source, request.term ) );
			};
		} else {
			initSource.call( this );
		}
	},

	_renderItem: function( ul, item) {
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
			.appendTo( ul );
	}
});

})( jQuery );

/***
_accounts application specific javascript
***/
var link;
ts.init(function(ts) {
	if(ts.user.anon) { // redirect to homepage when user not logged in
		window.location = ts.getHost();
	} else if(ts.user.name === ts.currentSpace){
		initSiteIconUpload(ts.user.name);
	} else {
		link = $("<a />").attr("href", ts.getHost(ts.user.name) + "/_account").text("Change User Icon");
		$("#siteiconArea div").empty().append(link);
	}
	$(".hostSuffix").text("." + ts.getHost("").split("//")[1]);
	ts.getSpaces(function(spaces) {
		$("<div class='info' />").text("You have " + spaces.length + " spaces.").insertBefore($(".spaceSearch")[0]);
		$("form.spaceSearch input").autocomplete({
			html: true,
			source: function(req, response) {
				ts.getSpaces(function(spaces) {
					var selected = [];
					for(var i = 0; i < spaces.length; i++) {
						var space = spaces[i];
						if(space.name.indexOf(req.term) > -1) {
							var host = ts.getHost(space.name) ;
							var img = host + "/SiteIcon";
							selected.push({
								value: space.name,
								label: '<a href="' + host + '" target="_parent" class="autocompleteLink"><img src="' + img + '" style="height:24px;width:auto;max-height:24px;max-width:24px;"/>' + space.name + '</a>'
							});
						}
					}
					response(selected);
				});
			},
			select: function(event, ui) {
				window.top.location = ts.getHost(ui.item.value);
			}
		});

		var $ul = $('.ts-space-search');
		$.each(spaces, function(i, space) {
			$ul.append($('<li/>').html($('<a/>').attr('href', space.uri)
				.text(space.name)));
		});

		$('form.spaceSearch button').click(function(ev) {
			$('.list-container').slideToggle('fast');
			ev.preventDefault();
			return false;
		});
	});
});

if(window != window.top) {
	$("html").addClass("iframeMode");
	$("a").live("click",function(ev) {
		$(ev.target).attr("target", "_parent");
	});
}
</script>
<!--[if lt IE 8]>
<script type="text/javascript" src="/bags/common/tiddlers/json2.js"></script>
<![endif]-->
</body>
</html>
<html>
<head>
<title>Bulk Deletion Application</title>
<link rel="stylesheet" href="/bags/common/tiddlers/profile.css" type="text/css">
<script src="/bags/common/tiddlers/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="container">
	<div id="header">
		<h1>Bulk Deletion Application</h1>
	</div>
	<div class="main section">
	Please take care when using this space as it can delete everything in your private and public bags. To use simply select the tiddlers you want to delete and click the delete all button.

	<form id="filter" style="display:none;">
		<p>Note you can filter this list using <a href="http://tweb-filters.tiddlyspace.com/GettingStarted">tiddlyweb filters</a>.</p>
		<h2>Filter this list:</h2>
		<input name="value" type='text' placeholder='select=tag:systemConfig'>
		<button>Apply Filter</button>
	</form>
	<h2>Select tiddlers to delete</h2>
	<table id='bulk'>
	</table>
	</div>
</div>
<script type='text/javascript'>
var space = window.location.host.split(".")[0];
var tableObj = {};
var url = "/recipes/" + space + "_private/tiddlers";
var hash = window.location.hash;
if(hash.indexOf("?") === 1) {
	url += hash.substr(1, hash.length);
}
$("#filter").submit(onSubmit).show();
var onSubmit = function(ev) {
	var filterVal = $("#filter [name=value]").val();
	if(filterVal.indexOf("?") === 0) {
		filterVal = filterVal.substr(1, filterVal.length);
	}
	window.location.hash = "#?" + filterVal;
	window.location.reload();
	ev.preventDefault();
};
if(window.location.hash.indexOf("#?") > -1) {
	$("#filter [name=value]").val(window.location.hash.substr(2));
}
$("#filter button").click(onSubmit);
$.ajax({ url: url,
	dataType: "json", success: function(tiddlers) {
		var table = $("#bulk")[0];
		$("<tr><th>Title</th><th>Status</th><th>Select <input type='checkbox' class='batchSelect' /></th></tr>").appendTo(table);
		$(".batchSelect").click(function(ev) {
			var ch = $(ev.target).attr("checked") ? true : false;
			$("input.tidCheckBox:visible").attr("checked", false).each(function(i, el) {
				$(el).attr("checked", ch);
			});
		});
		$("<button />").text("delete all selected tiddlers").insertBefore(table).click(function(ev) {
			if(!confirm("DELETE all the tiddlers that have been selected before? Be warning that this is irreversable!")) {
				return;
			}
			var tiddlers = [];
			$("input.tidCheckBox:checked:visible").each(function(i, el) {
				var tid = $(el).data("tiddler");
				if(tid) {
					tiddlers.push(tid);
				}
			});
			function deletetid(tid) {
				$.ajax({ url: "/bags/" + tid.bag + "/tiddlers/" + encodeURIComponent(tid.title),
					type: "DELETE",
					success: function(r) {
						var el = tableObj[tid.title];
						$(el).animate({ opacity: 0}, {
							complete: function(el) {
								$(this).remove();
								}
							});
					}
				});
			}
			for(var i = 0; i < tiddlers.length; i++) {
				var tid = tiddlers[i];
				deletetid(tid);
			}
		});
		for(var i = 0; i < tiddlers.length; i++) {
			var tiddler = tiddlers[i];
			if(tiddler.bag.indexOf(space) === 0) {
				var row = $("<tr />").appendTo(table)[0];
				$("<td />").text(tiddler.title).appendTo(row);
				var status = tiddler.bag.split("_")[1];
				$("<td />").text(status).appendTo(row);
				var deletecol = $("<td />").appendTo(row)[0];
				tableObj[tiddler.title] = row;
				$("<input />").addClass("tidCheckBox").attr("type", "checkbox").data("tiddler", tiddler).appendTo(deletecol);
			}
		}
	}
});
</script>
</body>
</html>
!Upload an icon
<<tiddler spaceIcon>>
!Describe your space
If you haven't already done so, you should provide a brief decscription of yourself and what you're using this space for. To do this, just edit the [[SiteInfo]] tiddler (keeping the title the same of course).

!Change the title
<<tiddler spaceTitle>>
!Change the theme
<<tiddler colorScheme>>
!Change the menu
If you'd like to change the menu items along the top, you can edit the [[MainMenu]] tiddler.

!Change the default tiddlers
<<tiddler setDefaultTiddlers>>
!More Advanced customisations
If you know HTML and CSS, you can edit some or all of the following tiddlers to customise your space further:
* PageTemplate
* EditTemplate
* ViewTemplate
* StyleSheet
iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMBAMAAACkW0HUAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGFVM9rE0EU/jZuqdAiCFprDrJ4kCJJWatoRdQ2/RFiawzbH7ZFkGQzSdZuNuvuJrWliOTi0SreRe2hB/+AHnrwZC9KhVpFKN6rKGKhFy3xzW5MtqXqwM5+8943731v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GqHGAYAu28pMW6JEwIAAAAASUVORK5CYII=
@@Please do not modify this tiddler; it was created automatically upon space creation.@@
Welcome to @caspian a new theme from @jon. To get up and running you may want to edit [[GettingStarted]].
@@Please do not modify this tiddler; it was created automatically upon space creation.@@
/***
|''Name''|TiddlySpaceConfig|
|''Version''|0.7.7|
|''Description''|TiddlySpace configuration|
|''Status''|stable|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpaceConfig.js|
|''CoreVersion''|2.6.1|
|''Requires''|TiddlyWebConfig ServerSideSavingPlugin TiddlyFileImporter|
!Code
***/
//{{{
(function($) {

var tweb = config.extensions.tiddlyweb;

var recipe = config.defaultCustomFields["server.workspace"].split("recipes/")[1];
var currentSpace; // assigned later

var disabledTabs = [];

var coreBags = ["system", "tiddlyspace"];
var systemSpaces = ["plugins", "info", "images", "theme"];
systemSpaces = $.map(systemSpaces, function(item, i) {
	return "system-%0_public".format(item);
});

// hijack search macro to add custom attributes for mobile devices
var _search = config.macros.search.handler;
config.macros.search.handler = function(place, macroName, params) {
	_search.apply(this, arguments);
	$(".searchField:input", place).
		attr({ autocapitalize: "off", autocorrect: "off" });
};

// arg is either a container name or a tiddler object
// if fuzzy is truthy, space may be inferred from workspace (for new tiddlers)
// returns space object or false
var determineSpace = function(arg, fuzzy) {
	if(typeof arg == "string") { // container name
		var space = split(arg, "_", "r");
		return ["public", "private"].contains(space.type) ? space : false;
	} else if(arg) { // tiddler
		var container = determineContainer(arg, fuzzy);
		return container ? determineSpace(container.name, fuzzy) : false;
	} else {
		return false;
	}
};

// if fuzzy is truthy, container may be inferred from workspace for new tiddlers
// returns container object or false
var determineContainer = function(tiddler, fuzzy) { // TODO: expose?
	var bag = tiddler.fields["server.bag"];
	var recipe = tiddler.fields["server.recipe"]; // XXX: unused/irrelevant/redundant!?
	if(bag) {
		return { type: "bag", name: bag };
	} else if(recipe) {
		return { type: "recipe", name: recipe };
	} else if(fuzzy) { // new tiddler
		var workspace = tiddler.fields["server.workspace"];
		if(workspace) {
			var container = split(workspace, "/", "l");
			return ["bags", "recipes"].contains(container.type) ? container : false;
		} else {
			return false;
		}
	} else {
		return false;
	}
};

// hijack removeTiddlerCallback to restore tiddler from recipe cascade -- TODO: move into TiddlyWebWiki?
var sssp = config.extensions.ServerSideSavingPlugin;
var _removeTiddlerCallback = sssp.removeTiddlerCallback;
sssp.removeTiddlerCallback = function(context, userParams) {
	var title = context.tiddler.title;
	var recipe = context.tiddler.fields["server.recipe"];
	_removeTiddlerCallback.apply(this, arguments);
	if(recipe) {
		context.workspace = "recipes/" + recipe;
		var callback = function(context, userParams) {
			if(context.status) {
				var dirty = store.isDirty();
				store.saveTiddler(context.tiddler).clearChangeCount();
				store.setDirty(dirty);
			} else {
				store.notify(title, true);
			}
		};
		context.adaptor.getTiddler(title, context, null, callback);
	}
};

// splits a string once using delimiter
// mode "l" splits at the first, "r" at the last occurrence
// returns an object with members type and name
var split = function(str, sep, mode) {
	mode = mode == "r" ? "pop" : "shift"; // TODO: use +/-1 instead of "l"/"r"?
	var arr = str.split(sep);
	var type = arr.length > 1 ? arr[mode]() : null;
	return { type: type, name: arr.join(sep) };
};

var plugin = config.extensions.tiddlyspace = {
	currentSpace: determineSpace(recipe),
	coreBags: coreBags.concat(systemSpaces),

	determineSpace: determineSpace,
	isValidSpaceName: function(name) {
		return name.match(/^[a-z][0-9a-z\-]*[0-9a-z]$/) ? true : false;
	},
	getCurrentBag: function(type) {
		return "%0_%1".format(currentSpace, type);
	},
	getCurrentWorkspace: function(type) {
		return "bags/" + this.getCurrentBag(type);
	},
	// returns the URL for a space's avatar (SiteIcon) based on a server_host
	// object and an optional space name
	// optional nocors argument prevents cross-domain URLs from being generated
	getAvatar: function(host, space, nocors) {
		if(space && typeof space != "string") { // backwards compatibility -- XXX: deprecated
			space = space.name;
		}
		var subdomain = nocors ? currentSpace : space;
		host = host ? this.getHost(host, subdomain) : "";
		var bag = space ? "%0_public".format(space) : "tiddlyspace";
		return "%0/bags/%1/tiddlers/SiteIcon".format(host, bag);
	},
	// returns the URL based on a server_host object (scheme, host, port) and an
	// optional subdomain
	getHost: function(host, subdomain) {
		if(host === undefined) { // offline
			tweb.status.server_host = {}; // prevents exceptions further down the stack -- XXX: hacky workaround, breaks encapsulation
			return null;
		}
		subdomain = subdomain ? subdomain + "." : "";
		var url = "%0://%1%2".format(host.scheme, subdomain, host.host);
		var port = host.port;
		if(port && !["80", "443"].contains(port)) {
			url += ":" + port;
		}
		return url;
	},
	disableTab: function(tabTiddler) {
		if(typeof(tabTiddler) == "string") {
			disabledTabs.push(tabTiddler);
		} else {
			for(var i = 0; i < tabTiddler.length; i++) {
				plugin.disableTab(tabTiddler[i]);
			}
		}
	},
    checkSyncStatus: function(tiddler) {
		if(tiddler) {
			var title = typeof(tiddler) === "string" ? tiddler : tiddler.title;
			var el = story.getTiddler(title) || false;
			if(el) {
				refreshElements(el);
			}
		}
	},
	isDisabledTab: function(tabTitle) {
		var match = new RegExp("(?:\\[\\[([^\\]]+)\\]\\])", "mg").exec(tabTitle);
		var tabIdentifier = match ? match[1] : tabTitle;
		return disabledTabs.contains(tabIdentifier);
	},
	getCSRFToken: window.getCSRFToken || null // this may not have been processed yet
};

currentSpace = plugin.currentSpace.name;

tweb.serverPrefix = tweb.host.split("/")[3] || ""; // XXX: assumes root handler
tweb.getStatus(function(status) {
	var url = plugin.getHost(status.server_host);
	tweb.status.server_host.url = url;
	config.messages.tsVersion = status.version;
});

if(window.location.protocol == "file:") {
	// enable AutoSave by default
	config.options.chkAutoSave = config.options.chkAutoSave === undefined ?
		true : config.options.chkAutoSave;
} else {
	// set global read-only mode based on membership heuristics
	var indicator = store.getTiddler("SiteTitle") || tiddler;
	readOnly = !(recipe.split("_").pop() == "private" ||
		tweb.hasPermission("write", indicator));
	// replace TiddlyWiki's ImportTiddlers due to cross-domain restrictions
	if(config.macros.fileImport) {
		$.extend(config.macros.importTiddlers, config.macros.fileImport);
	}
}

// hijack saveChanges to ensure SystemSettings is private by default
var _saveChanges = saveChanges;
saveChanges = function(onlyIfDirty, tiddlers) {
	if(tiddlers && tiddlers.length == 1 &&
			tiddlers[0] && tiddlers[0].title == "SystemSettings") {
		var fields = tiddlers[0].fields;
		delete fields["server.recipe"];
		fields["server.bag"] = plugin.getCurrentBag("private");
		fields["server.workspace"] = plugin.getCurrentWorkspace("private");
	}
	return _saveChanges.apply(this, arguments);
};

// ensure backstage is always initialized
// required to circumvent TiddlyWiki's read-only based handling
config.macros.backstageInit = {
	init: function() {
		showBackstage = true;
	}
};

// disable evaluated macro parameters for security reasons
config.evaluateMacroParameters = "none";
var _parseParams = String.prototype.parseParams;
String.prototype.parseParams = function(defaultName, defaultValue, allowEval,
		noNames, cascadeDefaults) {
	if(config.evaluateMacroParameters == "none") {
		arguments[2] = false;
	}
	return _parseParams.apply(this, arguments);
};

var _tabsMacro = config.macros.tabs.handler;
config.macros.tabs.handler = function(place, macroName, params) {
	var newParams = [params[0]]; // keep cookie name
	for(var i = 1; i < params.length; i += 3) {
		var tabTitle = params[i + 2];
		if(!plugin.isDisabledTab(tabTitle)){
			newParams = newParams.concat(params[i], params[i + 1], tabTitle);
		}
	}
	_tabsMacro.apply(this, [place, macroName, newParams]);
};

// disable ControlView for XHRs by default
$.ajaxSetup({
	beforeSend: function(xhr) {
		xhr.setRequestHeader("X-ControlView", "false");
	}
});
// TiddlyWeb adaptor currently still uses httpReq, which needs extra magic -- XXX: obsolete this!
var _httpReq = httpReq;
httpReq = function(type, url, callback, params, headers, data, contentType,
		username, password, allowCache) {
	headers = headers || {};
	headers["X-ControlView"] = "false";
	_httpReq.apply(this, arguments);
};

// register style sheet for backstage separately (important)
store.addNotification("StyleSheetBackstage", refreshStyles);

// option for default privacy setting
config.optionsDesc.chkPrivateMode = "Set your default privacy mode to private";
config.optionsSource.chkPrivateMode = "setting";
config.options.chkPrivateMode = config.options.chkPrivateMode || false;
saveSystemSetting("chkPrivateMode", true);
config.defaultCustomFields["server.workspace"] = plugin.
	getCurrentWorkspace(config.options.chkPrivateMode ? "private" : "public");

config.paramifiers.follow = {
	onstart: function(v) {
		if(!readOnly) {
			var bag = "%0_public".format(currentSpace);
			story.displayTiddler(null, v, DEFAULT_EDIT_TEMPLATE, null, null,
				"server.bag:%0 server.workspace:bags/%0".format(bag));
			story.setTiddlerTag(v, "follow", 1);
			story.focusTiddler(v, "text");
		}
	}
};

var fImport = config.macros.fileImport;
if(fImport) {
	fImport.uploadTo = "Upload to: ";
	var _createForm = config.macros.fileImport.createForm;
	config.macros.fileImport.createForm = function(place, wizard, iframeName) {
		var container = $("<div />").text(fImport.uploadTo).appendTo(place);
		var select = $('<select name="mode" />').appendTo(container)[0];
		$('<option value="private" selected>private</a>').appendTo(select);
		$('<option value="public">public</a>').appendTo(select);
		wizard.setValue("importmode", select);
		_createForm.apply(this, [place, wizard, iframeName]);
	};

	var _onGet = config.macros.importTiddlers.onGetTiddler;
	config.macros.importTiddlers.onGetTiddler = function(context, wizard) {
		var type = $(wizard.getValue("importmode")).val();
		var ws =  plugin.getCurrentWorkspace(type);
		wizard.setValue("workspace", ws);
		_onGet.apply(this, [context, wizard]);
	};
}

config.extensions.ServerSideSavingPlugin.reportSuccess = function(msg, tiddler) {
	plugin.checkSyncStatus(tiddler);
	msg = config.extensions.ServerSideSavingPlugin.locale[msg];
	var link = "/" + encodeURIComponent(tiddler.title);
	displayMessage(msg.format([tiddler.title]), link);
};


})(jQuery);
//}}}
<html manifest="manifest_offline.appcache">
<head>
	<title>Offline Viewer</title>
	<script type='text/javascript' src='/bags/common/tiddlers/backstage.js'></script>
	<link href="/bags/common/tiddlers/profile.css" type='text/css' rel='stylesheet' >
	<link href="/_offline.css" type='text/css' rel='stylesheet' >
</head>
<body>
	<div id="container">
		<h1 id="siteTitle"></h1>
		<div id="mainMenu"></div>
		<div id="header">
			<h1>
				<a href="#" id="title">Offline Tiddlers</a>
			</h1>
		</div>
		<div id="text-html" class="main section">Select a tiddler from the right hand side of the screen. This allows you to view
			your space without an internet connection. Kill your internet and try it out!</div>
	</div>
	<div id="sidebar">
		<a class='button' href="/takenote">take note</a>
		<ul></ul>
	</div>
	<script src="/bags/common/tiddlers/jquery.js" type="text/javascript" charset="utf-8"></script>
	<script src="/twikifier.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript" src="/_offline.js"></script>
</body>
</html>
/***
|''Name''|TiddlyWebAdaptor|
|''Description''|adaptor for interacting with TiddlyWeb|
|''Author:''|FND|
|''Contributors''|Chris Dent, Martin Budden|
|''Version''|1.4.10|
|''Status''|stable|
|''Source''|http://svn.tiddlywiki.org/Trunk/association/adaptors/TiddlyWebAdaptor.js|
|''CodeRepository''|http://svn.tiddlywiki.org/Trunk/association/|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.5|
|''Keywords''|serverSide TiddlyWeb|
!Notes
This plugin includes [[jQuery JSON|http://code.google.com/p/jquery-json/]].
!To Do
* createWorkspace
* document custom/optional context attributes (e.g. filters, query, revision) and tiddler fields (e.g. server.title, origin)
!Code
***/
//{{{
(function($) {

var adaptor = config.adaptors.tiddlyweb = function() {};

adaptor.prototype = new AdaptorBase();
adaptor.serverType = "tiddlyweb";
adaptor.serverLabel = "TiddlyWeb";
adaptor.mimeType = "application/json";

adaptor.parsingErrorMessage = "Error parsing result from server";
adaptor.noBagErrorMessage = "no bag specified for tiddler";
adaptor.locationIDErrorMessage = "no bag or recipe specified for tiddler"; // TODO: rename

// retrieve current status (requires TiddlyWeb status plugin)
adaptor.prototype.getStatus = function(context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/status";
	var uri = uriTemplate.format([context.host]);
	var req = httpReq("GET", uri, adaptor.getStatusCallback, context,
		null, null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getStatusCallback = function(status, context, responseText, uri, xhr) {
	context.status = responseText ? status : false;
	try {
		context.statusText = xhr.statusText;
	} catch(exc) { // offline (Firefox)
		context.status = false;
		context.statusText = null;
	}
	context.httpStatus = xhr.status;
	if(context.status) {
		context.serverStatus = $.evalJSON(responseText); // XXX: error handling!?
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// retrieve a list of workspaces
adaptor.prototype.getWorkspaceList = function(context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.workspaces = [];
	var uriTemplate = "%0/recipes"; // XXX: bags?
	var uri = uriTemplate.format([context.host]);
	var req = httpReq("GET", uri, adaptor.getWorkspaceListCallback,
		context, { accept: adaptor.mimeType }, null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getWorkspaceListCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		try {
			var workspaces = $.evalJSON(responseText);
		} catch(ex) {
			context.status = false; // XXX: correct?
			context.statusText = exceptionText(ex, adaptor.parsingErrorMessage);
			if(context.callback) {
				context.callback(context, context.userParams);
			}
			return;
		}
		context.workspaces = workspaces.map(function(itm) { return { title: itm }; });
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// retrieve a list of tiddlers
adaptor.prototype.getTiddlerList = function(context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/%1/%2/tiddlers%3";
	var params = context.filters ? "?" + context.filters : "";
	if(context.format) {
		params = context.format + params;
	}
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name), params]);
	var req = httpReq("GET", uri, adaptor.getTiddlerListCallback,
		context, merge({ accept: adaptor.mimeType }, context.headers), null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerListCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		context.tiddlers = [];
		try {
			var tiddlers = $.evalJSON(responseText); //# NB: not actual tiddler instances
		} catch(ex) {
			context.status = false; // XXX: correct?
			context.statusText = exceptionText(ex, adaptor.parsingErrorMessage);
			if(context.callback) {
				context.callback(context, context.userParams);
			}
			return;
		}
		for(var i = 0; i < tiddlers.length; i++) {
			var tiddler = adaptor.toTiddler(tiddlers[i], context.host);
			context.tiddlers.push(tiddler);
		}
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// perform global search
adaptor.prototype.getSearchResults = function(context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/search?q=%1%2";
	var filterString = context.filters ? ";" + context.filters : "";
	var uri = uriTemplate.format([context.host, context.query, filterString]); // XXX: parameters need escaping?
	var req = httpReq("GET", uri, adaptor.getSearchResultsCallback,
		context, { accept: adaptor.mimeType }, null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getSearchResultsCallback = function(status, context, responseText, uri, xhr) {
	adaptor.getTiddlerListCallback(status, context, responseText, uri, xhr); // XXX: use apply?
};

// retrieve a particular tiddler's revisions
adaptor.prototype.getTiddlerRevisionList = function(title, limit, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/%1/%2/tiddlers/%3/revisions";
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name), adaptor.normalizeTitle(title)]);
	var req = httpReq("GET", uri, adaptor.getTiddlerRevisionListCallback,
		context, merge({ accept: adaptor.mimeType }, context.headers), null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerRevisionListCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		context.revisions = [];
		try {
			var tiddlers = $.evalJSON(responseText); //# NB: not actual tiddler instances
		} catch(ex) {
			context.status = false; // XXX: correct?
			context.statusText = exceptionText(ex, adaptor.parsingErrorMessage);
			if(context.callback) {
				context.callback(context, context.userParams);
			}
			return;
		}
		for(var i = 0; i < tiddlers.length; i++) {
			var tiddler = adaptor.toTiddler(tiddlers[i], context.host);
			context.revisions.push(tiddler);
		}
		var sortField = "server.page.revision";
		context.revisions.sort(function(a, b) {
			return a.fields[sortField] < b.fields[sortField] ? 1 :
				(a.fields[sortField] == b.fields[sortField] ? 0 : -1);
		});
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// retrieve an individual tiddler revision -- XXX: breaks with standard arguments list -- XXX: convenience function; simply use getTiddler?
adaptor.prototype.getTiddlerRevision = function(title, revision, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.revision = revision;
	return this.getTiddler(title, context, userParams, callback);
};

// retrieve an individual tiddler
//# context is an object with members host and workspace
//# callback is passed the new context and userParams
adaptor.prototype.getTiddler = function(title, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = title;
	if(context.revision) {
		var uriTemplate = "%0/%1/%2/tiddlers/%3/revisions/%4";
	} else {
		uriTemplate = "%0/%1/%2/tiddlers/%3";
	}
	if(!context.tiddler) {
		context.tiddler = new Tiddler(title);
	}
	context.tiddler.fields["server.type"] = adaptor.serverType;
	context.tiddler.fields["server.host"] = AdaptorBase.minHostName(context.host);
	context.tiddler.fields["server.workspace"] = context.workspace;
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name), adaptor.normalizeTitle(title),
		context.revision]);
	var req = httpReq("GET", uri, adaptor.getTiddlerCallback, context,
		merge({ accept: adaptor.mimeType }, context.headers), null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		try {
			var tid = $.evalJSON(responseText);
		} catch(ex) {
			context.status = false;
			context.statusText = exceptionText(ex, adaptor.parsingErrorMessage);
			if(context.callback) {
				context.callback(context, context.userParams);
			}
			return;
		}
		var tiddler = adaptor.toTiddler(tid, context.host);
		tiddler.title = context.tiddler.title;
		tiddler.fields["server.etag"] = xhr.getResponseHeader("Etag");
		// normally we'd assign context.tiddler = tiddler here - but we can't do
		// that because of IE, which triggers getTiddler in putTiddlerCallback,
		// and since ServerSideSavingPlugin foolishly relies on persistent
		// object references, we need to merge the data into the existing object
		$.extend(context.tiddler, tiddler);
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// retrieve tiddler chronicle (all revisions)
adaptor.prototype.getTiddlerChronicle = function(title, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = title;
	var uriTemplate = "%0/%1/%2/tiddlers/%3/revisions?fat=1";
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name), adaptor.normalizeTitle(title)]);
	var req = httpReq("GET", uri, adaptor.getTiddlerChronicleCallback,
		context, { accept: adaptor.mimeType }, null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerChronicleCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		context.responseText = responseText;
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// store an individual tiddler
adaptor.prototype.putTiddler = function(tiddler, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = tiddler.title;
	context.tiddler = tiddler;
	context.host = context.host || this.fullHostName(tiddler.fields["server.host"]);
	var uriTemplate = "%0/%1/%2/tiddlers/%3";
	try {
		context.workspace = context.workspace || tiddler.fields["server.workspace"];
		var workspace = adaptor.resolveWorkspace(context.workspace);
	} catch(ex) {
		return adaptor.locationIDErrorMessage;
	}
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name),
		adaptor.normalizeTitle(tiddler.title)]);
	var etag = adaptor.generateETag(workspace, tiddler);
	var headers = etag ? { "If-Match": etag } : null;
	var payload = {
		type: tiddler.fields["server.content-type"] || null,
		text: tiddler.text,
		tags: tiddler.tags,
		fields: $.extend({}, tiddler.fields)
	};
	delete payload.fields.changecount;
	$.each(payload.fields, function(key, value) {
		if(key.indexOf("server.") == 0) {
			delete payload.fields[key];
		}
	});
	payload = $.toJSON(payload);
	var req = httpReq("PUT", uri, adaptor.putTiddlerCallback,
		context, headers, payload, adaptor.mimeType, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.putTiddlerCallback = function(status, context, responseText, uri, xhr) {
	context.status = [204, 1223].contains(xhr.status);
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(context.status) {
		var loc = xhr.getResponseHeader("Location");
		var etag = xhr.getResponseHeader("Etag");
		if(loc && etag) {
			var bag = loc.split("/bags/").pop().split("/")[0];
			context.tiddler.fields["server.bag"] = bag;
			context.tiddler.fields["server.workspace"] = "bags/" + bag;
			var rev = etag.split("/").pop().split(/;|:/)[0];
			context.tiddler.fields["server.page.revision"] = rev;
			context.tiddler.fields["server.etag"] = etag;
			if(context.callback) {
				context.callback(context, context.userParams);
			}
		} else { // IE
			context.adaptor.getTiddler(context.tiddler.title, context,
				context.userParams, context.callback);
		}
	} else if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// store a tiddler chronicle
adaptor.prototype.putTiddlerChronicle = function(revisions, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = revisions[0].title;
	var headers = null;
	var uriTemplate = "%0/%1/%2/tiddlers/%3/revisions";
	var host = context.host || this.fullHostName(tiddler.fields["server.host"]);
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name),
		adaptor.normalizeTitle(context.title)]);
	if(workspace.type == "bag") { // generate ETag
		var etag = [adaptor.normalizeTitle(workspace.name),
			adaptor.normalizeTitle(context.title), 0].join("/"); //# zero-revision prevents overwriting existing contents
		headers = { "If-Match": '"' + etag + '"' };
	}
	var payload = $.toJSON(revisions);
	var req = httpReq("POST", uri, adaptor.putTiddlerChronicleCallback,
		context, headers, payload, adaptor.mimeType, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.putTiddlerChronicleCallback = function(status, context, responseText, uri, xhr) {
	context.status = [204, 1223].contains(xhr.status);
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// store a collection of tiddlers (import TiddlyWiki HTML store)
adaptor.prototype.putTiddlerStore = function(store, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/%1/%2/tiddlers";
	var host = context.host;
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name)]);
	var req = httpReq("POST", uri, adaptor.putTiddlerStoreCallback,
		context, null, store, "text/x-tiddlywiki", null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.putTiddlerStoreCallback = function(status, context, responseText, uri, xhr) {
	context.status = [204, 1223].contains(xhr.status);
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// rename an individual tiddler or move it to a different workspace -- TODO: make {from|to}.title optional
//# from and to are objects with members title and workspace (bag; optional),
//# representing source and target tiddler, respectively
adaptor.prototype.moveTiddler = function(from, to, context, userParams, callback) { // XXX: rename parameters (old/new)?
	var self = this;
	var newTiddler = store.getTiddler(from.title) || store.getTiddler(to.title); //# local rename might already have occurred
	var oldTiddler = $.extend(true, {}, newTiddler); //# required for eventual deletion
	oldTiddler.title = from.title; //# required for original tiddler's ETag
	var _getTiddlerChronicle = function(title, context, userParams, callback) {
		return self.getTiddlerChronicle(title, context, userParams, callback);
	};
	var _putTiddlerChronicle = function(context, userParams) {
		if(!context.status) {
			return callback(context, userParams);
		}
		var revisions = $.evalJSON(context.responseText); // XXX: error handling?
		// change current title while retaining previous location
		for(var i = 0; i < revisions.length; i++) {
			delete revisions[i].revision;
			if(!revisions[i].fields.origin) { // NB: origin = "<workspace>/<title>"
				revisions[i].fields.origin = ["bags", revisions[i].bag, revisions[i].title].join("/");
			}
			revisions[i].title = to.title;
		}
		// add new revision
		var rev = $.extend({}, revisions[0]);
		$.each(newTiddler, function(i, item) {
			if(!$.isFunction(item)) {
				rev[i] = item;
			}
		});
		rev.title = to.title;
		rev.created = rev.created.convertToYYYYMMDDHHMM();
		rev.modified = new Date().convertToYYYYMMDDHHMM();
		delete rev.fields.changecount;
		revisions.unshift(rev);
		if(to.workspace) {
			context.workspace = to.workspace;
		} else if(context.workspace.substring(0, 4) != "bags") { // NB: target workspace must be a bag
			context.workspace = "bags/" + rev.bag;
		}
		var subCallback = function(context, userParams) {
			if(!context.status) {
				return callback(context, userParams);
			}
			context.adaptor.getTiddler(newTiddler.title, context, userParams, _deleteTiddler);
		};
		return self.putTiddlerChronicle(revisions, context, context.userParams, subCallback);
	};
	var _deleteTiddler = function(context, userParams) {
		if(!context.status) {
			return callback(context, userParams);
		}
		$.extend(true, newTiddler, context.tiddler);
		context.callback = null;
		return self.deleteTiddler(oldTiddler, context, context.userParams, callback);
	};
	callback = callback || function() {};
	context = this.setContext(context, userParams);
	context.host = context.host || oldTiddler.fields["server.host"];
	context.workspace = from.workspace || oldTiddler.fields["server.workspace"];
	return _getTiddlerChronicle(from.title, context, userParams, _putTiddlerChronicle);
};

// delete an individual tiddler
adaptor.prototype.deleteTiddler = function(tiddler, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = tiddler.title; // XXX: not required!?
	var uriTemplate = "%0/bags/%1/tiddlers/%2";
	var host = context.host || this.fullHostName(tiddler.fields["server.host"]);
	var bag = tiddler.fields["server.bag"];
	if(!bag) {
		return adaptor.noBagErrorMessage;
	}
	var uri = uriTemplate.format([host, adaptor.normalizeTitle(bag),
		adaptor.normalizeTitle(tiddler.title)]);
	var etag = adaptor.generateETag({ type: "bag", name: bag }, tiddler);
	var headers = etag ? { "If-Match": etag } : null;
	var req = httpReq("DELETE", uri, adaptor.deleteTiddlerCallback, context, headers,
		null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.deleteTiddlerCallback = function(status, context, responseText, uri, xhr) {
	context.status = [204, 1223].contains(xhr.status);
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// compare two revisions of a tiddler (requires TiddlyWeb differ plugin)
//# if context.rev1 is not specified, the latest revision will be used for comparison
//# if context.rev2 is not specified, the local revision will be sent for comparison
//# context.format is a string as determined by the TiddlyWeb differ plugin
adaptor.prototype.getTiddlerDiff = function(title, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = title;

	var tiddler = store.getTiddler(title);
	try {
		var workspace = adaptor.resolveWorkspace(tiddler.fields["server.workspace"]);
	} catch(ex) {
		return adaptor.locationIDErrorMessage;
	}
	var tiddlerRef = [workspace.type + "s", workspace.name, tiddler.title].join("/");

	var rev1 = context.rev1 ? [tiddlerRef, context.rev1].join("/") : tiddlerRef;
	var rev2 = context.rev2 ? [tiddlerRef, context.rev2].join("/") : null;

	var uriTemplate = "%0/diff?rev1=%1";
	if(rev2) {
		uriTemplate += "&rev2=%2";
	}
	if(context.format) {
		uriTemplate += "&format=%3";
	}
	var host = context.host || this.fullHostName(tiddler.fields["server.host"]);
	var uri = uriTemplate.format([host, adaptor.normalizeTitle(rev1),
		adaptor.normalizeTitle(rev2), context.format]);

	if(rev2) {
		var req = httpReq("GET", uri, adaptor.getTiddlerDiffCallback, context, null,
			null, null, null, null, true);
	} else {
		var payload = {
			title: tiddler.title,
			text: tiddler.text,
			modifier: tiddler.modifier,
			tags: tiddler.tags,
			fields: $.extend({}, tiddler.fields)
		}; // XXX: missing attributes!?
		payload = $.toJSON(payload);
		req = httpReq("POST", uri, adaptor.getTiddlerDiffCallback, context,
			null, payload, adaptor.mimeType, null, null, true);
	}
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerDiffCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	context.uri = uri;
	if(status) {
		context.diff = responseText;
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// generate tiddler information
adaptor.prototype.generateTiddlerInfo = function(tiddler) {
	var info = {};
	var uriTemplate = "%0/%1/%2/tiddlers/%3";
	var host = this.host || tiddler.fields["server.host"]; // XXX: this.host obsolete?
	host = this.fullHostName(host);
	var workspace = adaptor.resolveWorkspace(tiddler.fields["server.workspace"]);
	info.uri = uriTemplate.format([host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name),
		adaptor.normalizeTitle(tiddler.title)]);
	return info;
};

// create Tiddler instance from TiddlyWeb tiddler JSON
adaptor.toTiddler = function(json, host) {
	var created = Date.convertFromYYYYMMDDHHMM(json.created);
	var modified = Date.convertFromYYYYMMDDHHMM(json.modified);
	var fields = json.fields;
	fields["server.type"] = adaptor.serverType;
	fields["server.host"] = AdaptorBase.minHostName(host);
	fields["server.bag"] = json.bag;
	fields["server.title"] = json.title;
	if(json.recipe) {
		fields["server.recipe"] = json.recipe;
	}
	if(json.type && json.type != "None") {
		fields["server.content-type"] = json.type;
	}
	fields["server.permissions"] = json.permissions.join(", ");
	fields["server.page.revision"] = json.revision;
	fields["server.workspace"] = "bags/" + json.bag;
	var tiddler = new Tiddler(json.title);
	tiddler.assign(tiddler.title, json.text, json.modifier, modified, json.tags,
		created, json.fields, json.creator);
	return tiddler;
};

adaptor.resolveWorkspace = function(workspace) {
	var components = workspace.split("/");
	return {
		type: components[0] == "bags" ? "bag" : "recipe",
		name: components[1] || components[0]
	};
};

adaptor.generateETag = function(workspace, tiddler) {
	var revision = tiddler.fields["server.page.revision"];
	var etag = revision == "false" ? null : tiddler.fields["server.etag"];
	if(!etag && workspace.type == "bag") {
		if(typeof revision == "undefined") {
			revision = "0";
		} else if(revision == "false") {
			return null;
		}
		etag = [adaptor.normalizeTitle(workspace.name),
			adaptor.normalizeTitle(tiddler.title), revision].join("/");
		etag = '"' + etag + '"';
	}
	return etag;
};

adaptor.normalizeTitle = function(title) {
	return encodeURIComponent(title);
};

})(jQuery);


/*
 * jQuery JSON Plugin
 * version: 1.3
 * source: http://code.google.com/p/jquery-json/
 * license: MIT (http://www.opensource.org/licenses/mit-license.php)
 */
(function($){function toIntegersAtLease(n)
{return n<10?'0'+n:n;}
Date.prototype.toJSON=function(date)
{return this.getUTCFullYear()+'-'+
toIntegersAtLease(this.getUTCMonth())+'-'+
toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(string)
{if(escapeable.test(string))
{return'"'+string.replace(escapeable,function(a)
{var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};$.toJSON=function(o,compact)
{var type=typeof(o);if(type=="undefined")
return"undefined";else if(type=="number"||type=="boolean")
return o+"";else if(o===null)
return"null";if(type=="string")
{return $.quoteString(o);}
if(type=="object"&&typeof o.toJSON=="function")
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
if(compact)
return"["+ret.join(",")+"]";else
return"["+ret.join(", ")+"]";}
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
if(compact)
ret.push(name+":"+val);else
ret.push(name+": "+val);}
return"{"+ret.join(", ")+"}";};$.compactJSON=function(o)
{return $.toJSON(o,true);};$.evalJSON=function(src)
{return eval("("+src+")");};$.secureEvalJSON=function(src)
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};})(jQuery);
//}}}
/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBxdWFsaXR5ID0gOTIK/9sAQwADAgICAgIDAgICAwMDAwQGBAQEBAQIBgYFBgkICgoJCAkJCgwPDAoLDgsJCQ0RDQ4PEBAREAoMEhMSEBMPEBAQ/9sAQwEDAwMEAwQIBAQIEAsJCxAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ/8IAEQgBLAEsAwEiAAIRAQMRAf/EAB0AAAEFAQEBAQAAAAAAAAAAAAcDBAUGCAIBAAn/xAAZAQADAQEBAAAAAAAAAAAAAAABAgMABAX/2gAMAwEAAhADEAAAAdBeUpPz+y+fUzpWuPtN7xuXtQVxtnVTV2ta1XfDWHuHcGb/AOY+ur7ximNJcsOlL71h0we/MvmD31j8M+8Y8KXqTFFayKUW0xnOK4gdZUKzEkXlGisSJ5HtKbve0up0U9562V7SUBcKJONl37J8C5VowItz6xoeK4rq5tVrhGHI0y7fM5UGs1ARtUKF6zS4B179lkhTcxpxEzz0Q5XTnVs1ft9SKayDEhnBzsKQ0ZO2LJZG67d1f9c+o/qn3WynXagb50mP2W1Zzscd081GvETTbxsBKjLdMjIS6wZEUEgAM0Hd1A4XJcC5m0iknRcdWAQudWGkybDWT3Amvua96RXSh0xjCWjiYqHmogrFs3LJ0tLZ02Oke+Vpt0p6vj0rznVxJDohDbr4zp1PSsbUm00q0ZaKOXcReJAMISr6koi/TOGGGqPMr3llO1hgyRJ4CGssSCxLoXYoR0pZKFZTYXMXm+NyvHSDDm6YyJlYwpCsn8e6Wtm8anSL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wOW8F+jIWrhxi/rC0/5YxRPzjNoJ5lXeKP0pAkO5gef+z4wOv1f6svOH/nrEA4/P9GJv+ReYF3/AIPjCrgk7fowEiJeR/Wc5lbtf6xIX9//AFhlG75/qy/UfD/Rg2iTAaz8lf6xtT8WUoi/Df8AGXhXtR/jJogvZf8ArFmn/wBeYNwnu+CF/wCL4x0f8j6yScf8dYoU2+4Kf73gT+wxXkvpZHt/t6xig+b3hYCh6xLSn55LgPyyhoX5/wCsYRL88Bv+T/rKX30v8YroflZA1OsjJvIPWAeZDwyHmQ4mQ8yHmQyHmQ8yGQyHmTIeZDzIZDIeZMh5kPMh5kPMh5kPMh5kPMh5kPMh5kPMh5kPMh5n/9k=
// Substitute date components into a string
Date.prototype.formatString = function(template)
{
	var t = template.replace(/0hh12/g,String.zeroPad(this.getHours12(),2));
	t = t.replace(/hh12/g,this.getHours12());
	t = t.replace(/0hh/g,String.zeroPad(this.getHours(),2));
	t = t.replace(/hh/g,this.getHours());
	t = t.replace(/mmm/g,config.messages.dates.shortMonths[this.getMonth()]);
	t = t.replace(/0mm/g,String.zeroPad(this.getMinutes(),2));
	t = t.replace(/mm/g,this.getMinutes());
	t = t.replace(/0ss/g,String.zeroPad(this.getSeconds(),2));
	t = t.replace(/ss/g,this.getSeconds());
	t = t.replace(/[ap]m/g,this.getAmPm().toLowerCase());
	t = t.replace(/[AP]M/g,this.getAmPm().toUpperCase());
	t = t.replace(/wYYYY/g,this.getYearForWeekNo());
	t = t.replace(/wYY/g,String.zeroPad(this.getYearForWeekNo()-2000,2));
	t = t.replace(/YYYY/g,this.getFullYear());
	t = t.replace(/YY/g,String.zeroPad(this.getFullYear()-2000,2));
	t = t.replace(/MMM/g,config.messages.dates.months[this.getMonth()]);
	t = t.replace(/0MM/g,String.zeroPad(this.getMonth()+1,2));
	t = t.replace(/MM/g,this.getMonth()+1);
	t = t.replace(/0WW/g,String.zeroPad(this.getWeek(),2));
	t = t.replace(/WW/g,this.getWeek());
	t = t.replace(/DDD/g,config.messages.dates.days[this.getDay()]);
	t = t.replace(/ddd/g,config.messages.dates.shortDays[this.getDay()]);
	t = t.replace(/0DD/g,String.zeroPad(this.getDate(),2));
	t = t.replace(/DDth/g,this.getDate()+this.daySuffix());
	t = t.replace(/DD/g,this.getDate());
	var tz = this.getTimezoneOffset();
	var atz = Math.abs(tz);
	t = t.replace(/TZD/g,(tz < 0 ? '+' : '-') + String.zeroPad(Math.floor(atz / 60),2) + ':' + String.zeroPad(atz % 60,2));
	t = t.replace(/\\/g,"");
	return t;
};

Date.prototype.getWeek = function()
{
	var dt = new Date(this.getTime());
	var d = dt.getDay();
	if(d==0) d=7;// JavaScript Sun=0, ISO Sun=7
	dt.setTime(dt.getTime()+(4-d)*86400000);// shift day to Thurs of same week to calculate weekNo
	var n = Math.floor((dt.getTime()-new Date(dt.getFullYear(),0,1)+3600000)/86400000);
	return Math.floor(n/7)+1;
};

Date.prototype.getYearForWeekNo = function()
{
	var dt = new Date(this.getTime());
	var d = dt.getDay();
	if(d==0) d=7;// JavaScript Sun=0, ISO Sun=7
	dt.setTime(dt.getTime()+(4-d)*86400000);// shift day to Thurs of same week
	return dt.getFullYear();
};

Date.prototype.getHours12 = function()
{
	var h = this.getHours();
	return h > 12 ? h-12 : ( h > 0 ? h : 12 );
};

Date.prototype.getAmPm = function()
{
	return this.getHours() >= 12 ? config.messages.dates.pm : config.messages.dates.am;
};

Date.prototype.daySuffix = function()
{
	return config.messages.dates.daySuffixes[this.getDate()-1];
};

// Convert a date to local YYYYMMDDHHMM string format
Date.prototype.convertToLocalYYYYMMDDHHMM = function()
{
	return this.getFullYear() + String.zeroPad(this.getMonth()+1,2) + String.zeroPad(this.getDate(),2) + String.zeroPad(this.getHours(),2) + String.zeroPad(this.getMinutes(),2);
};

// Convert a date to UTC YYYYMMDDHHMM string format
Date.prototype.convertToYYYYMMDDHHMM = function()
{
	return this.getUTCFullYear() + String.zeroPad(this.getUTCMonth()+1,2) + String.zeroPad(this.getUTCDate(),2) + String.zeroPad(this.getUTCHours(),2) + String.zeroPad(this.getUTCMinutes(),2);
};

// Convert a date to UTC YYYYMMDD.HHMMSSMMM string format
Date.prototype.convertToYYYYMMDDHHMMSSMMM = function()
{
	return this.getUTCFullYear() + String.zeroPad(this.getUTCMonth()+1,2) + String.zeroPad(this.getUTCDate(),2) + "." + String.zeroPad(this.getUTCHours(),2) + String.zeroPad(this.getUTCMinutes(),2) + String.zeroPad(this.getUTCSeconds(),2) + String.zeroPad(this.getUTCMilliseconds(),3) +"0";
};

// Static method to create a date from a UTC YYYYMMDDHHMM format string
Date.convertFromYYYYMMDDHHMM = function(d)
{
	d = d?d.replace(/[^0-9]/g, ""):"";
	return Date.convertFromYYYYMMDDHHMMSSMMM(d.substr(0,12));
};

// Static method to create a date from a UTC YYYYMMDDHHMMSS format string
Date.convertFromYYYYMMDDHHMMSS = function(d)
{
	d = d?d.replace(/[^0-9]/g, ""):"";
	return Date.convertFromYYYYMMDDHHMMSSMMM(d.substr(0,14));
};

// Static method to create a date from a UTC YYYYMMDDHHMMSSMMM format string
Date.convertFromYYYYMMDDHHMMSSMMM = function(d)
{
	d = d ? d.replace(/[^0-9]/g, "") : "";
	return new Date(Date.UTC(parseInt(d.substr(0,4),10),
			parseInt(d.substr(4,2),10)-1,
			parseInt(d.substr(6,2),10),
			parseInt(d.substr(8,2)||"00",10),
			parseInt(d.substr(10,2)||"00",10),
			parseInt(d.substr(12,2)||"00",10),
			parseInt(d.substr(14,3)||"000",10)));
};
/*{{{*/
.tiddler .originButton div {
	display: inline-block;
}

.tiddler .spaceSiteIcon .siteIcon {
	_display: inline; /* IE doesn't like inline-block */
}

.tiddler .originButton {
	display: block;
}

.selected .tagging,
.selected .tagging:hover {
	border: none;
	background: none;
}

.tagging {
	float: none;
	background: none;
	border: none;
}

.tagging li.listTitle {
	margin-left: 0px;
}
.tagging li {
	margin: 0 8px;
}

.tagging .tiddlyLink {
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	-o-border-radius: 3px;
	border-radius: 3px;
	padding: 1px 2px;
	line-height: 1.2em;
}

/* for following */
#popup .siteIcon {
	float: left;
	height: 25px;
}

.content {
	width: 100%; /* IE */
	font-size: 0.9em;
}

.editorHeading {
	height: 48px;
}

.heading {
	left: 0;
	margin-bottom: 40px;
	position: relative;
	top: 32px;
}

.followButton a {
	display: block;
	margin-top: -20px;
}

.tiddler .followPlaceHolder {
	display: block;
	position: absolute;
	top: 16px;
	right: 64px;
	_right: 138px; // add width of modifierIcon
}

.tiddler .followButton {
	position: relative;
	height: 24px;
	text-align: left;
	color: #fff;
	background: [[ColorPalette::PrimaryMid]];
	padding: 10px 0px 0px 10px;
	width: 38px;
	margin: -16px -8px 24px 0;
}

/* creates the larger triangle */
.followButton:before {
	content: "\00a0";
	display: block; /* reduce the damage in FF3.0 */
	position: relative;
	bottom: -20px;
	right: 0;
	width: 0;
	height: 0;
	border-width: 0 0 20px 20px;
	border-style: solid;
	border-color: transparent [[ColorPalette::PrimaryMid]];
}

.toolbar svg {
	height: 16px;
	width: 16px;
}

.toolbar svg .glyph {
	fill: #ccc;
}

.toolbar a:hover .glyph {
	fill: black;
}

.toolbar a:active .glyph {
	fill: [[ColorPalette::Background]];
}

.originButton,
.followPlaceHolder,
.tiddler .subtitle {
	cursor: pointer;
}

.editSpaceSiteIcon .originButton {
	cursor: auto;
}

.tiddler .subtitle:hover {
	font-weight: bold;
	background: none;
}

.originButton img,
.originButton svg {
	margin-left: 0px;
}

.modifierIcon {
	position: absolute;
	width: 74px;
	top: 0px;
	right: 0px;
	_right: 74px; /* in IE6 positioning works incorrectly so use -width instead */
	text-align: right;
}

.modifierIcon img,
.modifierIcon svg {
	margin-right: 8px;
}

.tiddler .viewer {
	padding-bottom: 16px;
	margin: 0 0 0 56px;
	line-height: 1.4em;
}

.viewer pre {
	margin-left: 0;
}

.siteIcon .label {
	color: [[ColorPalette::TertiaryDark]];
}

.tiddler .spaceSiteIcon {
	float: left;
	margin-right: 0;
	margin-top: 0;
	position: relative;
	display: block;
}

.tiddler .titleBar {
	display: block;
	margin-right: 136px;
	margin-left: 56px;
}

.followButton a {
	color: [[ColorPalette::Background]];
}

.tiddler {
	position: relative;
	padding: 0;
	margin-bottom: 3em;
	border-top: 3px solid [[ColorPalette::PrimaryMid]];
	background: #fff;
}

.tiddler .editor {
	padding: 0px 8px;
}

.tiddler .heading .title {
	position: relative;
	display: block;
	word-wrap: break-word;
	font-size: 32px;
	line-height: 32px;
}
.tiddler .heading .editor.title {
	font-size: 1.7em;
	line-height: normal;
}

.tiddler .headingClear {
	clear: both;
}

.tiddler .subtitle {
	font-style: italic;
	font-size: 0.9em;
	color: #a6a59e;
	margin-top: 0;
}

.toolbar {
	position: absolute;
	padding: 0;
	top: 8px;
	right: -8px;
}

.toolbar .moreCommand.highlight {
	background: none;
}

.tiddler .toolbar .button {
	border: none;
	display: inline;
	padding: 0px;
	margin-right: 16px;
}

.tiddler .toolbar a:hover {
	background: none;
}

.tiddler .tagged .listTitle {
	display: none;
}

.revButton {
	float: right;
}

/*! EditTemplate specific*/
.tiddler .privacySettings {
	text-align: center;
}
.tiddler .privacySettings .originButton {
	display: inline;
}

.editSpaceSiteIcon, .privacyEdit {
	float: left;
}

.editSpaceSiteIcon svg,
.editSpaceSiteIcon img,
.editSpaceSiteIcon .roundelLabel {
	float: left;
}

.tagTitle {
	position: absolute;
	text-align: center;
	width: 48px;
	top: 0px;
	left: -56px;
}

.editSpaceSiteIcon .originButton img,
.editSpaceSiteIcon .originButton svg {
	height: 16px;
	margin-left: 24px;
	margin-right: 32px;
	width: 16px;
}

.tagAnnotation {
	margin-top: 8px;
	padding-bottom: 8px;
}
.annotationsBox {
	margin-top: 8px;
}

.editorFooter {
	position: relative;
	padding: 0;
	margin-top: 16px;
	margin-left: 64px;
}

.tiddler .editorFooter .editor {
	padding-left: 0px;
}

.heading .editor input {
	width: 100%;
	font-size: 1.5em;
}

.spaceSiteIcon .externalImage .image a:hover,
.modifierIcon .externalImage .image a:hover {
	background: none;
}

div.toolbar {
	visibility:hidden;
	right:-16px;
}

.selected div.toolbar {
	visibility: visible;
}

.followButton a:hover {
	background: [[ColorPalette::PrimaryMid]];
	text-decoration: underline;
}

a.image:hover {
	background: transparent;
}

@media all and (max-device-width: 480px) {
	div.toolbar {
		visibility:visible;
	}
}
@media only screen and (device-width: 768px) {
	div.toolbar {
		visibility:visible;
	}
}
@media all and (max-width: 960px) {
	.tiddler .titleBar {
		margin-left: 36px;
		margin-right: 80px;
	}

	.tiddler .heading {
		margin-bottom: 48px;
	}

	.tiddler .heading .title {
		font-size: 32px;
		line-height: 32px;
	}

	.tiddler .modifierIcon img,
	.tiddler .modifierIcon svg,
	.tiddler .spaceSiteIcon .originButton img,
	.originButton svg {
		width: 32px;
		height: 32px;
		margin-left: 0px;
		margin-right: 0px;
	}

	.tiddler .followPlaceHolder {
		right: 48px;
	}

	.tiddler .followButton {
		width: 24px;
	}

	.tiddler .viewer {
		margin: 0px 0px 0px 36px;
		padding-top: 0;
	}

	br {
		line-height: 0.5em;
	}
}
/*}}}*/
ColorPalette
StyleSheet
SiteSubtitle
GettingStarted
SiteTitle
MainMenu
SiteIcon
DefaultTiddlers
ViewTemplate
PageTemplate
SideBarOptions
EditTemplate
SiteInfo
SideBarTabs
ToolbarCommands
<html>
<head>
  <title>@s</title>
  <link href="/bags/common/tiddlers/profile.css" type='text/css' rel='stylesheet' >
  <link href="/jquery-ui.css" type='text/css' rel='stylesheet' >
</style>
	<script type="text/javascript" src="/bags/common/tiddlers/backstage.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<h1>@s</h1>
</div>
<h2>Tiddlers that are @ing this space</h2>
Tiddlers that are tagged with <span class='magicTag'>@<spacename></span> are listed below.
<ul id="ats">
</ul>
</div>
<script type='text/javascript' src='/bags/common/tiddlers/jquery.js'></script>
<script type='text/javascript' src='http://htmljs.tiddlyspace.com/htmljs-prettydates'></script>
<script type='text/javascript' src='/bags/common/tiddlers/jquery-json.js'></script>
<script type='text/javascript' src='/bags/tiddlyspace/tiddlers/chrjs'></script>
<script type="text/javascript">
$.ajaxSetup({
	beforeSend: function(xhr) {
		xhr.setRequestHeader("X-ControlView", "false");
	}
});
var host = "http://tiddlyspace.com";
// TODO: what about running from homepage?
var magicTag = "@" + document.location.hostname.split(".")[0];
$(".magicTag").text(magicTag);
var search = new tiddlyweb.Search("tag:" + magicTag, "/");
var list = $("#ats");
search.get(function(tiddlers) {
	tiddlers.sort(function(a, b) {
		return a.modified < b.modified ? 1 : -1;
	});
	for(var i = 0; i < tiddlers.length; i++) {
		var tiddler = tiddlers[i];
		var item = $("<li />").appendTo(list);
		$("<a />").attr("href",
			host + "/bags/" + encodeURIComponent(tiddler.bag.name) + "/tiddlers/" + encodeURIComponent(tiddler.title)).text(tiddler.title).appendTo(item);
		$("<span />").text(" " + simpleDate(tiddler.modified)).appendTo(item);
		$("<span />").text(" from ").appendTo(item);
		// TODO: hacky
		$("<a />").attr("href", "http://" + tiddler.modifier + ".tiddlyspace.com").text(tiddler.modifier).appendTo(item);
	}
	if(tiddlers.length === 0) {
		$("<li />").text("no tiddlers tagged " + magicTag).appendTo(list);
	}
}, function() {
	$("<li />").text("Unable to retrieve tiddlers tagged " + magicTag).appendTo(list);
});
</script>
</body>
</html>
<!--
{{{
-->
<span class='yourSearchTitle' macro='foundTiddler title'/></span>&nbsp;:
<span class='yourSearchTags' macro='foundTiddler field tags 50'/></span>
<span macro="yourSearch if previewText"><div class='yourSearchText' macro='foundTiddler field text 250'/></div></span>
<!--
}}}
-->
The title and subtitle of your space are visible to visitors and are also displayed in your browser's tabs. Click on the SiteTitle and SiteSubtitle tiddler links below to make changes.
* [[SiteTitle]]
* [[SiteSubtitle]]
<<image "http://jon.tiddlyspace.com/screenshot_familytree" width:400>>

Familytree is a Family Tree vertical for [[TiddlyWiki|http://www.tiddlywiki.org]] created by Jon Robson.
It was first released October 2009. Read the corresponding blog post [[here|http://www.jonrobson.me.uk/posts/Finally a Family Tree Vertical]]

It has been modified to work with TiddlySpace, to get started with your own space simply include the familytree space (see [[1. GettingStarted]]) and begin your tree!

!!Example
See [[Jon Robson's Family Tree|@@robsontree]]
!!Tagging
Tagging a tiddler with rootTree will make them appear on startup.
!!Feedback
I would love to hear your feedback - please post it [[here|http://groups.google.com/group/TiddlyWiki/topics]] or contact me through @jon.
!!Dev
This provides the [[FamilyTreeUtilsPlugin]] and makes use of the @nicetagging @tiddlytagmindmap and @aet spaces to create a family tree vertical.
<!DOCTYPE HTML>
<html>
<body style="display:none">
topics: <ul id="topics"></ul>
<button id='addtopic'>add topic</button>
stream:
<ul id="stream"></ul>
<script type='text/javascript' src='/bags/common/tiddlers/jquery.js'></script>
<script type='text/javascript' src='/bags/tiddlyspace/tiddlers/chrjs'></script>
<script src="/twikifier.js" type="text/javascript" charset="utf-8"></script>
<script type='text/javascript'>
	$.ajaxSetup({
		beforeSend: function(xhr) {
			xhr.setRequestHeader("X-ControlView", "false");
		}
	});
	function renderTopic(topic) {
		var item = $("<li />").appendTo("#topics");
		$("<button class='show' />").text(topic).appendTo(item);
		$("<button class='delete'>x</button>").appendTo(item);
		return item[0];
	}
	var host =  '/';
	var space = "jon";
	var active_topics = [];
	var current_topic, offset;
	function renderTopics() {
		var topics = active_topics;
		$("#topics").empty();
		for(var i = 0; i < topics.length; i++) {
			var topic = topics[i];
			if(topic) {
				renderTopic(topic);
			}
		}
		$("body").show();
	}
	// Array Remove - By John Resig (MIT Licensed)
	Array.prototype.remove = function(from, to) {
		var rest = this.slice((to || from) + 1 || this.length);
		this.length = from < 0 ? this.length + from : from;
		return this.push.apply(this, rest);
	};

	var topicList = new tiddlyweb.Tiddler("Topics", new tiddlyweb.Bag(space + "_public", host));
	topicList.get(function(tid) {
			active_topics = tid.text.split("\n");
			renderTopics(active_topics);
			$("#topics .show:first").trigger("click");
		},
		function() {
			active_topics = ["tiddlyspace"];
			renderTopics(active_topics)
		}
	);
	$("#addtopic").click(function(ev) {
		var text = prompt("What topic would you like to watch?");
		if(active_topics.indexOf(text) === -1) {
			active_topics.push(text);
		}
		var el = renderTopic(text);
		topicList.text = active_topics.join("\n");
		topicList.put(function() {
			$("button.show", el).trigger("click");
		}, function() {
			alert("eek!")
		});
	});
	$("#topics .delete").live("click",function(ev) {
		var topic = $(".show", this.parentNode).text();
		active_topics.remove(active_topics.indexOf(topic));
		renderTopics();
		topicList.text = active_topics.join("\n");
		topicList.put(function() {}, function() {
			alert("eek!")
		});
	});
	w = createWikifier(window, jQuery, { host: host, container: "recipes/" + space + "_public" });
	$("#topics .show").live("click",function(ev) {
		var tag = $(this).text();
		current_topic = tag;
		offset = 0;
		$("#stream").empty();
		var search = new tiddlyweb.Search('tag:"' + tag + '" &fat=y', host);
		search.get(function(tiddlers) {
			for(var i = 0; i < tiddlers.length; i++) {
				var tiddler = tiddlers[i];
				var item = $("<li />").appendTo("#stream")[0];
				$("<h2 />").text(tiddler.title + ": ").appendTo(item);
				
				$("<div class='text' />").text(tiddler.text).appendTo(item);
				$("<div class='author' />").text(tiddler.modifier).appendTo(item);
			}
		}, function() {
			$("<li>no topics :-(</li>").appendTo("#stream");
		});
	});
	$(window).scroll(function(){
		if($(window).scrollTop() == $(document).height() - $(window).height()) {
			offset += 10;
			// find a way to get all tiddlers created before the ones above
			console.log("loadMore();");
		}
	});
</script>
</body>
</html>
[tag[rootTree]]]
/***
|''Name''|ImportExternalLinksPlugin|
|''Author''|Jon Robson|
|''Version''|0.3.0|
|''Requires''|TiddlySpaceConfig TiddlySpaceLinkPlugin TiddlySpaceCloneCommand|
|''Description''|Turns space links into ajax links so you don't have to leave the comfort of your own TiddlyWiki|
!Notes
This maybe should hides the editTiddler, cloneTiddler commands. Ideally the toolbar commands should hide themselves but we need a strong concept of "this is a sucked in tiddler" to do that.
***/
//{{{
(function($){
var tiddlyspace = config.extensions.tiddlyspace;
_createSpaceLink = createSpaceLink;
if(_createSpaceLink) {
	createSpaceLink = function(place, spaceName, title, alt, isBag) {
		var tooltip = "Click to open in current document. Right click to open in original space.";
		_createSpaceLink(place, spaceName, title, alt, isBag);
		var workspace;
		if(isBag) {
			workspace = "bags/%0".format(spaceName);
		} else {
			workspace = "bags/%0_public".format(spaceName);
		}
		if(title && spaceName != tiddlyspace.currentSpace.name) {
			var link = $("a:last", place);
			var newlink = $("<a />").text("[link]").after(link[0]);
			// very hacky
			var updateInterval = setInterval(function() {
				var href = link.attr("href");
				if(href) {
					$(newlink).attr("href", href);
					clearInterval(updateInterval);
				}
			}, 200);
			
			if(link.parent(".replyLink").length == 0) { // don't suck in a reply link.
				link.attr("title", tooltip).addClass("importLink").click(function(ev) {
					if(config.floorboards) {
						config.floorboards.pushUnique("%0_public".format(spaceName));
					}
					tiddlyspace.displayServerTiddler(ev.target, title, workspace, function(el) {
						// TODO: the commands should disable themselves based on the meta information.
						//$("[commandname=editTiddler], [commandname=cloneTiddler]", el).hide(); 
					});
					ev.preventDefault();
				});
			}
		}
	};
}

var _cloneHandler = config.commands.cloneTiddler.handler;
config.commands.cloneTiddler.handler = function(event, src, title) {
	var _tiddler = store.getTiddler(title);
	var source = _tiddler ? _tiddler.fields["server.bag"] : false;
	var imported = _tiddler ? _tiddler.fields["tiddler.source"] : false;
	var realTitle = _tiddler ? _tiddler.fields["server.title"] : title;
	_cloneHandler.apply(this, [event, src, title]);
	var tidEl = story.getTiddler(title);
	$(story.getTiddlerField(title, "title")).val(realTitle);
	if(source) {
		$("<input />").attr("type", "hidden").attr("edit", "tiddler.source").val(source).appendTo(tidEl);
		$("<input />").attr("type", "hidden").attr("edit", "server.activity").appendTo(tidEl);
	}
}
})(jQuery);
//}}}
<!--{{{-->
<div macro='slideRevision'></div>
<div class='heading'>
	<span class="titleBar">
		<div class='title' macro='view title text'></div>
	</span>
	<span class='modifierIcon'
		macro='view modifier SiteIcon label:no height:48 width:48 preserveAspectRatio:yes'>
	</span>
	<div class='toolbar'
		macro='toolbar [[ToolbarCommands::RevisionToolbar]] icons:yes height:48 width:48 more:popup'>
	</div>
	<div class='tagClear'></div>
</div>
<div class='content'>
	<div class='viewer' macro='view text wikified'></div>
</div>
<div class='tagInfo'>
	<div class='tidTags' macro='tags'></div>
	<div class='tagging' macro='tagging'></div>
</div>
<!--}}}-->
/***
|''Name''|GUID|
!Attribution
GUID code written by Mahemoff
 * Copyright (c) <year>, <copyright holder>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * TODO:
 * - Support for ISO GUID stanard
***/
//{{{
function Guid(options) {
	this.options = options || {};
	this.chars = this.options.chars || Guid.constants.alphanumerics;
	this.epoch = this.options.epoch || Guid.constants.epoch1970;
	this.counterSequenceLength = this.options.counterSequenceLength || 1;
	this.randomSequenceLength = this.options.randomSequenceLength || 2;
}

Guid.prototype.generate = function() {
	var now = (new Date()).getTime() - this.epoch;
	var guid = this.baseN(now);
	this.counterSeq = (now==this.lastTimestampUsed ? this.counterSeq+1 : 1);
	guid += this.counterSeq;
	for (var i=0; i<this.randomSequenceLength; i++) {
		guid += this.chars.charAt(Math.floor(Math.random() * this.chars.length));
	}
	this.lastTimestampUsed = now;
	return guid;
};

Guid.prototype.baseN = function(val) {
	if (val === 0) {
		return "";
	}
	var rightMost = val % this.chars.length;
	var rightMostChar = this.chars.charAt(rightMost);
	var remaining = Math.floor(val / this.chars.length);
	return this.baseN(remaining) + rightMostChar;
};

Guid.constants = {};
Guid.constants.numbers = "0123456789";
Guid.constants.alphas = "abcdefghijklmnopqrstuvwxyz";
Guid.constants.lowerAlphanumerics = "0123456789abcdefghijklmnopqrstuvwxyz";
Guid.constants.alphanumerics = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// http://tools.ietf.org/html/rfc1924
Guid.constants.base85 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&()*+-;<=>?@^_`{|}~";

Guid.constants.epoch1970 = (new Date(0));
Guid.constants.epoch = function(year) { 
	return (new Date("Jan 1 " + year)).getTime();
};

version.extensions.GuidPlugin = { installed: true };
if (!config.extensions) { 
	config.extensions = {};
}
config.extensions.GuidPlugin = {};

// clients may override these
config.extensions.GuidPlugin.guid = new Guid();
//}}}
iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAA3XAAAN1wFCKJt4AAAHTklEQVR4Ae2dT0gVXRTAx0+pBLEwTEGolQZRCoJLo1wZLnQTRK5UQg0SIVy5kDbuahWWWrkRC3Ih4kIEaaEl4soWtamFJVKChRjk3/x+MnK7zbz5997MvDvz3iweZ+7cue+cn3fuPfecN9ecw8NDzfo4ODhYWFiYnJxcXFz8/v37t2/fdnZ2zp07V1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0giwG9LsyF5ZuP24X/hReglXPopzFUxaW6GRHAl4Cc58ckhf4WGzqi/NM71n/ADs8ZO5jRJdTZDoyghnUzMIy4Do6ZURnnOLpE7F/gj8Ey3KOgGUPCwKfP38mTU1YkSAHn1lYFpyk4u3t7VevXhG8/h/x+YTd3b0e1AAAAABJRU5ErkJggg==
TiddlySpace applications are now ready to [[launch|/Applications]].

/***
|''Name''|ActivityStreamPlugin|
|''Version''|0.5.4|
|''Description''|Provides a following macro|
|''Author''|Jon Robson|
|''Requires''|TiddlySpaceFollowingPlugin|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''Source''|https://github.com/jdlrobson/TiddlyWiki/raw/master/plugins/TiddlySpaceInstaller/ActivityStreamPlugin.js|
!Usage
{{{<<activity>>}}}
!!Supressing activity
You can supress notifications by  id:
"plugin", "shadow", "standard", "follow", "followYou", "siteInfo", "siteIcon", "ownSiteIcon", "notify", "reply"
e.g. {{{ <<activity supress:siteIcon>> }}} will hide siteIcon activity from you.

!!Supressing people
{{{<<activity ignore:person}}} will ignore all activity where person is the subject of the activity. eg. person followed other-person will not appear in the feed.
!!Controlling displayed dates.
{{{<<activity timestampFormat:"<0hh o' clock>" headingFormat:"0DD/0MM" >>}}} will display date headings as date/month eg.
3rd of January would be displayed as 03/01. This particular timestamp example gives you the hour of the activity.

!!Even more content
{{{<<activity limit:no>>}}} will show you all possible activity in the last X days where X is set at a macro level (advanced developers should see config.macros.activity.RECENTNESS).
!StyleSheet

.activityStream .externalImage, .activityStream .image {
	display: inline;
}

.feedItem .siteIcon {
	display: inline;
}

.activityStream .error {
	background-color: red;
	color: white;
	font-weight: bold;
}

.activityStream .feedItem {
list-style: none;
}

.activityStream .notification {
	background-color: yellow;
	color: black;
}

.activityStream .activityGroupTitle {
	font-weight: bold;
	margin-top: 8px;
}
.activityStream .feedItem {
	margin-left: 8px;
}
!Code
***/
//{{{
(function($) {
var name = "StyleSheetActivityStream";
config.shadowTiddlers[name] = store.getTiddlerText(tiddler.title +
     "##StyleSheet");
store.addNotification(name, refreshStyles);

var followMacro = config.macros.followTiddlers;
var tweb = config.extensions.tiddlyweb;
var tiddlyspace = config.extensions.tiddlyspace;
var scanMacro = config.macros.tsScan;

var modifierSpaceLink = "<<view modifier spaceLink>>";
var spaceTiddlyLink = "<<view server.bag spaceLink server.title>>";
var bagSpaceLink = "<<view server.bag spaceLink>>";
var bagSiteIcon = "<<view server.bag SiteIcon width:24 height:24 label:no preserveAspectRatio:yes>>";
var modifierSiteIcon = "<<view modifier SiteIcon width:24 height:24 label:no preserveAspectRatio:yes>>";
var timestamp = "[<<view modified date '0hh:0mm'>>]";
var replyLink = "<<view server.title replyLink>>";
config.shadowTiddlers.ActivityStreamTemplates = [
	"!notify\n%3 {{notification{%0 %1 has modified %2 in %0 %1 and flagged it for your attention!}}} %8\n",
	"!reply\n%3 {{notification{%0 %1 replied with %2 to your %4 %5 post.}}} %8\n",
	"!userSiteIcon\n%3 %6 %7 has a new ~SiteIcon.\n",
	"!spaceSiteIcon\n%3 %6 %7 updated the SiteIcon for the %0 %1 space.\n",
	"!image\n%3 %6 %7 drew the image %2 in the %1 space.\n",
	"!plugin\n%3 %6 %7 modified a plugin called %2 in the %0 %1 space.\n",
	"!shadow\n%3 %6 %7 modified a shadow tiddler %2 in the %0 %1 space.\n",
	"!geo\n%3 %6 %7 modified a geo tiddler called %2 in the %0 %1 space <<view title maplink 'view on map'>>. %8\n",
	"!followYou\n%3 %0 %1 is now following you.\n",
	"!follow\n%3 %0 %1 is now following %4 %5 <<view server.title link follow>>\n",
	"!siteInfo\n%3 %6 %7 <<view server.bag spaceLink server.title label:described>> the %0 %1 space.\n",
	"!video\n%3 %6 %7 modified a video entitled %2 in the %0 %1 space. %8\n",
	"!standard\n%3 %6 %7 modified %2 in the %0 %1 space. %8\n"
	].join("").format(bagSiteIcon, bagSpaceLink, spaceTiddlyLink, timestamp,
		"<<view server.title SiteIcon width:24 height:24 label:no preserveAspectRatio:yes>>", "<<view server.title spaceLink>>",
		modifierSiteIcon, modifierSpaceLink, replyLink);
story.refreshTiddler("ActivityStreamTemplates", null, true);
config.annotations.ActivityStreamTemplates = "This is a special tiddler used by the ActivityStreamPlugin. It is used for templating notifications. Templates at the top have preference over templates at the bottom.";

var macro = config.macros.activity = {
	default_limit: 50,
	templates: [],
	init: function() {
		var templates = [];
		var regex = new RegExp(/^!(.*)\n/gm);
		var text = store.getTiddlerText("ActivityStreamTemplates");
		var match = regex.exec(text);
		while(match) {
			templates.push(match[1]);
			match = regex.exec(text);
		}
		macro.templates = templates;
	},
	// order matters - earlier templates override older ones
	RECENTNESS: 2, // in days
	TIMESTAMP_FORMAT: "<0hh:0mm>",
	info: {},
	locale: {
		pleaseWait: "please wait while we load your stream...",
		errorLoading: "The activity stream failed to load. Please make sure you have an internet connection and try again.",
		userHeading: "Below is the activity stream for spaces that this space follows with the follow tag. (%0/%1 spaces have been loaded)",
		emptyStream: "Activity stream currently empty. (%0/%1 loaded)"
	},
	getTimeStamp: function() {
		var today = new Date();
		macro._lastRun = today.getTime();
		var previous = new Date(today.setDate(today.getDate() - macro.RECENTNESS));
		return previous.convertToYYYYMMDDHHMM();
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var container = $("<div />").text(macro.locale.pleaseWait).appendTo(place).
			attr("refresh", "macro").attr("macroName", macroName).attr("paramString", paramString);
		var space = tiddlyspace.currentSpace.name;
		var options = macro.getOptions(paramString);
		$(container).attr("activity-limit", options.limit);
		macro._session = Math.random();
		var activityType;
		var sourceActivity = function(user) {
			macro.CURRENT_USER = user.name;
			macro.USER_AT_TAG = "@%0".format(user.name);
			followMacro.getFollowers(function(users) {
				macro.getActivity(container, users, activityType, options);
			}, macro.CURRENT_USER);
			container.attr("activity-type", activityType);
			macro._renderStream(container, activityType, options);
		};

		if(options.user) {
			sourceActivity({name: options.user});
		} else {
			sourceActivity({ name: tiddlyspace.currentSpace.name });
		}
	},
	getOptions: function(paramString) {
		var options = {};
		var args = paramString.parseParams("name")[0];
		var toMap = ["timestampFormat", "headingFormat", "limit", "user"];
		var i;
		for(i = 0; i < toMap.length; i++) {
			var map = toMap[i];
			options[map] = args[map] ? args[map][0] : false;
		}
		var supress = args.supress || [];
		var templates = [];
		var show = args.show ? args.show : macro.templates;
		for(i = 0; i < show.length; i++) {
			var template = show[i];
			if(supress.indexOf(template) === -1) {
				templates.push(template);
			}
		}
		options.ignore = args.ignore || [];
		options.templates = templates;
		return options;
	},
	_getActivityQuery: function(user, timestamp) {
		timestamp = timestamp || macro.getTimeStamp();
		if(user) {
			return "/bags/%0_public/tiddlers?select=modified:>%1".format(user, timestamp);
		} else {
			return false;
		}
	},
	refresh: function(container) {
		var type = $(container).attr("activity-type");
		var limit = $(container).attr("activity-limit");
		var options = macro.getOptions($(container).attr("paramString"));
		options.limit = parseInt(limit, 10);
		macro.renderStream(container, type, options);
	},
	getActivity: function(place, users, type, options) {
		var i;
		var timestamp = macro.activityTimestamp;
		var firstRun =  timestamp ? false : true;
		macro.info.loaded = firstRun ? 0 : macro.info.loaded;
		var afterAjax = function(tiddlers) {
			if(firstRun) {
				macro.info.loaded += 1;
			}
			macro.updateStream(tiddlers, type, options);
			macro.renderStream(place, type, options);
		};
		var success = function(tiddlers) {
			afterAjax(tiddlers);
		};
		var error = function() {
			afterAjax([]);
		};
		if(macro._lastRun > new Date().getTime() - 300000) { // leave 5 minutes between calls
			afterAjax([]);
			return;
		}
		macro.info.queries = users.length;
		for(i = 0; i < users.length; i++) {
			var user = users[i];
			ajaxReq({
				url: macro._getActivityQuery(user, timestamp),
				dataType: "json", success: success, error: error
			});
		}
		macro.activityTimestamp = new Date().convertToYYYYMMDDHHMM();
	},
	reportError: function(place) {
		var error = $("<div />").addClass("error").text(locale.errorLoading);
		$(place).empty().append(error);
	},
	createFeedEntry: function(container, tiddler, options) {
		var item = $("<li />").addClass("feedItem");
		var content = $("<div />").appendTo(item);
		var wikifyPlace = $("<span />").appendTo(content)[0];
		var author = tiddler.modifier;
		if(author && !options.ignore.contains(author)) {
			$(container).append(item);
			config.macros.view.views.activityItem(null, wikifyPlace, null, null, null, tiddler);
			return item;
		}
		return false;
	},
	renderStream: function(place, type, options) {
		window.clearTimeout(macro._renderTimeout);
		macro._renderTimeout = window.setTimeout(function() {
			macro._renderStream(place, type, options);
		}, 100);
	},
	_renderStream: function(place, type, options) {
		$(place).empty();
		var limit = options.limit;
		var container = $("<ul />").addClass("activityStream").appendTo(place);
		var textHeading = macro.locale.userHeading.format(macro.info.loaded, macro.info.queries);
		$("<li />").addClass("listTitle").text(textHeading).appendTo(container);
		var tiddlers = store.sortTiddlers(store.filterTiddlers("[server.activity[true]]"), "-modified"); // TODO: sort headings instead if possible (conflicts with limit)
		var headings = [];
		var groups = {};
		var processed = 0, i, j;
		var atEndOfActivityFeed = true;
		for(i = 0; i < tiddlers.length; i++) {
			var tiddler = tiddlers[i];
			if(options.templates.contains(tiddler.fields["server.activity.type"])) {
				if(!limit || processed < limit) {
					var modified = tiddler.modified;
					if(modified) {
						// format date.
						var modifiedString = modified.formatString(options.headingFormat || config.macros.timeline.dateFormat);
						if(headings.contains(modifiedString)) {
							groups[modifiedString].push(tiddler);
						} else {
							headings.push(modifiedString);
							groups[modifiedString] = [ tiddler ];
						}
					}
					processed += 1;
				} else {
					atEndOfActivityFeed = false;
				}
			}
		}
		var somethingRendered;
		for(i = 0; i < headings.length; i++) {
			var heading = headings[i];
			var _tiddlers = store.sortTiddlers(groups[heading], "-modified");
			var headingEl;
			if(_tiddlers.length > 0) {
				headingEl = $("<li />").addClass("listTitle activityGroupTitle").text(heading).appendTo(container);
			}
			var rendered = [];
			for(j = 0; j < _tiddlers.length; j++) {
				var item = macro.createFeedEntry(container, _tiddlers[j], options);
				if(item) {
					rendered.push(item);
				}
			}
			if(rendered.length === 0) {
				headingEl.remove();
			} else {
				somethingRendered = true;
			}
		}
		if(!somethingRendered) {
			var msg;
			if(macro.gotActivity) { // it has been run before
				msg = macro.locale.emptyStream.format(macro.info.loaded, macro.info.queries);
			} else {
				msg = macro.locale.pleaseWait;
			}
			$(container).text(msg);
		}
		if(!atEndOfActivityFeed) { // show more button
			$("<input />").attr("type", "button").val("more").click(function(ev) {
				var currentLimit = $(place).attr("activity-limit");
				var newLimit = parseInt(currentLimit, 10) + 50;
				macro.default_limit = newLimit;
				$(place).attr("activity-limit", newLimit);
				macro.refresh(place);
			}).appendTo(place);
		}
		this.gotActivity = true;
	},
	updateStream: function(jstiddlers, type, options) {
		// assume already sorted.
		var tiddlers = scanMacro._tiddlerfy(jstiddlers, options);
		var _dirty = store.isDirty();
		$.each(tiddlers, function(i, tid) {
			var info = config.macros.view.activity.getActivityInfo(tid, options);
			tid.fields["server.activity.type"] = info.type;
			tid.fields["server.activity"] = "true";
			if(!tid.tags.contains("excludeLists")) {
				tid.title = tiddlyspace.getLocalTitle(tid.title, tid.fields["server.workspace"]);
				tid.tags = tid.tags.concat(["excludeLists", "excludeMissing", "excludeSearch"]);
				tid.fields.doNotSave = "true";
				store.addTiddler(tid); // save caused unsaved changes alert and slowdown
			}
		});
		store.setDirty(_dirty);
	}
};

config.macros.view.views.activityItem = function(value, place, params, wikifier,
	paramString, tiddler) {
	var info = config.macros.view.activity.getActivityInfo(tiddler, {});
	wikify(info.template, place, null, tiddler);
};

var helper = config.macros.view.activity = {
	_isNotification: function(tiddler) {
		return tiddler.tags.contains(macro.USER_AT_TAG) || tiddler.tags.contains("@all");
	},
	_repliesOn: function() {
		return tiddlyspace.currentSpace.name === macro.CURRENT_USER;
	},
	types: {
		video: function(tiddler) {
			return tiddler.tags.contains("video");
		},
		geo: function(tiddler) {
			return tiddler.fields["geo.lat"] && tiddler.fields["geo.long"];
		},
		siteInfo: function(tiddler) {
			var title = tiddler.fields["server.title"];
			return title === "SiteInfo";
		},
		userSiteIcon: function(tiddler) {
			var modifierBag = "%0_public".format(tiddler.modifier);
			var title = tiddler.fields["server.title"];
			return title === "SiteIcon" && modifierBag === tiddler.fields["server.bag"];
		},
		spaceSiteIcon: function(tiddler) {
			var title = tiddler.fields["server.title"];
			return title === "SiteIcon"; // note userSiteIcon above does the bag check
		},
		shadow: function(tiddler) {
			var title = tiddler.fields["server.title"];
			return title in config.shadowTiddlers;
		},
		plugin: function(tiddler) {
			return tiddler.tags.contains("systemConfig");
		},
		followYou: function(tiddler) {
			var title = tiddler.fields["server.title"];
			title = title.indexOf("@") === 0 ? title.substr(1) : title;
			return tiddler.tags.contains("follow") && title === macro.USER_AT_TAG;
		},
		follow: function(tiddler) {
			return tiddler.tags.contains("follow");
		},
		reply: function(tiddler) {
			var title = tiddler.fields["server.title"];
			var myTiddler = store.getTiddler(tiddler.title);
			var myTiddlerIsOlder = myTiddler && myTiddler.modified < tiddler.modified;
			return store.tiddlerExists(title) && myTiddlerIsOlder && helper._repliesOn(tiddler);
		},
		notify: function(tiddler) {
			var title = tiddler.fields["server.title"];
			var myTiddler = store.getTiddler(title);
			var myTiddlerIsNewer = myTiddler && myTiddler.modified > tiddler.modified;
			return helper._isNotification(tiddler) && helper._repliesOn(tiddler) && !myTiddlerIsNewer;
		},
		standard: function(tiddler) {
			return true;
		},
		image: function(tiddler) {
			return config.macros.image.isImageTiddler(tiddler);
		}
	},
	// each type should point to a slice in ActivityStreamTemplates tiddler
	getActivityInfo: function(tiddler, options) {
		var repliesOn = tiddlyspace.currentSpace.name === macro.CURRENT_USER;
		var activityType, i;
		if(tiddler) {
			for(i = 0; i < macro.templates.length; i++) {
				var type = macro.templates[i];
				if(!activityType && helper.types[type]) {
					if(helper.types[type](tiddler)) {
						activityType = type;
					}
				}
			}
		}
		template = store.getTiddlerText("ActivityStreamTemplates##" + activityType) || locale.standardTemplate;
		return activityType ? { template: template, type: activityType } : false;
	}
};

config.macros.view.views.link = function(value, place, params, wikifier,
		paramString, tiddler) {
		var el = createTiddlyLink(place,value,true);
		if(params[2]) {
			$(el).text(params[2]);
		}
};

config.macros.view.views.maplink = function(value, place, params, wikifier,
		paramString, tiddler) {
		var lat = tiddler.fields["geo.lat"];
		var lng = tiddler.fields["geo.long"];
		var label  = params[2] || value;
		if(lat && lng) {
			$("<a />").attr("href", "http://maps.google.com/maps?saddr=%0,%1".format(lat, lng)).text(label).appendTo(place);
		}
};

var _displayS = tiddlyspace.displayServerTiddler;
tiddlyspace.displayServerTiddler = function(src, title, workspace, callback) {
	var localTitle = tiddlyspace.getLocalTitle(title, workspace);
	var localTiddler = store.getTiddler(localTitle);

	var _callback = function(src, tiddler) {
		if(callback) {
			callback(src, tiddler);
		}
		if(localTiddler) {
			tiddler.fields["server.activity"] = "true";
			tiddler.fields["server.activity.type"] = localTiddler.fields["server.activity.type"];
		}
	};
	return _displayS.apply(this, [ src, title, workspace, _callback ]);
};
}(jQuery));
//}}}
/***
|''Name''|PermalinkViewPlugin|
|''Version''|0.9.0|
|''Author''|Jon Robson|
|''Description''|Provides a permalink view type|
|''Requires''|ImageMacroPlugin|
!Notes
***/
//{{{
(function($) {
config.macros.view.views.permalink =  function(value, place, params, wikifier,
	paramString, tiddler) {
	var permalink = "#[[%0]]".format([value]);
	if(store.tiddlerExists("link.svg")) {
		config.macros.image.renderImage(place, "link.svg", {height: 24, width: 24, labelOptions: { include: false}, link: permalink});
	} else {
		$("<a />").attr("href", permalink).text(value).appendTo(place);
	}
};

})(jQuery);
//}}}
/***
|''Name''|TiddlySpacePublishingCommands|
|''Version''|0.8.5|
|''Status''|@@beta@@|
|''Description''|toolbar commands for drafting and publishing|
|''Author''|Jon Robson|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpacePublishingCommands.js|
|''CoreVersion''|2.6.1|
|''Requires''|TiddlySpaceConfig TiddlySpaceFilters|
!Usage
Provides changeToPrivate, changeToPublic and saveDraft commands
Provides TiddlySpacePublisher macro.
{{{<<TiddlySpacePublisher type:private>>}}} make lots of private tiddlers public.
{{{<<TiddlySpacePublisher type:public>>}}} make lots of public tiddlers public.
!TODO
* add public argument?
!Code
***/
//{{{
(function($) {

var tiddlyspace = config.extensions.tiddlyspace;
var originMacro = config.macros.tiddlerOrigin;

tiddlyspace.getTiddlerStatusType = function(tiddler) {
	var isShadow = store.isShadowTiddler(tiddler.title);
	var exists = store.tiddlerExists(tiddler.title);
	if(isShadow && !exists) {
		return "shadow";
	} else if(!exists) {
		return "missing";
	} else {
		var types = ["private", "public"];
		var type = "external";
		for(var i = 0; i < types.length; i++) {
			var t = types[i];
			type = config.filterHelpers.is[t](tiddler) ? t : type;
		}
		if(config.filterHelpers.is.unsynced(tiddler)) {
			type = type == "private" ? "unsyncedPrivate" : "unsyncedPublic";
		}
		return type;
	}
};

var cmd = config.commands.publishTiddler = {
	text: "make public",
	tooltip: "Change this private tiddler into a public tiddler",
	errorMsg: "Error publishing %0: %1",

	isEnabled: function(tiddler) {
		return !readOnly && config.filterHelpers.is["private"](tiddler);
	},
	handler: function(ev, src, title) {
		var tiddler = store.getTiddler(title);
		if(tiddler) {
			var newBag = cmd.toggleBag(tiddler.fields["server.bag"]);
			this.moveTiddler(tiddler, {
				title: tiddler.fields["publish.name"] || tiddler.title,
				fields: { "server.bag": newBag }
			});
		}
	},
	toggleBag: function(bag, to) {
		var newBag;
		if(typeof bag != typeof "") {
			var tiddler = bag;
			bag = tiddler.fields["server.bag"];
		}
		if(bag.indexOf("_private") > -1) { // should make use of endsWith
			to = to ? to : "public";
			newBag = bag.replace("_private", "_" + to);
		} else {
			to = to ? to : "private";
			newBag = bag.replace("_public", "_" + to);
		}
		return newBag;
	},
	copyTiddler: function(title, newTitle, newBag, callback) {
		var original = store.getTiddler(title);
		newTitle = newTitle ? newTitle : title;
		var adaptor = original.getAdaptor();
		var publish = function(original, callback) {
			var tiddler = $.extend(new Tiddler(newTitle), original);
			tiddler.fields = $.extend({}, original.fields, {
				"server.bag": newBag,
				"server.workspace": "bags/%0".format(newBag),
				"server.page.revision": "false"
			});
			delete tiddler.fields["server.title"];
			tiddler.title = newTitle;
			adaptor.putTiddler(tiddler, null, null, callback);
		};
		publish(original, callback);
	},
	moveTiddler: function(tiddler, newTiddler, callback) {
			var info = {
			copyContext: {},
			deleteContext: {}
		};
		var _dirty = store.isDirty();
		var adaptor = tiddler.getAdaptor();
		var newTitle = newTiddler.title;
		var oldTitle = tiddler.title;
		delete tiddler.fields["server.workspace"];
		var oldBag = tiddler.fields["server.bag"];
		var newBag = newTiddler.fields["server.bag"];
		var newWorkspace = "bags/%0".format(newBag);
		cmd.copyTiddler(oldTitle, newTitle, newBag, function(ctx) {
				info.copyContext = ctx;
				var context = {
					tiddler: tiddler,
					workspace: newWorkspace
				};
				store.addTiddler(ctx.tiddler);
				tiddler.title = oldTitle; // for cases where a rename occurs
				if(ctx.status) { // only do if a success
					if(oldBag != newBag) {
						adaptor.deleteTiddler(tiddler, context, {}, function(ctx) {
							info.deleteContext = ctx;
							var el;
							if(tiddler) {
								tiddler.fields["server.workspace"] = newWorkspace;
								tiddler.fields["server.bag"] = newBag;
							}
							el = el ? el : story.refreshTiddler(oldTitle, null, true);
							if(oldTitle != newTitle) {
								store.deleteTiddler(oldTitle);
								store.notify(oldTitle, true);
							}
							if(el) {
								story.displayTiddler(el, newTitle);
							}
							if(oldTitle != newTitle) {
								story.closeTiddler(oldTitle);
							}
							if(callback) {
								callback(info);
							}
							store.setDirty(_dirty);
						});
					} else {
						if(callback) {
							callback(info);
						}
					}
					refreshDisplay();
				}
		});
	}
};

var changeToPrivate = config.commands.changeToPrivate = {
	text: "make private",
	tooltip: "turn this public tiddler into a private tiddler",
	isEnabled: function(tiddler) {
		return !readOnly && config.filterHelpers.is["public"](tiddler);
	},
	handler: function(event, src, title) {
		var tiddler = store.getTiddler(title);
		var newBag = cmd.toggleBag(tiddler, "private");
		var newTiddler = { title: title, fields: { "server.bag": newBag }};
		cmd.moveTiddler(tiddler, newTiddler);
	}
};
config.commands.changeToPublic = cmd;

/* Save as draft command */
var saveDraftCmd = config.commands.saveDraft = {
	text: "save draft",
	tooltip: "Save as a private draft",
	isEnabled: function(tiddler) {
		return changeToPrivate.isEnabled(tiddler);
	},
	getDraftTitle: function(title) {
		var draftTitle;
		var draftNum = "";
		while(!draftTitle) {
			var suggestedTitle = "%0 [draft%1]".format(title, draftNum);
			if(store.getTiddler(suggestedTitle)) {
				draftNum = !draftNum ? 2 : draftNum + 1;
			} else {
				draftTitle = suggestedTitle;
			}
		}
		return draftTitle;
	},
	createDraftTiddler: function(title, gatheredFields) {
		var tiddler = store.getTiddler(title);
		var draftTitle = saveDraftCmd.getDraftTitle(title);
		var draftTiddler = new Tiddler(draftTitle);
		if(tiddler) {
			$.extend(true, draftTiddler, tiddler);
		} else {
			$.extend(draftTiddler.fields, config.defaultCustomFields);
		}
		for(var fieldName in gatheredFields) {
			if(TiddlyWiki.isStandardField(fieldName)) {
				draftTiddler[fieldName] = gatheredFields[fieldName];
			} else {
				draftTiddler.fields[fieldName] = gatheredFields[fieldName];
			}
		}
		var privateBag = tiddlyspace.getCurrentBag("private");
		var privateWorkspace = tiddlyspace.getCurrentWorkspace("private");
		draftTiddler.title = draftTitle;
		draftTiddler.fields["publish.name"] = title;
		draftTiddler.fields["server.workspace"] = privateWorkspace;
		draftTiddler.fields["server.bag"] = privateBag;
		draftTiddler.fields["server.title"] = draftTitle;
		draftTiddler.fields["server.page.revision"] = "false";
		delete draftTiddler.fields["server.etag"];
		return draftTiddler;
	},
	handler: function(ev, src, title) {
		var tiddler = store.getTiddler(title); // original tiddler
		var tidEl = story.getTiddler(title);
		var uiFields = {};
		story.gatherSaveFields(tidEl, uiFields);
		var tid = saveDraftCmd.createDraftTiddler(title, uiFields);
		tid = store.saveTiddler(tid.title, tid.title, tid.text, tid.modifier,
			new Date(), tid.tags, tid.fields);
		autoSaveChanges(null, [tid]);
		story.closeTiddler(title);
		story.displayTiddler(src, title);
		story.displayTiddler(src, tid.title);
	}
};

var macro = config.macros.TiddlySpacePublisher = {
	locale: {
		title: "Batch Publisher",
		changeStatusLabel: "Make %0",
		noTiddlersText: "No tiddlers to publish",
		changeStatusPrompt: "Make all the selected tiddlers %0.",
		description: "Change tiddlers from %0 to %1 in this space"
	},

	listViewTemplate: {
		columns: [
			{ name: "Selected", field: "Selected", rowName: "title", type: "Selector" },
			{ name: "Tiddler", field: "tiddler", title: "Tiddler", type: "Tiddler" },
			{ name: "Status", field: "status", title: "Status", type: "WikiText" }
		],
		rowClasses: []
	},

	changeStatus: function(tiddlers, status, callback) { // this is what is called when you click the publish button
		var publicBag;
		for(var i = 0; i < tiddlers.length; i++) {
			var tiddler = tiddlers[i];
			var newTiddler = {
				title: tiddler.title,
				fields: { "server.bag": cmd.toggleBag(tiddler, status) }
			};
			cmd.moveTiddler(tiddler, newTiddler, callback);
		}
	},
	getMode: function(paramString) {
		var params = paramString.parseParams("anon")[0];
		var status = params.type ?
			(["public", "private"].contains(params.type[0]) ? params.type[0] : "private") :
			"private";
		var newStatus = status == "public" ? "private" : "public";
		return [status, newStatus];
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var wizard = new Wizard();
		var locale = macro.locale;
		var status = macro.getMode(paramString);
		wizard.createWizard(place, locale.title);
		wizard.addStep(macro.locale.description.format(status[0], status[1]),
			'<input type="hidden" name="markList" />');
		var markList = wizard.getElement("markList");
		var listWrapper = $("<div />").addClass("batchPublisher").
			attr("refresh", "macro").attr("macroName", macroName).
			attr("params", paramString)[0];
		markList.parentNode.insertBefore(listWrapper, markList);
		$.data(listWrapper, "wizard", wizard);
		macro.refresh(listWrapper);
	},
	getCheckedTiddlers: function(listWrapper, titlesOnly) {
		var tiddlers = [];
		$(".chkOptionInput[rowName]:checked", listWrapper).each(function(i, el) {
			var title = $(el).attr("rowName");
			if(titlesOnly) {
				tiddlers.push(title);
			} else {
				tiddlers.push(store.getTiddler(title));
			}
		});
		return tiddlers;
	},
	refresh: function(listWrapper) {
		var checked = macro.getCheckedTiddlers(listWrapper, true);
		var paramString = $(listWrapper).empty().attr("params");
		var wizard = $.data(listWrapper, "wizard");
		var locale = macro.locale;
		var params = paramString.parseParams("anon")[0];
		var publishCandidates = [];
		var status = macro.getMode(paramString);
		var pubType = status[0];
		var newPubType = status[1];
		var tiddlers = params.filter ? store.filterTiddlers(params.filter[0]) :
			store.filterTiddlers("[is[%0]]".format(pubType));
		var enabled = [];
		for(var i = 0; i < tiddlers.length; i++) {
			var tiddler = tiddlers[i];
			var title = tiddler.title;
			if(!tiddler.tags.contains("excludePublisher") && title !== "SystemSettings") {
				publishCandidates.push({ title: title, tiddler: tiddler, status: pubType});
			}
			if(checked.contains(title)) {
				enabled.push("[rowname=%0]".format(title));
			}
		}

		if(publishCandidates.length === 0) {
			createTiddlyElement(listWrapper, "em", null, null, locale.noTiddlersText);
		} else {
			var listView = ListView.create(listWrapper, publishCandidates, macro.listViewTemplate);
			wizard.setValue("listView", listView);
			var btnHandler = function(ev) {
				var tiddlers = macro.getCheckedTiddlers(listWrapper);
				var callback = function(status) {
					$(".batchPublisher").each(function(i, el) {
						macro.refresh(el);
					});
				};
				macro.changeStatus(tiddlers, newPubType, callback);
			};
			wizard.setButtons([{
				caption: locale.changeStatusLabel.format(newPubType),
				tooltip: locale.changeStatusPrompt.format(newPubType),
				onClick: btnHandler
			}]);
			$(enabled.join(",")).attr("checked", true); // retain what was checked before
		}
	}
};

})(jQuery);
//}}}
!Spaces
<<groupBy server.bag>>

!Private
<<list filter [is[private]]>>

!Public
<<list filter [is[public]]>>

!Drafts
<<list filter [is[draft]]>>
/***
|''Name''|TiddlySpaceBackstage|
|''Version''|0.8.0|
|''Description''|Provides a TiddlySpace version of the backstage and a homeLink macro|
|''Status''|@@beta@@|
|''Contributors''|Jon Lister, Jon Robson, Colm Britton|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpaceBackstage.js|
|''Requires''|TiddlySpaceConfig ImageMacroPlugin TiddlySpaceViewTypes|
!StyleSheet
.tiddler .error.annotation .button{
	display: inline-block;
}

#backstageArea {
	z-index: 49;
	color: white;
	background-color: black;
	background: -webkit-gradient(linear,left bottom,left top,color-stop(0, #222),color-stop(0.5, #333),color-stop(1, #555));
	background: -moz-linear-gradient(center bottom,#222 0%, #333 50%, #555 100%);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ff555555, endColorstr=#ff222222);
	-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ff555555, endColorstr=#ff222222)";
	height: 25px;
	padding: 0;
}

#backstageButton {
	overflow: hidden;
}

#backstageButton #backstageShow,
#backstageButton #backstageHide {
	margin: 0px;
	padding: 0px;
}

#backstageButton #backstageShow:hover,
#backstageButton #backstageHide:hover {
	background: none;
	color: none;
}

#backstageButton img,
#backstageButton svg {
	width: 24px;
	height: 24px;
}

#messageArea {
	top: 50px;
}

#backstageToolbar {
	position: relative;
}

#backstageArea a {
	padding: 0px;
	margin-left: 0px;
	color: white;
	background: none;
}

#backstageArea a:hover {
	background-color: white;
}

#backstage ol,
#backstage ul {
	padding: auto;
}

#backstageButton a {
	margin: 0;
}

.backstagePanelBody ul {
	padding: 5px;
	margin: 5px;
}

#backstage #backstagePanel {
	margin-left: 5%;
	padding: 0em;
	margin-right: 5%;
}

#backstageToolbar a {
	position: relative;
}

#backstageArea a.backstageSelTab,
#backstageToolbar .backstageTask {
	line-height: 25px;
	color: #767676;
}

.backstageTask .externalImage,
.backstageTask .image {
	display: inline;
}

#backstageToolbar a span {
	z-index: 2;
}

a.backstageTask {
	display: inline;
        margin-left: 1em !important;
}

.backstagePanelBody .button {
	display: inline-block;
	margin-right: 10px;
}

.backstagePanelBody {
	margin: 0 0 0 0.6em;
	padding: 0.4em 0.5em 1px 0.5em;
}

#backstage table {
	margin: auto;
}

#backstage .wizard table {
	border: 0px;
	margin: 0;
}

#backstage div  li.listLink {
	border: 0px;
	width: 78%;
	font-size: 0.7em;
}

#backstage div li.listTitle {
	font-weight: bold;
	text-decoration: underline;
	font-size: 1em;
	background: #ccc;
	width: 100%;
}

#backstage fieldset {
	border: solid 1px [[ColorPalette::Background]];
}

#backstage .viewer table,#backstage table.twtable {
	border: 0px;
}

#backstageToolbar img {
	padding: 0;
}

#backstage .wizard,
#backstage .wizardFooter {
	background: none;
}

.viewer td, .viewer tr, .twtable td, .twtable tr {
	border: 1px solid #eee;
}

#backstage .inlineList ul li {
	background-color: [[ColorPalette::Background]];
	border: solid 1px [[ColorPalette::TertiaryMid]];
	display: block;
	float: left;
	list-style: none;
	margin-right: 1em;
	padding: 0.5em;
}

.backstageClear, .inlineList form {
	clear: both;
	display: block;
	margin-top: 3em;
}

.tiddlyspaceMenu {
	text-align: center;
}

span.chunkyButton {
	display: inline-block;
	padding: 0;
	margin: 0;
	border: solid 2px #000;
	background-color: #04b;
}

span.chunkyButton a.button, span.chunkyButton a:active.button {
	white-space: nowrap;
	font-weight: bold;
	font-size: 1.8em;
	color: #fff;
	text-align: center;
	padding: 0.5em 0.5em;
	margin: 0;
	border-style: none;
	display: block;
}

span.chunkyButton:hover {
	background-color: #014;
}

span.chunkyButton a.button:hover {
	border-style: none;
	background: none;
	color: #fff;
}

#backstage .unpluggedSpaceTab .wizard,
.unpluggedSpaceTab .wizard {
	background: white;
	border: 2px solid #CCC;
	padding: 5px;
}

.syncKey .keyItem {
	border: 1px solid black;
	display: inline-block;
	margin: 0.2em;
	padding: 0.1em 0.1em 0.1em 0.1em;
}

.keyHeading {
	font-size: 2em;
	font-weight: bold;
	margin: 0.4em 0em -0.2em;
}

.unpluggedSpaceTab .putToServer,
.unpluggedSpaceTab .notChanged {
	display: none;
}

.tiddlyspaceMenu ul {
	margin: 0;
	padding: 0;
}

.tiddlyspaceMenu ul li {
	list-style: none;
}

.unsyncedChanges .unsyncedList {
	display: block;
}

.unsyncedList {
	display: none;
}
!Code
***/
//{{{
(function ($) {
    var name = "StyleSheet" + tiddler.title;
    config.shadowTiddlers[name] = "/*{{{*/\n%0\n/*}}}*/".
        format(store.getTiddlerText(tiddler.title + "##StyleSheet")); // this accesses the StyleSheet section of the current tiddler (the plugin that contains it)
    store.addNotification(name, refreshStyles);

    if (!config.extensions.tiddlyweb.status.tiddlyspace_version) { // unplugged
        config.extensions.tiddlyweb.status.tiddlyspace_version = "<unknown>";
        config.extensions.tiddlyweb.status.server_host = {
            url:config.extensions.tiddlyweb.host }; // TiddlySpaceLinkPlugin expects this
    }
    var disabled_tasks_for_nonmembers = ["tiddlers", "plugins", "batch", "sync"];

    var tweb = config.extensions.tiddlyweb;
    var tiddlyspace = config.extensions.tiddlyspace;
    var currentSpace = tiddlyspace.currentSpace.name;
    var imageMacro = config.macros.image;

    if (config.options.chkBackstage === undefined) {
        config.options.chkBackstage = false;
    }

// Set up Backstage
    config.tasks = {};
    config.tasks.status = {
        text:"status",
        tooltip:"TiddlySpace Info",
        content:"<<tiddler Backstage##Menu>>"
    };
    config.tasks.tiddlers = {
        text:"tiddlers",
        tooltip:"tiddlers control panel",
        content:"<<tiddler Backstage##BackstageTiddlers>>"
    };
    config.tasks.plugins = {
        text:"plugins",
        tooltip:"Manage installed plugins",
        content:"<<tiddler Backstage##Plugins>>"
    };
    config.tasks.batch = {
        text:"batch",
        tooltip:"Batch manage public/private tiddlers",
        content:"<<tiddler Backstage##BatchOps>>"
    };
    config.tasks.tweaks = {
        text:"tweaks",
        tooltip:"Tweak TiddlyWiki behaviors",
        content:"<<tiddler Backstage##Tweaks>>"
    };
    config.tasks.exportTiddlers = {
        text:"import/export",
        tooltip:"Import/export tiddlers from/to a TiddlyWiki",
        content:"<<tiddler Backstage##ImportExport>>"
    };
    config.tasks.sync = {
        text:"sync",
        tooltip:"Check Sync status",
        content:"<<tiddler Backstage##SpaceUnplugged>>"
    };

    if (window.location.protocol === "file:") {
        config.unplugged = true;
    }

    config.backstageTasks = ["status", "tiddlers", "plugins",
        "batch", "tweaks", "exportTiddlers", "sync"];

    config.messages.backstage.prompt = "";
// initialize state
    var _show = backstage.show;
    backstage.show = function () {
        // selectively hide backstage tasks and tabs based on user status
        var tasks = $("#backstageToolbar .backstageTask").show();
        var bs = backstage.tiddlyspace;
        if (!config.unplugged) {
            tweb.getUserInfo(function (user) {
                if (user.anon) {
                    jQuery.each(disabled_tasks_for_nonmembers, function (i, task) {
                        var taskIndex = config.backstageTasks.indexOf(task);
                        if (taskIndex !== -1) {
                            config.backstageTasks.splice(taskIndex, 1);
                        }
                    });
                    config.messages.memberStatus = bs.locale.loggedout;
                } else {
                    config.messages.memberStatus = readOnly ?
                        bs.locale.nonmember : bs.locale.member;
                }
            });
        } else {
            config.messages.memberStatus = bs.locale.unplugged;
        }

        // display backstage
        return _show.apply(this, arguments);
    };
    if (readOnly) {
        jQuery.each(disabled_tasks_for_nonmembers, function (i, task) {
            var taskIndex = config.backstageTasks.indexOf(task);
            if (taskIndex !== -1) {
                config.backstageTasks.splice(taskIndex, 1);
            }
        });
    }

    var tasks = config.tasks;
    var commonUrl = "/bags/common/tiddlers/%0";

    backstage.tiddlyspace = {
        locale:{
            member:"You are a member of this space.",
            nonmember:"You are not a member of this space.",
            loggedout:"You are currently logged out of TiddlySpace.",
            unplugged:"You are unplugged."
        },
        showButton:function () {
            var showBtn = $("#backstageShow")[0];
            var altText = $(showBtn).text();
            $(showBtn).empty();
            imageMacro.renderImage(showBtn, "backstage.svg",
                { altImage:commonUrl.format("backstage.png"), alt:altText});
        },
        hideButton:function () {
            var hideBtn = $("#backstageHide")[0];
            var altText = $(hideBtn).text();
            $(hideBtn).empty();
            imageMacro.renderImage(hideBtn, "close.svg",
                { altImage:commonUrl.format("close.png"), alt:altText, width:24, height:24 });
        }
    };

    var _init = backstage.init;
    backstage.init = function () {
        _init.apply(this, arguments);
        var init = function (user) {
            var bs = backstage.tiddlyspace;
            bs.showButton();
            bs.hideButton();
        };
        tweb.getUserInfo(init);
    };

    var home = config.macros.homeLink = {
        locale:{
            linkText:"your home space"
        },
        handler:function (place) {
            var container = $("<span />").appendTo(place)[0];
            tweb.getUserInfo(function (user) {
                if (!user.anon && user.name !== currentSpace) {
                    createSpaceLink(container, user.name, null, home.locale.linkText);
                }
            });
        }
    };

    config.macros.exportSpace = {
        handler:function (place, macroName, params) {
            var filename = params[0] ||
                "/tiddlers.wiki?download=%0.html".format(currentSpace);
            $('<a class="button">download</a>').// XXX: i18n
                attr("href", filename).appendTo(place);
        }
    };

}(jQuery));
//}}}
<html>
<head>
<title>Upload file to your space</title>
<style type="text/css">
form,
input,
textarea {
	border: solid 1px green;
}

textarea {
	width: 400px;
	height: 400px;
}

form.error,
textarea.error,
input.error {
	border: solid 1px red;
}

form.saving,
textarea.saving,
input.saving {
	border: solid 1px yellow;
}

</style>
<link href="/HtmlCss" type='text/css' rel='stylesheet' >
<script type='text/javascript' src='http://tiddlyspace.com/bags/ts_public/tiddlers/jquery.min.js'></script>
<script type='text/javascript' src='http://tiddlyspace.com/bags/ts_public/tiddlers/jquery-json.min.js'></script>
<script type='text/javascript' src='/TiddlySpaceCSRF'></script>
<script type='text/javascript' src='/jquery.form.js'></script>
<script type="text/javascript">
$(document).ready(function() {
	var space = window.location.hostname.split(".")[0];
	var csrf = window.getCSRFToken();
	var form = $('#upload')[0];
	$(form).attr("action", "/bags/" + space + "_public/tiddlers?csrf_token=" + csrf + "&redirect=/tiddlers");
	$(form).ajaxForm({
		beforeSubmit: function() {
			var file = $("[name=file]").val();
			var a = file.split('\\');
			file = a[a.length - 1];
			var val = $("[name=title]").val();
			if(!val) {
				$("[name=title]").val(file);
			}
		},
		success: function(a) {
			var title = $("[name=title]").val;
			$('#messageArea').html("Successfully uploaded to ");
			$("<a />").attr("href", "/" + encodeURIComponent(title)).text(title).appendTo("#messageArea");
			$("[name=title]").val("");
		},
		error: function() {
			$('#messageArea').html("Error uploading file.")
		}
	});
});
</script>
</head>
<body>
<div id="container">
	<div class="settings">
		<h1>Upload files to your space</h1>
		<div id="messageArea"></div>
		<form id="upload" method="POST" enctype="multipart/form-data">
				title: <input type="text" name="title" />
				<input type="hidden" name="tags" value="excludeLists">
				<input type="hidden" name="csrf_token" class="csrf" />
				<input type="file" name="file" />
				<input type="submit" value="upload" />
		</form>
	</div>
</div>
</body>
</html>
/***
|''Name''|RevisionsCommandPlugin|
|''Description''|provides access to tiddler revisions|
|''Author''|FND|
|''Contributors''|Martin Budden|
|''Version''|0.3.3|
|''Status''|@@beta@@|
|''Source''|http://svn.tiddlywiki.org/Trunk/association/plugins/RevisionsCommandPlugin.js|
|''CodeRepository''|http://svn.tiddlywiki.org/Trunk/association/plugins/|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.6.0|
|''Keywords''|serverSide|
!Usage
Extend [[ToolbarCommands]] with {{{revisions}}}.
!Revision History
!!v0.1 (2009-07-23)
* initial release (renamed from experimental ServerCommandsPlugin)
!!v0.2 (2010-03-04)
* suppressed wikification in diff view
!!v0.3 (2010-04-07)
* restored wikification in diff view
* added link to side-by-side diff view
!To Do
* strip server.* fields from revision tiddlers
* resolve naming conflicts
* i18n, l10n
* code sanitizing
* documentation
!Code
***/
//{{{
(function($) {

jQuery.twStylesheet(".diff { white-space: pre, font-family: monospace }",
	{ id: "diff" });

var cmd = config.commands.revisions = {
	type: "popup",
	hideShadow: true,
	text: "revisions",
	tooltip: "display tiddler revisions",
	revTooltip: "", // TODO: populate dynamically?
	loadLabel: "loading...",
	loadTooltip: "loading revision list",
	selectLabel: "select",
	selectTooltip: "select revision for comparison",
	selectedLabel: "selected",
	compareLabel: "compare",
	linkLabel: "side-by-side view",
	revSuffix: " [rev. #%0]",
	diffSuffix: " [diff: #%0 #%1]",
	dateFormat: "YYYY-0MM-0DD 0hh:0mm",
	listError: "revisions could not be retrieved",

	handlePopup: function(popup, title) {
		title = this.stripSuffix("rev", title);
		title = this.stripSuffix("diff", title);
		var tiddler = store.getTiddler(title);
		var type = _getField("server.type", tiddler);
		var adaptor = new config.adaptors[type]();
		var limit = null; // TODO: customizable
		var context = {
			host: _getField("server.host", tiddler),
			workspace: _getField("server.workspace", tiddler)
		};
		var loading = createTiddlyButton(popup, cmd.loadLabel, cmd.loadTooltip);
		var params = { popup: popup, loading: loading, origin: title };
		adaptor.getTiddlerRevisionList(title, limit, context, params, this.displayRevisions);
	},

	displayRevisions: function(context, userParams) {
		removeNode(userParams.loading);
		if(context.status) {
			var callback = function(ev) {
				var e = ev || window.event;
				var revision = resolveTarget(e).getAttribute("revision");
				context.adaptor.getTiddlerRevision(tiddler.title, revision, context,
					userParams, cmd.displayTiddlerRevision);
			};
			var table = createTiddlyElement(userParams.popup, "table");
			for(var i = 0; i < context.revisions.length; i++) {
				var tiddler = context.revisions[i];
				var row = createTiddlyElement(table, "tr");
				var timestamp = tiddler.modified.formatString(cmd.dateFormat);
				var revision = tiddler.fields["server.page.revision"];
				var cell = createTiddlyElement(row, "td");
				createTiddlyButton(cell, timestamp, cmd.revTooltip, callback, null,
					null, null, { revision: revision });
				cell = createTiddlyElement(row, "td", null, null, tiddler.modifier);
				cell = createTiddlyElement(row, "td");
				createTiddlyButton(cell, cmd.selectLabel, cmd.selectTooltip,
					cmd.revisionSelected, null, null, null,
					{ index:i, revision: revision, col: 2 });
				cmd.context = context; // XXX: unsafe (singleton)!?
			}
		} else {
			$("<li />").text(cmd.listError).appendTo(userParams.popup);
		}
	},

	revisionSelected: function(ev) {
		var e = ev || window.event;
		e.cancelBubble = true;
		if(e.stopPropagation) {
			e.stopPropagation();
		}
		var n = resolveTarget(e);
		var index = n.getAttribute("index");
		var col = n.getAttribute("col");
		while(!index || !col) {
			n = n.parentNode;
			index = n.getAttribute("index");
			col = n.getAttribute("col");
		}
		cmd.revision = n.getAttribute("revision");
		var table = n.parentNode.parentNode.parentNode;
		var rows = table.childNodes;
		for(var i = 0; i < rows.length; i++) {
			var c = rows[i].childNodes[col].firstChild;
			if(i == index) {
				if(c.textContent) {
					c.textContent = cmd.selectedLabel;
				} else {
					c.text = cmd.selectedLabel;
				}
			} else {
				if(c.textContent) {
					c.textContent = cmd.compareLabel;
				} else {
					c.text = cmd.compareLabel;
				}
				c.onclick = cmd.compareSelected;
			}
		}
	},

	compareSelected: function(ev) {
		var e = ev || window.event;
		var n = resolveTarget(e);
		var context = cmd.context;
		context.rev1 = n.getAttribute("revision");
		context.rev2 = cmd.revision;
		context.tiddler = context.revisions[n.getAttribute("index")];
		context.format = "unified";
		context.adaptor.getTiddlerDiff(context.tiddler.title, context,
			context.userParams, cmd.displayTiddlerDiffs);
	},

	displayTiddlerDiffs: function(context, userParams) {
		var tiddler = context.tiddler;
		tiddler.title += cmd.diffSuffix.format([context.rev1, context.rev2]);
		tiddler.text = "{{diff{\n" + context.diff + "\n}}}";
		tiddler.tags = ["diff"];
		tiddler.fields.doNotSave = "true"; // XXX: correct?
		if(!store.getTiddler(tiddler.title)) {
			store.addTiddler(tiddler);
		}
		var src = story.getTiddler(userParams.origin);
		var tiddlerEl = story.displayTiddler(src, tiddler);
		var uri = context.uri.replace("format=unified", "format=horizontal");
		var link = $('<a target="_blank" />').attr("href", uri).text(cmd.linkLabel);
		$(".viewer", tiddlerEl).prepend(link);
	},

	displayTiddlerRevision: function(context, userParams) {
		var tiddler = context.tiddler;
		tiddler.title += cmd.revSuffix.format([tiddler.fields["server.page.revision"]]);
		tiddler.fields.doNotSave = "true"; // XXX: correct?
		if(!store.getTiddler(tiddler.title)) {
			store.addTiddler(tiddler);
		}
		var src = story.getTiddler(userParams.origin);
		story.displayTiddler(src, tiddler);
	},

	stripSuffix: function(type, title) {
		var str = cmd[type + "Suffix"];
		var i = str.indexOf("%0");
		i = title.indexOf(str.substr(0, i));
		if(i != -1) {
			title = title.substr(0, i);
		}
		return title;
	}
};

var _getField = function(name, tiddler) {
	return tiddler.fields[name] || config.defaultCustomFields[name];
};

})(jQuery);
//}}}
/***
|''Description''|Sanitisation for dynamically pulling tiddlers into your space and displaying them|
!Notes
Works both inside and outside TiddlyWiki. Uses the HTML Sanitizer provided by the Google Caja project
(see http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer for more on this), which is licensed under
an Apache License (see http://www.apache.org/licenses/LICENSE-2.0).
!Code
***/
//{{{
(function($) {

var cleanURL = function(url) {
	var regexp = /^(?:http|https|mailto|ftp|irc|news):\/\//;
	return (regexp.test(url)) ? url : null;
};

$.sanitize = function(html) {
	return html_sanitize(html, cleanURL);
};

/*
 * HTML Sanitizer, provided by Google Caja
 */

/* Copyright Google Inc.
 * Licensed under the Apache Licence Version 2.0
 * Autogenerated at Tue May 17 17:39:24 BST 2011
 * @provides html4
 */var html4={};html4.atype={NONE:0,URI:1,URI_FRAGMENT:11,SCRIPT:2,STYLE:3,ID:4,IDREF:5,IDREFS:6,GLOBAL_NAME:7,LOCAL_NAME:8,CLASSES:9,FRAME_TARGET:10},html4.ATTRIBS={"*::class":9,"*::dir":0,"*::id":4,"*::lang":0,"*::onclick":2,"*::ondblclick":2,"*::onkeydown":2,"*::onkeypress":2,"*::onkeyup":2,"*::onload":2,"*::onmousedown":2,"*::onmousemove":2,"*::onmouseout":2,"*::onmouseover":2,"*::onmouseup":2,"*::style":3,"*::title":0,"a::accesskey":0,"a::coords":0,"a::href":1,"a::hreflang":0,"a::name":7,"a::onblur":2,"a::onfocus":2,"a::rel":0,"a::rev":0,"a::shape":0,"a::tabindex":0,"a::target":10,"a::type":0,"area::accesskey":0,"area::alt":0,"area::coords":0,"area::href":1,"area::nohref":0,"area::onblur":2,"area::onfocus":2,"area::shape":0,"area::tabindex":0,"area::target":10,"bdo::dir":0,"blockquote::cite":1,"br::clear":0,"button::accesskey":0,"button::disabled":0,"button::name":8,"button::onblur":2,"button::onfocus":2,"button::tabindex":0,"button::type":0,"button::value":0,"canvas::height":0,"canvas::width":0,"caption::align":0,"col::align":0,"col::char":0,"col::charoff":0,"col::span":0,"col::valign":0,"col::width":0,"colgroup::align":0,"colgroup::char":0,"colgroup::charoff":0,"colgroup::span":0,"colgroup::valign":0,"colgroup::width":0,"del::cite":1,"del::datetime":0,"dir::compact":0,"div::align":0,"dl::compact":0,"font::color":0,"font::face":0,"font::size":0,"form::accept":0,"form::action":1,"form::autocomplete":0,"form::enctype":0,"form::method":0,"form::name":7,"form::onreset":2,"form::onsubmit":2,"form::target":10,"h1::align":0,"h2::align":0,"h3::align":0,"h4::align":0,"h5::align":0,"h6::align":0,"hr::align":0,"hr::noshade":0,"hr::size":0,"hr::width":0,"iframe::align":0,"iframe::frameborder":0,"iframe::height":0,"iframe::marginheight":0,"iframe::marginwidth":0,"iframe::width":0,"img::align":0,"img::alt":0,"img::border":0,"img::height":0,"img::hspace":0,"img::ismap":0,"img::name":7,"img::src":1,"img::usemap":11,"img::vspace":0,"img::width":0,"input::accept":0,"input::accesskey":0,"input::align":0,"input::alt":0,"input::autocomplete":0,"input::checked":0,"input::disabled":0,"input::ismap":0,"input::maxlength":0,"input::name":8,"input::onblur":2,"input::onchange":2,"input::onfocus":2,"input::onselect":2,"input::readonly":0,"input::size":0,"input::src":1,"input::tabindex":0,"input::type":0,"input::usemap":11,"input::value":0,"ins::cite":1,"ins::datetime":0,"label::accesskey":0,"label::for":5,"label::onblur":2,"label::onfocus":2,"legend::accesskey":0,"legend::align":0,"li::type":0,"li::value":0,"map::name":7,"menu::compact":0,"ol::compact":0,"ol::start":0,"ol::type":0,"optgroup::disabled":0,"optgroup::label":0,"option::disabled":0,"option::label":0,"option::selected":0,"option::value":0,"p::align":0,"pre::width":0,"q::cite":1,"select::disabled":0,"select::multiple":0,"select::name":8,"select::onblur":2,"select::onchange":2,"select::onfocus":2,"select::size":0,"select::tabindex":0,"table::align":0,"table::bgcolor":0,"table::border":0,"table::cellpadding":0,"table::cellspacing":0,"table::frame":0,"table::rules":0,"table::summary":0,"table::width":0,"tbody::align":0,"tbody::char":0,"tbody::charoff":0,"tbody::valign":0,"td::abbr":0,"td::align":0,"td::axis":0,"td::bgcolor":0,"td::char":0,"td::charoff":0,"td::colspan":0,"td::headers":6,"td::height":0,"td::nowrap":0,"td::rowspan":0,"td::scope":0,"td::valign":0,"td::width":0,"textarea::accesskey":0,"textarea::cols":0,"textarea::disabled":0,"textarea::name":8,"textarea::onblur":2,"textarea::onchange":2,"textarea::onfocus":2,"textarea::onselect":2,"textarea::readonly":0,"textarea::rows":0,"textarea::tabindex":0,"tfoot::align":0,"tfoot::char":0,"tfoot::charoff":0,"tfoot::valign":0,"th::abbr":0,"th::align":0,"th::axis":0,"th::bgcolor":0,"th::char":0,"th::charoff":0,"th::colspan":0,"th::headers":6,"th::height":0,"th::nowrap":0,"th::rowspan":0,"th::scope":0,"th::valign":0,"th::width":0,"thead::align":0,"thead::char":0,"thead::charoff":0,"thead::valign":0,"tr::align":0,"tr::bgcolor":0,"tr::char":0,"tr::charoff":0,"tr::valign":0,"ul::compact":0,"ul::type":0},html4.eflags={OPTIONAL_ENDTAG:1,EMPTY:2,CDATA:4,RCDATA:8,UNSAFE:16,FOLDABLE:32,SCRIPT:64,STYLE:128},html4.ELEMENTS={a:0,abbr:0,acronym:0,address:0,applet:16,area:2,b:0,base:18,basefont:18,bdo:0,big:0,blockquote:0,body:49,br:2,button:0,canvas:0,caption:0,center:0,cite:0,code:0,col:2,colgroup:1,dd:1,del:0,dfn:0,dir:0,div:0,dl:0,dt:1,em:0,fieldset:0,font:0,form:0,frame:18,frameset:16,h1:0,h2:0,h3:0,h4:0,h5:0,h6:0,head:49,hr:2,html:49,i:0,iframe:4,img:2,input:2,ins:0,isindex:18,kbd:0,label:0,legend:0,li:1,link:18,map:0,menu:0,meta:18,nobr:0,noframes:20,noscript:20,object:16,ol:0,optgroup:0,option:1,p:1,param:18,pre:0,q:0,s:0,samp:0,script:84,select:0,small:0,span:0,strike:0,strong:0,style:148,sub:0,sup:0,table:0,tbody:1,td:1,textarea:8,tfoot:1,th:1,thead:1,title:24,tr:1,tt:0,u:0,ul:0,"var":0},html4.ueffects={NOT_LOADED:0,SAME_DOCUMENT:1,NEW_DOCUMENT:2},html4.URIEFFECTS={"a::href":2,"area::href":2,"blockquote::cite":0,"body::background":1,"del::cite":0,"form::action":2,"img::src":1,"input::src":1,"ins::cite":0,"q::cite":0},html4.ltypes={UNSANDBOXED:2,SANDBOXED:1,DATA:0},html4.LOADERTYPES={"a::href":2,"area::href":2,"blockquote::cite":2,"body::background":1,"del::cite":2,"form::action":2,"img::src":1,"input::src":1,"ins::cite":2,"q::cite":2};var html=function(a){function x(b,c,d){var e=[];w(function(b,e){for(var f=0;f<e.length;f+=2){var g=e[f],h=e[f+1],i=null,j;if((j=b+"::"+g,a.ATTRIBS.hasOwnProperty(j))||(j="*::"+g,a.ATTRIBS.hasOwnProperty(j)))i=a.ATTRIBS[j];if(i!==null)switch(i){case a.atype.NONE:break;case a.atype.SCRIPT:case a.atype.STYLE:h=null;break;case a.atype.ID:case a.atype.IDREF:case a.atype.IDREFS:case a.atype.GLOBAL_NAME:case a.atype.LOCAL_NAME:case a.atype.CLASSES:h=d?d(h):h;break;case a.atype.URI:h=c&&c(h);break;case a.atype.URI_FRAGMENT:h&&"#"===h.charAt(0)?(h=d?d(h):h,h&&(h="#"+h)):h=null;break;default:h=null}else h=null;e[f+1]=h}return e})(b,e);return e.join("")}function w(b){var c,d;return v({startDoc:function(a){c=[],d=!1},startTag:function(e,f,g){if(!d){if(!a.ELEMENTS.hasOwnProperty(e))return;var h=a.ELEMENTS[e];if(h&a.eflags.FOLDABLE)return;if(h&a.eflags.UNSAFE){d=!(h&a.eflags.EMPTY);return}f=b(e,f);if(f){h&a.eflags.EMPTY||c.push(e),g.push("<",e);for(var i=0,j=f.length;i<j;i+=2){var k=f[i],l=f[i+1];l!==null&&l!==void 0&&g.push(" ",k,'="',r(l),'"')}g.push(">")}}},endTag:function(b,e){if(d)d=!1;else{if(!a.ELEMENTS.hasOwnProperty(b))return;var f=a.ELEMENTS[b];if(!(f&(a.eflags.UNSAFE|a.eflags.EMPTY|a.eflags.FOLDABLE))){var g;if(f&a.eflags.OPTIONAL_ENDTAG)for(g=c.length;--g>=0;){var h=c[g];if(h===b)break;if(!(a.ELEMENTS[h]&a.eflags.OPTIONAL_ENDTAG))return}else for(g=c.length;--g>=0;)if(c[g]===b)break;if(g<0)return;for(var i=c.length;--i>g;){var h=c[i];a.ELEMENTS[h]&a.eflags.OPTIONAL_ENDTAG||e.push("</",h,">")}c.length=g,e.push("</",b,">")}}},pcdata:function(a,b){d||b.push(a)},rcdata:function(a,b){d||b.push(a)},cdata:function(a,b){d||b.push(a)},endDoc:function(a){for(var b=c.length;--b>=0;)a.push("</",c[b],">");c.length=0}})}function v(c){return function(d,e){d=String(d);var f=null,g=!1,h=[],j=void 0,l=void 0,m=void 0;c.startDoc&&c.startDoc(e);while(d){var n=d.match(g?t:u);d=d.substring(n[0].length);if(g){if(n[1]){var o=b(n[1]),p;if(n[2]){var q=n[3];switch(q.charCodeAt(0)){case 34:case 39:q=q.substring(1,q.length-1)}p=k(i(q))}else p=o;h.push(o,p)}else if(n[4]){l!==void 0&&(m?c.startTag&&c.startTag(j,h,e):c.endTag&&c.endTag(j,e));if(m&&l&(a.eflags.CDATA|a.eflags.RCDATA)){f===null?f=b(d):f=f.substring(f.length-d.length);var r=f.indexOf("</"+j);r<0&&(r=d.length),l&a.eflags.CDATA?c.cdata&&c.cdata(d.substring(0,r),e):c.rcdata&&c.rcdata(s(d.substring(0,r)),e),d=d.substring(r)}j=l=m=void 0,h.length=0,g=!1}}else if(n[1])c.pcdata&&c.pcdata(n[0],e);else if(n[3])m=!n[2],g=!0,j=b(n[3]),l=a.ELEMENTS.hasOwnProperty(j)?a.ELEMENTS[j]:void 0;else if(n[4])c.pcdata&&c.pcdata(n[4],e);else if(n[5]&&c.pcdata)switch(n[5]){case"<":c.pcdata("&lt;",e);break;case">":c.pcdata("&gt;",e);break;default:c.pcdata("&amp;",e)}}c.endDoc&&c.endDoc(e)}}function s(a){return a.replace(m,"&amp;$1").replace(n,"&lt;").replace(o,"&gt;")}function r(a){return a.replace(l,"&amp;").replace(n,"&lt;").replace(o,"&gt;").replace(p,"&#34;").replace(q,"&#61;")}function k(a){return a.replace(j,g)}function i(a){return a.replace(h,"")}function g(a,b){return f(b)}function f(a){a=b(a);if(c.hasOwnProperty(a))return c[a];var f=a.match(d);if(f)return String.fromCharCode(parseInt(f[1],10));if(!!(f=a.match(e)))return String.fromCharCode(parseInt(f[1],16));return""}var b;"script"==="SCRIPT".toLowerCase()?b=function(a){return a.toLowerCase()}:b=function(a){return a.replace(/[A-Z]/g,function(a){return String.fromCharCode(a.charCodeAt(0)|32)})};var c={lt:"<",gt:">",amp:"&",nbsp:"240",quot:'"',apos:"'"},d=/^#(\d+)$/,e=/^#x([0-9A-Fa-f]+)$/,h=/\0/g,j=/&(#\d+|#x[0-9A-Fa-f]+|\w+);/g,l=/&/g,m=/&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi,n=/</g,o=/>/g,p=/\"/g,q=/\=/g,t=new RegExp("^\\s*(?:(?:([a-z][a-z-]*)(\\s*=\\s*(\"[^\"]*\"|'[^']*'|(?=[a-z][a-z-]*\\s*=)|[^>\"'\\s]*))?)|(/?>)|[\\s\\S][^a-z\\s>]*)","i"),u=new RegExp("^(?:&(\\#[0-9]+|\\#[x][0-9a-f]+|\\w+);|<!--[\\s\\S]*?-->|<!\\w[^>]*>|<\\?[^>*]*>|<(/)?([a-z][a-z0-9]*)|([^<&>]+)|([<&>]))","i");return{escapeAttrib:r,makeHtmlSanitizer:w,makeSaxParser:v,normalizeRCData:s,sanitize:x,unescapeEntities:k}}(html4),html_sanitize=html.sanitize

// stop here if we're not in TiddlyWiki
// XXX: is this the correct way of checking for TiddlyWiki?
if (!window.TiddlyWiki || !window.store || !store instanceof TiddlyWiki) {
	return;
}

var tiddlyspace = config.extensions.tiddlyspace;

var _subWikify = Wikifier.prototype.subWikify;

var cleanedTitle = 'This section has been cleaned of any potentially harmful code';

var replaceFunctions = {
	html: function(w) {
		var sanitizedHTML, spanEl;
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			sanitizedHTML = $.sanitize(lookaheadMatch[1]);
			spanEl = createTiddlyElement(w.output, 'span', null, 'sanitized');
			spanEl.innerHTML = sanitizedHTML;
			spanEl.setAttribute('title', cleanedTitle);
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	},
	customFormat: function(w) {
		switch(w.matchText) {
			case '@@':
				var e = createTiddlyElement(w.output, 'span');
				var styles = config.formatterHelpers.inlineCssHelper(w);
				if (styles.length === 0) {
					e.className = 'marked';
				}
				w.subWikifyTerm(e, /(@@)/mg);
				break;
			case '{{':
				var lookaheadRegExp = /\{\{[\s]*([\w]+[\s\w]*)[\s]*\{(\n?)/mg;
				lookaheadRegExp.lastIndex = w.matchStart;
				var lookaheadMatch = lookaheadRegExp.exec(w.source);
				if(lookaheadMatch) {
					w.nextMatch = lookaheadRegExp.lastIndex;
					e = createTiddlyElement(w.output,lookaheadMatch[2] == "\n" ? "div" : "span",null,lookaheadMatch[1]);
					w.subWikifyTerm(e,/(\}\}\})/mg);
				}
				break;
		}
	}
};

Wikifier.prototype.subWikify = function(output, terminator) {
	var tid = this.tiddler,
		spaceName = tiddlyspace.currentSpace.name,
		tidSpace, recipeName, stripped;
	try {
		recipeName = tid.fields['server.recipe'] ||
			tid.fields['server.workspace'];
		tidSpace = tiddlyspace.resolveSpaceName(recipeName);
		if (tidSpace !== spaceName) {
			// external tiddler, so replace dangerous formatters
			stripped = stripHTML(tid, this.formatter);
		}
	} catch(e) {
		// do nothing. There's no tiddler, so assume it's safe (?!?!?)
	}

	_subWikify.apply(this, arguments);

	if (stripped) {
		// change back to the original function
		unstripHTML(stripped, this.formatter);
	}
};

// replace potentially unsafe formatters with versions that strip bad HTML/CSS
var stripHTML = function(tid, formatter) {
	var popped = {}, _handler;
	for (var i = 0; i < formatter.formatters.length; i++) {
		var f = formatter.formatters[i];
		if (replaceFunctions[f.name]) {
			_handler = f.handler;
			popped[f.name] = _handler;
			f.handler = replaceFunctions[f.name];
		}
	};

	return popped;
};

// put the original formatters back where they belong
var unstripHTML = function(stripped, formatter) {
	for (var i = 0; i < formatter.formatters.length; i++) {
		var f = formatter.formatters[i];
		if (stripped[f.name]) {
			f.handler = stripped[f.name];
		}
	};
};

})(jQuery);
//}}}
iVBORw0KGg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ru4XeGKarTrXsfrTkbA1Zhl8hwIOwWu/CZI0cskDftWJ6bgzPT0yIGcrPpcvYYelB3UxZ8sOEWwHPlphOoKrznIbgAp+XlZEeA54KeK4MUrpwaNeimhtqNl4Wd4hCaTgDieTWfX7T607M+NOn2wJzs1YZHapxx4Iza1XwCc8+IiMmCh62JSTcAgRTH7303KqI4G0wnACcRPEBg4VXRMzML5xTqerl+M7yTmlNMJwDwe8GMiA8iTWjh6beXH1YMnQiV32rddAJMNz6FHfD0DQ5R/mzIC08VIAXnlx5sGDjuw2oxkkk5yPZ/2PEYlsnfMMOKYrVQCJmYv0bD8v8eUuTmxQDF25YUAhxES3tnOWH4CUZYFTxqjWLCPmiorflvvACX6p80AktNbFa76T5gFrBY9SQlF+KTXz58shZesLdD/n8XY9QFT0AftY6dOtLU1MRDqWklKSbkPHziIKTSu2SrRVfSbLIe0AzNp/Kn8/8MBNUt217cJn7NSoCW6TvgPHTyMbgy7soszEFZJfnzzybS7LgHTbiGHyyTFR6FXkkAq3CI6T5AJPy0kmo1ADx/oF2YNC3PjuCPXymfXRCaUDGdAOQRP1QyUvkvkBHwrBmpXGa/cPBj8f0yYsTSAtMJwJTXDE0X5kIG3AWgBOXJmZh/xFuKgukE4AeCT/zuaaRO+78zN5BC0zfcOghPVTfF+AD8HQ3iD9MJ6D79NTCfwVHnFWNqaBz5gIzn+gQaOd9vUB0eC2nwGTGUxKRJCaMX/3RyuaTgw+AGDoDFF4n/dvC5StWn7npua09iUMWjkkJgfirnodZ0gu1Vs17iuvdl8+4A8/r5/6QSCJ0oWfX/A3UKXhQwWVptAAAAAElFTkSuQmCC
<!--{{{-->
<link rel="shortcut icon" href="/recipes/familytree_public/tiddlers/favicon.ico" />
<link href="/bags/familytree_public/tiddlers.atom?select=tag:!excludeLists"
	rel="alternate" type="application/atom+xml" title="familytree's public feed" />
<!--}}}-->
<<familytreelist filter:"[tag[place]]">>
iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAYAAAA6GuKaAA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L92E/1KCVpz+iXz/D36BLy8VVzwEAAAAAElFTkSuQmCC
/***
|''Name''|BinaryTiddlersPlugin|
|''Description''|renders base64-encoded binary tiddlers as images or links|
|''Author''|FND|
|''Version''|0.3.2|
|''Status''|@@beta@@|
|''Source''|http://svn.tiddlywiki.org/Trunk/association/plugins/BinaryTiddlersPlugin.js|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.5|
!Code
***/
//{{{
(function($) {

"use strict";

var ctfield = "server.content-type";

var plugin = config.extensions.BinaryTiddlersPlugin = {
	isWikiText: function(tiddler) {
		var ctype = tiddler.fields[ctfield];
		if(ctype) {
			if (ctype === 'text/x-tiddlywiki') {
				return true;
			}
			return !this.isBinary(tiddler) && !this.isTextual(ctype);
		} else {
			return true;
		}
	},
	// NB: pseudo-binaries are considered non-binary here
	isBinary: function(tiddler) {
		var ctype = tiddler.fields[ctfield];
		return ctype ? !this.isTextual(ctype) : false;
	},
	isTextual: function(ctype) {
		return ctype.indexOf("text/") === 0
			|| this.endsWith(ctype, "+xml")
			|| ctype === 'application/json'
			|| ctype === 'application/javascript';
	},
	endsWith: function(str, suffix) {
		return str.length >= suffix.length &&
			str.substr(str.length - suffix.length) === suffix;
	},
	isLink: function(tiddler) {
		return this.isBinary(tiddler) && tiddler.text.indexOf("<html>") !== -1;
	}
};

// Disable edit for linked tiddlers (for now)
// This will be changed to a GET then PUT
config.commands.editTiddler.isEnabled = function(tiddler) {
    var existingTest = config.commands.editTiddler.isEnabled;
    if (existingTest) {
        return existingTest && !plugin.isLink(tiddler);
    } else {
        return !plugin.isLink(tiddler);
    }
};

// hijack text viewer to add special handling for binary tiddlers
var _view = config.macros.view.views.wikified;
config.macros.view.views.wikified = function(value, place, params, wikifier,
		paramString, tiddler) {
	var ctype = tiddler.fields["server.content-type"];
	if(params[0] === "text" && ctype && ctype !== 'text/x-tiddlywiki' &&
			!tiddler.tags.contains("systemConfig") && !plugin.isLink(tiddler)) {
		var el;
		if(plugin.isBinary(tiddler)) {
			var uri = "data:%0;base64,%1".format([ctype, tiddler.text]); // TODO: fallback for legacy browsers
			if(ctype.indexOf("image/") === 0) {
				el = $("<img />").attr("alt", tiddler.title).attr("src", uri);
			} else {
				el = $("<a />").attr("href", uri).text(tiddler.title);
			}
		} else {
			el = $("<pre />").text(tiddler.text);
		}
		el.appendTo(place);
	} else {
		_view.apply(this, arguments);
	}
};

// hijack edit macro to disable editing of binary tiddlers' body
var _editHandler = config.macros.edit.handler;
config.macros.edit.handler = function(place, macroName, params, wikifier,
		paramString, tiddler) {
	if(params[0] === "text" && plugin.isBinary(tiddler)) {
		return false;
	} else {
		_editHandler.apply(this, arguments);
	}
};

// hijack autoLinkWikiWords to ignore binary tiddlers
var _autoLink = Tiddler.prototype.autoLinkWikiWords;
Tiddler.prototype.autoLinkWikiWords = function() {
	return plugin.isWikiText(this) ? _autoLink.apply(this, arguments) : false;
};

}(jQuery));
//}}}
/***
|''Name''|ImageMacroPlugin|
|''Version''|0.9.4|
|''Description''|Allows the rendering of svg images in a TiddlyWiki|
|''Author''|Osmosoft|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''Notes''|Currently only works in modern browsers (not IE)|
|''Requires''|BinaryTiddlersPlugin|
!Usage
{{{<<image SVG>>}}} will render the text of the tiddler with title SVG as an SVG image (but not in ie where it will fail silently)
!!Parameters
width/height: specify width/height parameters
link: make the image link to a given location
tiddlyLink: link to a tiddler

!Notes
Binary tiddlers in TiddlyWeb when passed through the wikifier will be shown as images.
eg. {{{<<view text wikified>>}}} on a binary tiddler will show the image.
{{{<<view fieldname image>>}}}
will render the value of the tiddler field 'fieldname' as an image. This field can contain a tid
{{{<<image SiteIcon>>}}}
will create an image tag where the tiddler has content type beginning image and not ending +xml
will attempt to create svg object in other scenarios
{{{<<image /photos/x.jpg>>}}}
will create an image tag with src /photos/x.jpg as long as there is not a tiddler called /photos/x.jpg in 
which case it will render that tiddler as an image. Note for the case of svg files it will attempt to render as an svg if possible via the image
tag. It doesn't embed the svg in the dom for security reasons as svg code can contain javascript.
!Code
***/
//{{{
(function($) {

var macro = config.macros.image = {
	shim: "/bags/common/tiddlers/shim",
	ieVersion: config.browser.isIE ? parseInt(config.browser.ieVersion[1], 10) : false,
	svgns: "http://www.w3.org/2000/svg",
	xlinkns: "http://www.w3.org/1999/xlink", 
	svgAvailable: document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"),
	_fixPrefix: 1,
	_external_cache: {},
	_image_tag_cache: {},
	_image_dimensions: {},
	locale: {
		badImage: "This image cannot be displayed."
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler){
		var imageSource = params[0];
		// collect named arguments
		var args = macro.getArguments(paramString, params);
		this.renderImage(place, imageSource, args);
	},
	init: function() {
		var startupImages = store.getTaggedTiddlers("systemImage");
		var place = $("<div />").attr("id", "systemImageArea").appendTo("body").hide()[0];
		for(var i = 0; i < startupImages.length; i++) {
			var image = startupImages[i];
			macro.renderImage(place, image.title, { idPrefix: "" });
		}
		var data = new Image();
		data.onload = function() {
			// note ie 8 only supports data uris up to 32k so cannot be relied on
			macro.supportsDataUris = this.width != 1 || this.height != 1 ? false : true;
			macro.supportsDataUris = macro.ieVersion && macro.ieVersion < 9 ? false : macro.supportsDataUris;
		};
		data.onerror = data.onload;
		data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
	},
	refreshImage: function(src) {
		var elements = macro._image_tag_cache[src] ? macro._image_tag_cache[src] : [];
		if(macro._image_dimensions[src]) {
			macro._image_dimensions[src] = false;
		}
		for(var i = 0; i < elements.length; i++) {
			var el = $(elements[i]);
			var newSrc = "%0?nocache=%1".format(src, Math.random());
			el.attr("src", newSrc); // force reload
		}
	},
	isBinaryImageType: function(contentType) {
		return (contentType && contentType.indexOf("image") === 0 &&
			contentType.indexOf("+xml") != contentType.length - 4) ? true : false;
	},
	isImageTiddler: function(tiddler) {
		return macro.isSVGTiddler(tiddler) || macro.isBinaryImageTiddler(tiddler);
	},
	isSVGTiddler: function(tiddler) {
		var type = tiddler ? tiddler.fields['server.content-type'] : false;
		return type == "image/svg+xml";
	},
	isBinaryImageTiddler: function(tiddler) {
		return macro.isBinaryImageType(tiddler.fields['server.content-type']);
	},
	renderImage: function(place, imageSource, options) {
		var imageTiddler = store.getTiddler(imageSource);
		var container;
		var classes = ["image"];
		if(options.link) {
			classes = classes.concat(["imageLink", "externalLink"]);
			container = $("<a />").attr("href", options.link).appendTo(place)[0];
		} else if(options.tiddlyLink) {
			classes.push("imageLink");
			container = createTiddlyLink(place, options.tiddlyLink, false);
		} else {
			container = $("<span />").appendTo(place)[0];
		}
		$(container).addClass(classes.join(" "));

		options = options ? options : {};
		if(imageTiddler && macro.isBinaryImageTiddler(imageTiddler)) { // handle the case where we have an image url
			return macro._renderBinaryImageTiddler(container, imageTiddler, options);
		} else if(imageTiddler){ // handle the case where we have a tiddler
			return macro._renderSVGTiddler(container, imageTiddler, options);
		} else { // we have a string representing a url
			return macro._renderBinaryImageUrl(container, imageSource, options);
		}
	},
	_renderAlternateText: function(container, options) {
		var img;
		var src = options.src || "";
		if(options.width && options.height) {
			img = $("<img />").attr("src", src).addClass("svgImageText").attr("width", options.width).
				attr("height", options.height).appendTo(container);
		}
		var alt = options.alt;
		if(img && alt) {
			img.attr("alt", alt).attr("title", alt);
		} else if(alt) {
			$(container).addClass("svgImageText").text(alt);
		}
		macro._image_tag_cache[src] = img;
	},
	_renderSVGTiddler: function(place, tiddler, options) {
		if(!options) {
			options = {};
		}
		merge(options, { tiddler: tiddler, fix: true});

		if(macro.svgAvailable) {
			this._importSVG(place, options); // display the svg
		} else if(options.altImage) {
			var image = options.altImage;
			delete options.altImage;
			this._renderBinaryImageUrl(place, image, options);
		} else {
			this._renderAlternateText(place, options); // instead of showing the image show the alternate text.
		}
	},
	_renderBinaryImageTiddler: function(place, tiddler, options) {
		var resourceURI;
		var fields = tiddler.fields;
		if(fields["server.type"] == "tiddlyweb") { // construct an accurate url for the resource
			resourceURI = "%0/%1/tiddlers/%2".format(config.defaultCustomFields["server.host"],
				fields["server.workspace"], encodeURI(fields["server.title"]));
		} else { // guess the url for the resource
			resourceURI = tiddler.title;
		}
		var ctype = fields["server.content-type"] || tiddler.type;
		var text = tiddler.text;
		if(macro.supportsDataUris && ctype && text.indexOf("<html") == -1) {
			var uri = "data:%0;base64,%1".format(ctype, text);
			options.src = resourceURI;
			return macro._renderBinaryImageUrl(place, uri, options);
		} else if(options.src) {
			return macro._renderBinaryImageUrl(place, options.src, options);
		} else {
			return macro._renderBinaryImageUrl(place, resourceURI, options);
		}
	},
	_renderImageTag: function(container, src, width, height, options) {
		var img;
		img = $("<img />").appendTo(container);
		if(height) {
			img.attr("height", height);
		}
		if(width) {
			img.attr("width", width);
		}
		if(macro.ieVersion && macro.ieVersion < 7 && macro.shim && options.ie6png) {
			$(img).css({width: userW, height: userH,
					filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='%0', sizingMethod='scale')".format(src)
				}).attr("src", macro.shim);
		} else {
			img.attr("src", src);
		}
		if(!macro._image_tag_cache[options.srcUrl]) {
			macro._image_tag_cache[options.srcUrl] = [];
		}
		img = $(img).addClass(options.imageClass)[0];
		macro._image_tag_cache[options.srcUrl].push(img);
		return img;
	},
	_getDimensions: function(realDimensions, reqDimensions, preserve) {
		var w = realDimensions.width;
		var h = realDimensions.height;
		var reqh = reqDimensions.height;
		var reqw = reqDimensions.width;
		var finalw = w, finalh = h;
		var ratiow = reqw / w, ratioh = reqh / h;
		var scaledw = ratioh * w;
		var scaledh = ratiow * h;
		if(!reqw && reqh) {
			finalw = scaledw;
			finalh = reqh;
		} else if(reqw && !reqh) {
			finalw = reqw;
			finalh = scaledh;
		} else if(reqh && reqw) {
			var preserveWidth = w > h ? true : false;
			if(preserve) {
				if(preserveWidth && scaledh < reqh) {
					finalh = scaledh;
					finalw = reqw;
				} else {
					finalh = reqh;
					finalw = scaledw;
				}
			} else {
				finalw = reqw;
				finalh = reqh;
			}
		}
		return { width: parseInt(finalw, 10), height: parseInt(finalh, 10) };
	},
	_renderBinaryImageUrl: function(container, src, options) {
		var srcUrl = options.src ? options.src : src;
		srcUrl = srcUrl.indexOf("/") === -1 ? "/%0".format(srcUrl) : srcUrl; // for IE. 
		var image_dimensions = macro._image_dimensions[srcUrl];
		var image = new Image(); // due to weird scaling issues where you use just a width or just a height
		var createImageTag = function(dimensions, error) {
			if(error) {
				var altImage = options.altImage;
				if(altImage) {
					delete options.altImage;
					macro._renderBinaryImageUrl(container, altImage, options);
				} else {
					options.src = src;
					macro._renderAlternateText(container, options);
				}
			} else {
				var dim = macro._getDimensions(dimensions, { 
					width: options.width, height: options.height }, options.preserveAspectRatio);
				options.srcUrl = srcUrl;
				macro._renderImageTag(container, src, dim.width, dim.height, options);
			}
		};

		if(!image_dimensions) {
			image.onload = function() {
				var dimensions = { width: image.width, height: image.height};
				macro._image_dimensions[srcUrl] = dimensions;
				createImageTag(dimensions);
			};
			image.onerror = function() {
				createImageTag(null, true);
			};
			image.src = src;
		} else {
			createImageTag(image_dimensions);
		}
	},
	_generateIdPrefix: function(){
		return "twsvgfix_" + (this._fixPrefix++).toString() + "_";
	},
	_fixSVG: function(childNodes, idPrefix) {
		var urlPattern = /url\(\#([^\)]*)\)*/ig;
		var fixes = [
		{ attr: "id", pattern: /^(.*)$/ig },
		{ attr: "href", namespace: macro.xlinkns, pattern: /^#(.*)$/ig }
		];
		var url_fixes = ["filter", "fill", "mask", "stroke", "style"];
		for(var i = 0; i < url_fixes.length; i++) {
			fixes.push({ attr: url_fixes[i], pattern: urlPattern });
		}
		for(var t = 0; t < childNodes.length; t++) {
			var node = childNodes[t];
			for(var a = 0; a < fixes.length; a++) {
				var fix = fixes[a];
				var attr = fix.attr;
				var ns = fix.namespace || "";
				if(node.hasAttributeNS && node.hasAttributeNS(ns, attr)) {
					var v = node.getAttributeNS(ns, attr);
					fix.pattern.lastIndex = 0;
					var match = fix.pattern.exec(v);
					if(match) {
						// Make sure replacement string doesn't contain any single dollar signs
						var toReplace = match[1];
						if(toReplace.indexOf(idPrefix) !== 0 && toReplace.indexOf("twglobal_") !== 0) {
							var replacement = (idPrefix + toReplace).replace("$", "$$$$"); 
							v = v.replace(match[1], replacement);
						}
						node.setAttributeNS(ns, attr,v);
					}
				}
			}
			var children = node.childNodes;
			if(children.length > 0) {
				this._fixSVG(children, idPrefix);
			}
		}
	},
	_importSVG: function(place, options){
		options = options ? options : {};
		var svgDoc, tiddlerText = options.tiddler.text;
		if (window.DOMParser) {
			svgDoc = new DOMParser().parseFromString(tiddlerText, "application/xml").documentElement;
			var idPrefix = options.idPrefix || this._generateIdPrefix();
			this._fixSVG([svgDoc], idPrefix);
			var el = document.importNode(svgDoc, true);
			var svgHolder = document.createElementNS(macro.svgns,"svg");
			var width = options.width;
			var height = options.height;
			if(width || height) {
				if(width && height) { // set view box of containing svg element based on the svg viewbox and width and height.
					var viewBox = el.getAttribute("viewBox");
					var topLeft = "0 0";
					if(viewBox) {
						topLeft = viewBox.replace(/([0-9]*) +([0-9]*) +([0-9]*) +([0-9]*) */gi,"$1 $2");
					}
					svgHolder.setAttributeNS(macro.svgns, "viewBox", "0 0 %0 %1".format(width, height));
				} else {
					if(!width) {
						width = el.getAttribute("width");
					}
					if(!height) {
						height = el.getAttribute("height");
					}
				}
				svgHolder.setAttribute("width", width);
				svgHolder.setAttribute("height", height);

				el.setAttribute("width", "100%");
				el.setAttribute("height", "100%");
				svgHolder.setAttribute("class", "svgImage svgIcon %0".format(options.imageClass || ""));
				svgHolder.appendChild(el);
				place.appendChild(svgHolder);
			}
			else {
				var existing = el.className ? el.className.baseVal : "";
				el.setAttribute("class","svgImage %0".format(existing));
				place.appendChild(el);
			}
			// if a tiddler attribute is set this is read as a link
			$("[tiddler], [tiddlyLink]", place).attr("refresh", "link").click(function(ev) {
				var tiddler = $(ev.target).attr("tiddlyLink");
				if(tiddler) {
					story.displayTiddler(ev.target, tiddler);
				}
			});
		}
	},
	getArguments: function(paramString, params) {
		var args = paramString.parseParams("name", null, true, false, true)[0];
		var options = {};
		for(var id in args) {
			if(true) {
				var p = args[id];
				if(id == "def") {
					options[id] = p;
				} else {
					options[id] = p[0];
				}
			}
		}
		var width = isNaN(params[1]) ? false : parseInt(params[1], 10);
		var height = isNaN(params[2]) ? false : parseInt(params[2], 10);

		options.width = macro.lookupArgument(options, "width", width);
		options.height = macro.lookupArgument(options, "height", height);
		options.preserveAspectRatio = args.preserveAspectRatio && 
			args.preserveAspectRatio[0] == "yes" ? true : false;
		options.tiddlyLink = macro.lookupArgument(options, "tiddlyLink", false);
		options.link = macro.lookupArgument(options, "link", false);
		return options;
	},
	lookupArgument: function(args, id, ifEmpty) {
		return args[id] ? args[id] : ifEmpty;
	}
};

// update views
var _oldwikifiedview = config.macros.view.views.wikified;
// update wikifier to check tiddler type before rendering
merge(config.macros.view.views, {
	wikified: function(value, place, params, wikifier, paramString, tiddler) {
		if(macro.isImageTiddler(tiddler) && params[0] == "text") {
			var newplace = $("<div />").addClass("wikifiedImage").appendTo(place)[0];
			macro.renderImage(newplace, tiddler.title, { alt: macro.locale.badImage });
		} else {
			_oldwikifiedview.apply(this, arguments);
		}
	},
	image: function(value, place, params, wikifier, paramString, tiddler) {
		// a field can point to another tiddler whereas text is the current tiddler.
		var title = params[0] == "text" ? tiddler.title : value;
		var args = macro.getArguments(paramString, params);
		macro.renderImage(place, title, args);
	}
});
config.shadowTiddlers.StyleSheetImageMacro = [".wikifiedImage svg, .wikifiedImage .image { width: 80%; }",
	".svgImageText { background-color:[[ColorPalette::Error]]; color:#ddd; display: inline-block; }",
	"span.svgImageText { display: inline-block; overflow: hidden; }"
].join("");
store.addNotification("StyleSheetImageMacro", refreshStyles);

})(jQuery);
//}}}
/*{{{*/
Background: #dcf8dd
Foreground: #062207
PrimaryPale: #98ec9c
PrimaryLight: #48de50
PrimaryMid: #1eab25
PrimaryDark: #020d02
SecondaryPale: #ec9898
SecondaryLight: #de4848
SecondaryMid: #ab1e1e
SecondaryDark: #0d0202
TertiaryPale: #E1C5ED
TertiaryLight: #5748de
TertiaryMid: #2c1eab
TertiaryDark: #03020d
Error: #f88
ColorPaletteParameters: HSL([123|57], [0.7],[0.030142860021442175|0.7631902012508363])
/*}}}*/
Unless you're delighted with the default theme you can make some quick changes by generating a new random color palette, hit this button to cycle through some alternatives.

<<RandomColorPaletteButton saturation_pale:0.67 saturation_light:0.53
saturation_mid:0.43 saturation_dark:0.06 pale:0.99 light:0.85 mid:0.5 dark:0.31>>

You can also change the look and feel completely by installing a new theme. To do this, find one you like in the @themes space, note down the name, and include it in this space by going to the space menu. You can reach the space menu by clicking on the blue and pink circle at the top-right of the page and chooshing "THIS SPACE". Here are a few to check out:
* @pip
* @caspian-ii
* @basalt
* @simplicity
* @cheesecake
* @jelly-doughnut

(//Note that if you are using a custom TiddlySpace install, these themes may not be present.//)
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->

<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   version="1.1"
   width="14pt"
   height="14pt"
   viewBox="918 510 14 14"
   id="svg3070">
  <metadata
     id="metadata3089">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <defs
     id="defs3072">
    <radialGradient
       cx="0"
       cy="0"
       r="1"
       id="Gradient"
       gradientUnits="userSpaceOnUse">
      <stop
         id="stop3075"
         style="stop-color:#ffffff;stop-opacity:1"
         offset="0" />
      <stop
         id="stop3077"
         style="stop-color:#2b2b2b;stop-opacity:1"
         offset="1" />
    </radialGradient>
    <radialGradient
       id="Obj_Gradient"
       xlink:href="#Gradient"
       gradientTransform="matrix(11.473944,0,0,11.473944,922.3752,513.7837)" />
  </defs>
  <g
     id="g3080"
     style="fill:none;stroke:none">
    <g
       id="g3082">
      <path
         d="m 929.6952,512.9018 c -2.5384,-2.53843 -6.654,-2.53843 -9.1924,0 -2.5384,2.5384 -2.5384,6.654 0,9.19238 2.5384,2.53839 6.654,2.53839 9.1924,0 2.5384,-2.53838 2.5384,-6.65398 0,-9.19238 m -4.5962,2.8407 2.07733,-2.07734 1.75547,1.75549 -2.0773,2.07735 2.0773,2.07732 -1.75547,1.75548 -2.07733,-2.07732 -2.07733,2.07732 -1.75547,-1.75548 2.0773,-2.07732 -2.0773,-2.07735 1.75547,-1.75549 z"
         id="path3084"
         style="fill:url(#Obj_Gradient)" />
      <path
         d="m 927.61447,515.38354 a 4.51205,4.2590378 0 1 1 -9.0241,0 4.51205,4.2590378 0 1 1 9.0241,0 z"
         transform="matrix(1.0218069,0,0,1.0462046,-18.063694,-21.648443)"
         id="path2394"
         style="fill:#000000;fill-opacity:0;fill-rule:evenodd;stroke:none;stroke-width:5;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
    </g>
  </g>
</svg>
iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAYAAAA6GuKaAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAEZ0FNQQAAsY58+1GTAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwAACBpJREFUeNrtWXtMW+cVP9+1r40dwHZ4+RkegULI0hI1qzqVrHFa7a+mSxq1atU8iNRK09ZN3XtJK41oTRtN+yPVpHWTOmUeaH901bKu/+yPdiYNWjo1bR48mgLhEcAYA8EYQ/CD++18n7nXBoyvHQj/bEe63HvN9/h95zvn951zLsD/ZXOErHeA1/7s3U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gI19pT18/v1LryhslzOGvXOtQ7BjPv1bRAafvqWr6yd89/Y2Hm3pZJZMtkFU2AxNTYDYX8orneoWddp3dN5EphlKUQd/VOYWXM30ZyCqCf93jfVIS6HlYSnnYoVKxzQmsqG4w5OUMlgEcHRtHXxlYxk7Ixz88c+SJcxvyJUCui4iS9A4l5KnUWWylxcRus8FWi0k1qA+H52DE50fnDiwHy7+9kGeRudqzKg/nqqVTLd6X0K1fS/32IlelthgMhCXGLM9kGQcL4Fk8PDe/wIOfNCFvHBniN4zW0rHEhoHmhUqvVxsdhecxWDpOKDyZcyGdaRZIK8Zvfzh71N13D/3XJ9xsqHSQFXuWaicVcmavpHGYFbEkAxf5HwGENm0cPsVTbgH+l+S/c0hKbtisAOEAAAAASUVORK5CYII=
/***
|''Name:''|AET_Checkboxes|
|''Description:''|Adds radio boxes to the AdvancedEditTemplatePlugin|
|''Author:''|JonRobson |
|''Version:''|0.8.1|
|''Date:''|Oct 2010|
|''Requires:''|AETPlugin|
|''Comments:''|Please make comments at http://groups.google.co.uk/group/TiddlyWikiDev |
|''License:''|[[BSD License|http://www.opensource.org/licenses/bsd-license.php]] |
|''Requires:''|[[AdvancedEditTemplate (core code)|http://svn.tiddlywiki.org/Trunk/contributors/JonRobson/plugins/AET/plugins/AET.js]]|
!Usage
{{{<<aet type:radio field:fieldname values:tiddlerTitle>>}}}
***/
//{{{
(function($){
config.macros.aet.extensions.checkbox = {
	createCheckBox: function(place, title, metaDataName, autosavechanges){
		var macro = config.macros.aet;
		var c = document.createElement("input");
		c.setAttribute("type","checkbox");
		c.value = "false";
		place.appendChild(c);
		var selected = macro.getMetaData(title, metaDataName);
		if(!selected) {
			var qsvalue = macro.getVariableFromQueryString(metaDataName);
			if(qsvalue) selected = qsvalue;
		}
		if(selected){
			c.value = selected;
			c.checked = true;
		}
		var that = macro; 
		$(c).click(function(ev){
			var taskTiddler = story.findContainingTiddler(place);
			var title = taskTiddler.getAttribute("tiddler");
			if(this.checked) {
				that.setMetaData(title, metaDataName, "true", autosavechanges);
			} else{
				that.setMetaData(title, metaDataName, null, autosavechanges);
			}
		});
	}
};
config.macros.aet.controlTypes.checkbox = function(place, tiddler, fieldName, options){
	config.macros.aet.extensions.checkbox.createCheckBox(place, tiddler.title, fieldName, options.autosavechanges);
};
})(jQuery);
//}}}
<svg xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="100%" width="100%" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" viewBox="0 0 40 40"><metadata><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/><dc:title/></cc:Work></rdf:RDF></metadata><defs><linearGradient id="lG3826" x1="7.0996" gradientUnits="userSpaceOnUse" y1="18.829" gradientTransform="matrix(1.5858347,0,0,1.8078238,1098.1851,351.13716)" x2="1.5461" y2="-0.95166"><stop stop-color="#000" offset="0"/><stop stop-color="#9c9b99" offset="1"/></linearGradient><linearGradient id="lG3828" y2="372.44" gradientUnits="userSpaceOnUse" y1="375.7" x2="1111.7" x1="1097.7"><stop style="stop-color:#ac9393;" offset="0"/><stop style="stop-color:#c8b7b7;" offset="1"/></linearGradient></defs><g transform="translate(-1080.9375,-357.3329)"><path style="stroke-width:0;stroke-miterlimit:4;fill:url(#lG3826);" d="m1080.9,357.32,39.996-0.0426-0.01,40.008c-15.507-25.519-15.36-25.95-39.988-39.965z"/><path style="stroke-dashoffset:0;stroke:#7aa3be;stroke-linecap:round;stroke-miterlimit:4;stroke-width:1.49999988;fill:#c1e6fd;" d="m1091.9,363.55c6.5716-6.4925,16.576-7.3925,23.147-0.90003,6.5717,6.4925,6.5717,17.019,0,23.511-4.4424-8.6113-12.288-15.713-23.147-22.611z"/><path style="stroke-dashoffset:0;stroke:#ce81b0;stroke-linecap:round;stroke-miterlimit:4;stroke-width:1.5;fill:#f4c4e2;" d="m1110.2,367.62c3.217,3.2168,3.217,8.4323,0,11.649-3.8194-4.2357-8.3307-8.1824-11.649-11.649,3.217-3.2168,8.4325-3.2168,11.649-0.00002z"/><path style="stroke-linejoin:bevel;stroke:#000000;stroke-linecap:round;stroke-dasharray:none;stroke-miterlimit:4;stroke-width:0.80000001;fill:url(#lG3828);" d="m1081,357.34c18.79,6.4752,32.53,16.56,39.894,39.892-11.19-17.028-14.878-19.19-27.352-14.96,6.2984-12.098,3.9371-13.19-12.542-24.932z"/></g></svg>
/***
|''Name''|AETImage|
|''Requires''|BinaryUploadPlugin ImageMacroPlugin|
|''Source''|https://github.com/jdlrobson/TiddlyWiki/raw/master/plugins/AET/plugins/AETPluginImage.js|
|''Version''|0.2.3|
!Usage
{{{<<binaryEdit field>>}}}
***/
//{{{
(function($) {
var image = config.macros.image;
var binary = config.macros.binaryUpload;
var macro = config.macros.binaryEdit = {
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var args = paramString.parseParams("anon")[0];
		var bag = args.bag ? args.bag[0] : false;
		var mode = args.mode ? args.mode[0] : "image";
		var imageOptions = image.getArguments(paramString, params);
		imageOptions.alt = imageOptions.alt ? imageOptions.alt : "no image";
		var container = $("<span />").addClass("binaryEditContainer").appendTo(place)[0];
		macro.createForm(container, args.anon[0], tiddler, { imageOptions: imageOptions, mode: mode, maxwidth: 200, maxheight: 200, bag: bag, hide: args.hide });
	},
	createForm: function(place, field, tiddler, options) {
		var mode = options.mode;
		var preview = $("<div />").addClass("preview").appendTo(place)[0];
		var value = tiddler ? tiddler.fields[field]  || "" : "";
		var tags = [];
		if(mode == "image") {
			tags.push("excludeLists image");
			macro.showImage(preview, value, options.imageOptions);
		} else if(mode == "file") {
			tags.push("excludeLists file")
		}
		var input = $("<input />").attr("type", "text").attr("edit", field).val(value).appendTo(place)[0];
		binary.createUploadForm(place, {
			bag: options.bag,
			tags: tags,
			callback: function(place, fileName, workspace, baseurl) {
				var url = "%0/%1".format([baseurl, fileName]);
				$(input).val(url);
				if(mode == "image") {
					macro.showImage(preview, url, options.imageOptions);
				} else if(mode == "file") {
					image.renderImage(preview, "link.svg", {width: 24, height: 24, link: url});
				}
			}
		});
		var hide = options.hide ? options.hide : [];
		/*if(hide.contains("tags")) {
			$(".binaryUploadtags", place).hide();
		}
		if(hide.contains("value")) {
			$("[edit=%0]".format([field]), place).hide();
		}*/
	},
	showImage: function(container, imageUrl, options) {
		$(container).empty();
		if(!imageUrl) {
			return;
		} else {
			image.renderImage(container, imageUrl, options);
		}
	}
};
})(jQuery);
//}}}
@@Please do not modify this tiddler; it was created automatically upon space creation.@@
Enter some details about your mum here.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" version="1.1" viewBox="506 234 68 36" width="30" height="30"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:date>2010-09-16 14:51Z</dc:date><!-- Produced by OmniGraffle Professional 5.2.3 --></metadata><defs></defs><g stroke="none" stroke-opacity="1" stroke-dasharray="none" fill="none" fill-opacity="1"><rect width="1118" height="783"/><g><path d="M 538.68195 244.31807 C 540.43927 246.07547 540.43927 248.9247 538.68195 250.68204 C 536.92456 252.4394 534.07532 252.4394 532.318 250.68204 C 530.5606 248.9247 530.5606 246.07547 532.318 244.31807 C 534.07532 242.56075 536.92456 242.56075 538.68195 244.31807 M 511.12607 257.99356 C 511.26108 258.13019 511.39728 258.26608 511.53473 258.40121 C 527.2556 273.86606 552.74414 273.86606 568.46515 258.40121 C 568.60248 258.26617 568.73853 258.13037 568.87354 257.9938 C 568.8736 257.99374 568.8736 257.99371 568.8736 257.99362 C 568.87366 257.99371 568.87366 257.9938 568.87372 257.9939 C 570.72504 256.12051 572.35046 254.11153 573.74994 252 C 573.74994 251.99997 573.74994 251.99994 573.74994 251.99992 C 572.35046 249.8884 570.72504 247.87938 568.87372 246.00606 C 568.87366 246.00613 568.87366 246.00621 568.8736 246.00627 C 568.73865 245.86966 568.60254 245.73383 568.46515 245.5987 C 552.74414 230.13387 527.2556 230.13387 511.53473 245.5987 C 511.39728 245.73383 511.26108 245.86974 511.12613 246.00635 C 511.126 246.00624 511.126 246.00616 511.12595 246.00606 C 509.2748 247.87938 507.64954 249.88837 506.24994 251.9998 L 506.24994 251.99983 C 506.24994 251.9999 506.25 251.99992 506.25 251.99997 C 506.25 252 506.24994 252.00005 506.24994 252.00009 L 506.24994 252.00012 C 507.64954 254.11157 509.2748 256.12051 511.12595 257.9939 C 511.126 257.99377 511.126 257.99365 511.12607 257.99359 Z M 515.44916 252 C 515.8548 251.55469 516.27502 251.11778 516.71014 250.68985 C 522.16632 245.32257 529.06055 242.23206 536.17273 241.41824 C 534.6662 241.96199 533.2525 242.83762 532.04498 244.04512 C 527.65155 248.43852 527.65155 255.56163 532.04498 259.95502 C 533.2522 261.16226 534.6656 262.03778 536.17175 262.58154 C 529.05988 261.76761 522.16608 258.6771 516.71014 253.31009 C 516.2751 252.88219 515.85486 252.44528 515.44922 252 Z M 564.55054 251.99995 C 564.14502 252.44525 563.7248 252.88217 563.28973 253.31009 C 557.83368 258.67712 550.93988 261.76764 543.828 262.58157 C 545.33423 262.03781 546.74756 261.1623 547.9549 259.95502 C 552.34833 255.56163 552.34833 248.43852 547.9549 244.04512 C 546.74744 242.83765 545.33374 241.96202 543.82715 241.41824 C 550.9394 242.23206 557.83356 245.3226 563.28973 250.68985 C 563.7248 251.11775 564.14502 251.55467 564.55054 251.99995 Z M 568.8736 257.99362 C 570.7249 256.12033 572.35028 254.11139 573.74988 252.00002" fill="black" class="glyph"/></g></g></svg>
$.ajaxSetup({
	beforeSend: function(xhr) {
		xhr.setRequestHeader("X-ControlView", "false");
	}
});

var ELEMENT_SELECTOR = "#app-desc,#social";
var cache = {};
var host = "http://tiddlyspace.com";
function renderTiddler(el, tiddler) {
	var bag = tiddler.modifier + "_public";
	var srcImage = host + "/bags/" + bag + "/tiddlers/SiteIcon";
	var img;
	if(!cache[srcImage]) {
		img = new Image()
		img.width = 48;
		img.height = 48;
		img.src = srcImage;
		cache[srcImage] = img;
		img = $("<img />").css("max-width", 48).css("max-height", 48).attr("src", srcImage)[0];
	} else {
		img = cache[srcImage];
	}
	$(el).empty();
	$(img).attr("title", "@" + tiddler.modifier).appendTo(el);
	$("<h2 />").text(tiddler.title).appendTo(el);
	if(tiddler.render) {
		var container = $("<div />").html(tiddler.render).appendTo(el)[0];
		$("h1,h2,h3,h4,h5", container).each(function(i, header) {
			var nodeName = header.nodeName;
			var number = parseInt(nodeName.substr(1, nodeName.length), 10) + 2;
			$("<h" + number + " />").text($(header).text()).insertBefore(header);
			$(header).remove();
		});
	} else {
		$("<div />").text(tiddler.text).appendTo(el);
	}
}

function removeFriend(friend) {
	var tiddler = new tiddlyweb.Tiddler("@" + friend, userbag);
	var success = function() {
		printMessage("User " + friend + " removed from friends");
		var newFriends = [];
		var friends = app.friends;
		for(var i = 0; i < friends.length; i++) {
			var f = friends[i];
			if(f !== friend) {
				newFriends.push(f);
			}
		}
		app.friends = newFriends;
		$("#friend-" + friend).hide(2000);
	};
	tiddler["delete"](success, function() {
		var old = new tiddlyweb.Tiddler(friend, userbag);
		old["delete"](success, function() {
			printError("Unable to remove friend " + friend);
		})
	})
}

function socialStream(subscriptions) {
	var socialEl = $(ELEMENT_SELECTOR);
	$(socialEl).empty();
	var list = $("<ul />").appendTo(socialEl);
	var args = [];
	$("<li />").text("Loading...").appendTo(list);
	for(var i = 0; i < subscriptions.length; i++) {
		args.push("modifier:" + subscriptions[i]);
	}
	var qs = "q=" + args.join(" OR ") + " _limit:200&select=tag:!excludeLists&select=modified:>3d";
	$.ajax({
		data: {
			fat: "y",
			render: "y"
		},
		url: "/search?" + qs,
		dataType: "json",
		success: function(tiddlers) {
			$(list).empty();
			for(var i = 0; i < tiddlers.length; i++) {
				var item = $("<li />").appendTo(list)[0];
				renderTiddler(item, tiddlers[i]);
			}
		}
	});
}

var friends = [];
$.ajax({
	url: "/status",
	dataType: "json",
	success: function(status) {
		user = status.username;
		userbag = new tiddlyweb.Bag(user + "_public", "/");
		userbag.tiddlers().get(function(tiddlers) {
			for(var i = 0; i < tiddlers.length; i++) {
				var title = tiddlers[i].title;
				if(title.indexOf("@") === 0) {
					title = title.substr(1, title.length);
				}
				friends.push(title);
			}
			socialStream(friends);
		}, function() {
			
		}, "select=tag:follow");
	}
})

var simpleDate = (function() {

	var measures = {
		second: 1,
		minute: 60,
		hour: 3600,
		day: 86400,
		week: 604800,
		month: 2592000,
		year: 31536000
	};

	var chkMultiple = function(amount, type) {
		return (amount > 1) ? amount + " " + type + "s":"a " + type;
	};

	return function(thedate) {

		var dateStr, amount,
			current = new Date().getTime(),
			diff = (current - thedate.getTime()) / 1000; // work with seconds

		if(diff > measures.year) {
			amount = Math.round(diff/measures.year);
			dateStr = "about " + chkMultiple(amount, "year") + " ago";
		} else if(diff > measures.month) {
			amount = Math.round(diff/measures.month);
			//if(typeof amount == "")
			dateStr = "about " + chkMultiple(amount, "month") + " ago";
		} else if(diff > measures.week) {
			amount = Math.round(diff/measures.week);
			dateStr = "about " + chkMultiple(amount, "week") + " ago";
		} else if(diff > measures.day) {
			amount = Math.round(diff/measures.day);
			dateStr = "about " + chkMultiple(amount, "day") + " ago";
		} else if(diff > measures.hour) {
			amount = Math.round(diff/measures.hour);
			dateStr = "about " + chkMultiple(amount, "hour") + " ago";
		} else if(diff > measures.minute) {
			amount = Math.round(diff/measures.minute);
			dateStr = "about " + chkMultiple(amount, "minute") + " ago";
		} else {
			dateStr = "a few seconds ago";
		}

		return dateStr;

	};
})();

function prettyDate(t) {
	var date = new Date(Date.UTC(
		parseInt(t.substr(0, 4), 10),
		parseInt(t.substr(4, 2), 10) - 1,
		parseInt(t.substr(6, 2), 10),
		parseInt(t.substr(8, 2), 10),
		parseInt(t.substr(10, 2), 10),
		parseInt(t.substr(12, 2) || "0", 10),
		parseInt(t.substr(14, 3) || "0", 10)
	));
	return simpleDate(date);
}
There are a lot of interesting people using ~TiddlySpace that you might like to keep track of and interact with. There are a number of ways of doing this.

If you see a number in the speech bubble in one of your tiddlers, it means that someone is writing about the same thing as you. You can find out what they're saying by clicking on it. Likewise, if you see something interesting in someone else's space, you can respond to it and write up your own thoughts on the subject by clicking "Reply to this tiddler".

Additionally, if you find anyone interesting, or you find an interesting looking space and you'd like to know when it's changed, you can "follow" that space. To do this, simply create a tiddler with the title: {{{@space-name}}} and tag it {{{follow}}}. If you want, you can store some notes about that space in the body of the tiddler.

If you then want to know what happening, simply [[include|How do I include/exclude spaces?]]@docs the @tivity space and then visit your activity stream at [[/activity|/activity]], or just visit the @tapas space directly.

!Not sure who to follow?
Here's a few suggestions:
* @fnd
* @cdent
* @pmario
* @bengillies
* @dickon
/***
|''Name''|TiddlySpaceFollowingPlugin|
|''Version''|0.7.1|
|''Description''|Provides a following macro|
|''Author''|Jon Robson|
|''Requires''|TiddlySpaceConfig TiddlySpaceTiddlerIconsPlugin ErrorHandler|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
!Usage
Tag a tiddler with "follow" to express a list of followers.
Using the {{{<<followTiddlers X>>}}}
will reveal the number of tiddlers with name X in the set of spaces the *current* user viewing your space follows.
{{{<<following jon>>}}} will list all the users following Jon.
{{{<<followers jon>>}}} will list all the followers of jon.
{{{<linkedTiddlers>>}}} will list all tiddlers across TiddlySpace linked to the current tiddler
{{{<linkedTiddlers follow:yes>>}}} will list all tiddlers across TiddlySpace that come from your list of followers
adds spaceLink view type {{{<<view server.bag spaceLink>>}}} creates a link to the space described in server.bag
{{{<<view server.bag spaceLink title>>}}} makes a link to the tiddler with title expressed in the field title in space server.bag
If no name is given eg. {{{<<following>>}}} or {{{<<follow>>}}} it will default the current user.
!StyleSheet
.followTiddlersList li {
	list-style:none;
}

.followButton {
	width: 2em;
}

.followTiddlersList li .siteIcon {
	height:48px;
	width: 48px;
}

#sidebarTabs .followers li a,
.followers .siteIcon,
.followers .siteIcon div {
	display: inline;
}

.followTiddlersList li .externalImage, .followTiddlersList li .image {
	display: inline;
}

.scanResults li {
	list-style: none;
}
!Code
***/
//{{{
(function($) {
var LIMIT_FOLLOWING = 100;

var tweb = config.extensions.tiddlyweb;
var tiddlyspace = config.extensions.tiddlyspace;
var currentSpace = tiddlyspace.currentSpace.name;

var shadows = config.shadowTiddlers;
config.annotations.ScanTemplate = "This tiddler is the default template used in the display of tiddlers founding using the tsScan macro. To access attributes use the view macro e.g. {{{<<view title text>>}}}";
shadows.ScanTemplate = "<<view modifier SiteIcon width:24 height:24 spaceLink:yes label:no>> <<view title link>>";
shadows.FollowersTemplate = "<<view server.bag SiteIcon width:24 height:24 spaceLink:yes label:no>> <<view server.bag spaceLink>>";
shadows.FollowingTemplate = "<<view title SiteIcon width:24 height:24 spaceLink:yes label:no>> <<view title spaceLink>>";
shadows.FollowTiddlersBlackList = "";
shadows.FollowTiddlersHeading = "There are tiddlers in spaces you follow using the follow tag which use the title <<view title text>>";
shadows.FollowTiddlersTemplate = ["* <<view server.space SiteIcon width:24 height:24 spaceLink:yes label:no>> ",
	"<<view server.space spaceLink title external:no>> modified by <<view modifier spaceLink>> ",
	"in the <<view server.space spaceLink>> space (<<view modified date>> @ <<view modified date 0hh:0mm>>).\n"].join("");

var name = "StyleSheetFollowing";
shadows[name] = "/*{{{*/\n%0\n/*}}}*/".
	format(store.getTiddlerText(tiddler.title + "##StyleSheet"));
store.addNotification(name, refreshStyles);

// provide support for sucking in tiddlers from the server
tiddlyspace.displayServerTiddler = function(src, title, workspace, callback) {
	var adaptor = store.getTiddlers()[0].getAdaptor();
	var localTitle = tiddlyspace.getLocalTitle(title, workspace);
	var tiddler = new Tiddler(localTitle);
	tiddler.text = "Please wait while this tiddler is retrieved...";
	tiddler.fields.doNotSave = "true";
	store.addTiddler(tiddler);
	src = story.displayTiddler(src || null, tiddler.title);
	tweb.getStatus(function(status) {
		var context = {
			host: tweb.host, // TODO: inherit from source tiddler?
			workspace: workspace,
			headers: { "X-ControlView": "false" }
		};
		var getCallback = function(context, userParams) {
			var tiddler = context.tiddler;
			tiddler.title = localTitle;
			store.addTiddler(tiddler);
			story.refreshTiddler(localTitle, null, true); // overriding existing allows updating
			if(callback) {
				callback(src, tiddler);
			}
		};
		adaptor.getTiddler(title, context, null, getCallback);
	});
};

tiddlyspace.scroller = {
	runHandler: function(title, top, bottom, height) {
		var i;
		var handlers = tiddlyspace.scroller.handlers;
		var tidEl = story.getTiddler(title);
		if(tidEl) {
			var topEl = $(tidEl).offset().top + 20;
			if(top === false || (topEl > top && topEl < bottom)) {
				var h = handlers[title];
				for(i = 0; i < h.length; i++) {
					h[i]();
				}
				tiddlyspace.scroller.clearHandlers(title);
			}
		} else {
			tiddlyspace.scroller.clearHandlers(title);
		}
	},
	clearHandlers: function(title) {
		tiddlyspace.scroller.handlers[title] = [];
	},
	registerIsVisibleEvent: function(title, handler) {
		tiddlyspace.scroller.handlers[title] = tiddlyspace.scroller.handlers[title] || [];
		tiddlyspace.scroller.handlers[title].push(handler);
	},
	init: function() {
		this.handlers = {};
		this.interval = window.setInterval(function() {
			var top = $(window).scrollTop();
			var height = $(window).height();
			var bottom = top + height;
			var title;
			for(title in tiddlyspace.scroller.handlers) {
				if(title) {
					tiddlyspace.scroller.runHandler(title, top, bottom, height);
				}
			}
		}, 2000); // every 2 seconds check scroll position
	}
};
tiddlyspace.scroller.init();

var followMacro = config.macros.followTiddlers = {
	locale: {
		followListHeader: "Here are tiddlers from spaces you follow using the follow tag which use this title.",
		noTiddlersFromFollowers: "None of the spaces you follow contain a tiddler with this name.",
		errorMessage: "There was a problem retrieving tiddlers from the server. Please try again later."
	},
	init: function() {
		followMacro.lookup = {};
	},
	followTag: "follow",
	getHosts: function(callback) {
		tweb.getStatus(function(status) {
			callback(tweb.host, tiddlyspace.getHost(status.server_host, "%0"));
		});
	},
	getBlacklist: function() {
		return store.getTiddlerText("FollowTiddlersBlackList").split("\n");
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var args = paramString.parseParams("anon")[0];
		var containingTiddler = story.findContainingTiddler(place).getAttribute('tiddler');
		var title = (args.anon && args.anon[0]) || tiddler.fields["server.title"] || tiddler.title;
		var tid = store.getTiddler(title);
		var user = params[1] || false;
		if(tid) {
			followMacro.makeButton(place, {
				url: "/search?q=title:%22" + encodeURIComponent(title) + "%22",
				containingTiddler: containingTiddler,
				blacklisted: followMacro.getBlacklist(), title: title, user: user,
				consultFollowRelationship: (args.follow &&
					args.follow[0] === 'false') ? false : true });
		}
	},
	makeButton: function(place, options) { // this is essentially the same code in TiddlySpaceFollowingPlugin
		var title = options.title;
		var blacklisted = options.blacklisted;
		var tiddler = store.getTiddler(title);
		var btn = $('<div class="followButton" />').addClass("notLoaded").appendTo(place)[0];
		if(blacklisted.contains(title)) {
			$(btn).remove();
			return;
		} else {
			var user = options.user;
			window.setTimeout(function() { // prevent multiple calls due to refresh
				tiddlyspace.scroller.registerIsVisibleEvent(options.containingTiddler, function() {
					var mkButton = function(followers, ignore) {
						if(!followers && !ignore) {
							$(btn).remove();
						} else {
							$("<a />").appendTo(btn);
							var scanOptions = { url: options.url,
								spaceField: options.spaceField || "bag", template: null, sort: "-modified",
								callback: function(tiddlers) {
									$(btn).removeClass("notLoaded");
									followMacro.constructInterface(btn, tiddlers);
								}
							};
							if(!ignore) {
								scanOptions.showBags = followMacro._getFollowerBags(followers);
							}
							scanOptions.hideBags = [tiddler.fields["server.bag"]];
							scanMacro.scan(null, scanOptions, user);
						}
					};
					if(options.consultFollowRelationship) {
						followMacro.getFollowers(mkButton);
					} else {
						mkButton([], true);
					}
				});
			}, 1000);
		}
	},
	constructInterface: function(container, tiddlers) {
		var txt = tiddlers.length;
		var className = txt > 0 ? "hasReplies" : "noReplies";
		var el = $(story.findContainingTiddler(container));
		$(container).empty().addClass(className);
		var btn = $("<a />").addClass("followedTiddlers").text(txt).
			click(function(ev) {
				followMacro.followingOnClick(ev);
			}).appendTo('<div class="followedTiddlers" />').appendTo(container)[0];
		$.data(btn, "tiddlers", tiddlers);
	},
	followingOnClick: function(ev) {
		var target = ev.target;
		var locale = followMacro.locale;
		var el = $('<div class="followTiddlersList" />')[0];
		var popup = Popup.create(target,"div");
		$(popup).addClass("taggedTiddlerList followList").click(function(ev) { // make it so only clicking on the document outside the popup removes the popup
			if(ev.target.parentNode != document) {
				ev.stopPropagation();
			}
		}).append(el);
		var tiddlers = $.data(target, "tiddlers") || [];
		scanMacro.template(el, tiddlers.slice(0,1), "FollowTiddlersHeading");
		scanMacro.template(el, tiddlers, "FollowTiddlersTemplate");
		if(tiddlers.length === 0) {
			$("<li />").text(locale.noTiddlersFromFollowers).appendTo(el);
		}
		Popup.show();
		ev.stopPropagation();
		return popup;
	},
	_getFollowerBags: function(followers) { // XXX: private or not?
		return $.map(followers, function(name, i) {
			return name != currentSpace ? "%0_public".format(name) : null;
		});
	},
	getFollowers: function(callback, username) {
		// returns a list of spaces being followed by the existing space
		var followersCallback = function(user) {
			if(!user.anon) {
				scanMacro.scan(null, { 
					url: "/search?q=bag:%0_public tag:%1 _limit:%2".format(user.name, followMacro.followTag, LIMIT_FOLLOWING),
					spaceField: "title", template: null, cache: true,
					callback: function(tiddlers) {
						var followers = [];
						for(var i = 0; i < tiddlers.length; i++) {
							followers.push(tiddlyspace.resolveSpaceName(tiddlers[i].title));
						}
						callback(followers);
					}
				});
			} else {
				callback(false);
			}
		};
		return !username ? tweb.getUserInfo(followersCallback) : followersCallback({ name: username });
	}
};

var scanMacro = config.macros.tsScan = {
	init: function () {
		this.scanned = {};
	},
	_tiddlerfy: function(jsontiddlers, options) {
		var tiddlers = [];
		var spaceField = options.spaceField || "bag"; // TODO: phase out use view types instead
		$.each(jsontiddlers, function(i, t) {
			var use = false;
			if(!options.showBags || (options.showBags && options.showBags.contains(t.bag))) {
				use = true;
			}
			if(options.hideBags && options.hideBags.contains(t.bag)) {
				use = false;
			}
			if(use) {
				var spaceName = t[spaceField];
				var tiddler = config.adaptors.tiddlyweb.toTiddler(t, tweb.host);
				tiddler.fields["server.space"] = tiddlyspace.resolveSpaceName(spaceName);
				tiddlers.push(tiddler);
			}
		});
		return tiddlers;
	},
	_scanCallback: function(place, jsontiddlers, options) {
		var locale = followersMacro.locale;
		var tiddlers = scanMacro._tiddlerfy(jsontiddlers, options);
		
		if(options.sort) {
			tiddlers = store.sortTiddlers(tiddlers, options.sort);
		}
		if(options.filter) {
			var _store = new TiddlyWiki();
			config.lastStore = _store;
			for(var i = 0; i < tiddlers.length; i++) {
				var clone = tiddlers[i];
				clone.title = tiddlyspace.getLocalTitle(clone.title, clone.fields['server.workspace']);
				_store.addTiddler(clone);
			}
			tiddlers = _store.filterTiddlers(options.filter);
		}
		if(place) {
			$(place).empty();
			var list = $("<ul />").appendTo(place)[0];
			scanMacro.template(list, tiddlers, options.template);
			if(tiddlers.length === 0) {
				$("<li />").text(options.emptyMessage || locale.noone).appendTo(list);
				$(list).addClass("emptyList");
			}
		}
		if(options.callback) {
			options.callback(tiddlers);
		}
	},
	constructSearchUrl: function(host, options) {
		if(options.url) {
			return options.url;
		}
		var inputs = options.searchValues;
		var tag = options.tag;
		var searchField = options.searchField || "title";
		var searchQuery = [];
		for(var i = 0; i < inputs.length; i++) {
			searchQuery.push('%0:"%1"'.format(searchField, inputs[i]));
		}
		var query = searchQuery.join(" OR ");
		query = tag ? "(%0) AND tag:%1".format(query, tag) : query;
		query = options.query ? "%0;%1;".format(query, options.query) : query;
		query = options.fat ? "%0&fat=1".format(query) : query;
		return '%0/search?q=%1'.format(host, query);
	},
	scan: function(place, options) { // TODO: make use of list macro with url filter
		var locale = followersMacro.locale;
		options.template = options.template ? options.template : "ScanTemplate";
		followMacro.getHosts(function(host, tsHost) {
			$(place).text(followersMacro.locale.pleaseWait);
			options = options ? options: {};
			var url = scanMacro.constructSearchUrl(host, options);
			if(options.cache && scanMacro.scanned[url]) {
				var tiddlers = scanMacro.scanned[url].tiddlers;
				var run = function(tiddlers) {
					scanMacro._scanCallback(place, tiddlers, options);
				};
				if(tiddlers) {
					run(tiddlers);
				} else {
					scanMacro.scanned[url].callbacks.push(run);
				}
			} else {
				var callback = function(tiddlers) {
					scanMacro._scanCallback(place, tiddlers, options);
				};
				if(scanMacro.scanned[url] && scanMacro.scanned[url].callbacks) {
					scanMacro.scanned[url].callbacks.push(callback);
				} else {
					scanMacro.scanned[url] = {
						callbacks: [callback]
					};
				}
				ajaxReq({
					url: url,
					dataType: "json",
					success: function(tiddlers) {
						scanMacro.scanned[url].tiddlers = tiddlers;
						var callbacks = scanMacro.scanned[url].callbacks;
						while(callbacks.length > 0) {
							callbacks.pop()(tiddlers);
						}
					},
					error: function(xhr) {
						$(place).empty();
						$("<span />").addClass("annotation error").text(locale.error.format(xhr.status)).appendTo(place);
					}
				});
			}
		});
	},
	template: function(place, tiddlers, template) { // TODO: make use of list macro.
		for(var i = 0; i < tiddlers.length; i++) {
			var tiddler = tiddlers[i];
			var item = $('<li class="spaceName" />').appendTo(place)[0];
			var spaceName = tiddler.fields["server.space"] || "";
			var templateText = store.getTiddlerText(template).replace(/\$1/mg, spaceName);
			wikify(templateText, item, null, tiddler);
		}
	},
	getOptions: function(paramString, tiddler) {
		var args = paramString.parseParams("name", null, true, false, true)[0];
		var options = { query: false, sort: false, tag: false, template: false, showBags: args.show || false,
			hideBags: args.hide || false, filter: false, spaceField: "bag", searchField: "title", fat: false,
			emptyMessage: false };
		for(var name in args) {
			if(name != "name") {
				if(name == "fat") {
					options[name] = true;
				} else {
					options[name] = args[name][0];
				}
			}
		}
		// if user has set searchField to modifier, then use the modifiers value if available otherwise use searchValues.
		var searchField = options.searchField;
		var searchValues = args[searchField] ? args[searchField] : args.searchValues;
		// if neither of those were used use the first parameter
		var defaultValues = tiddler ? [ tiddler.title ] : [];
		options.searchValues = searchValues ? searchValues : ( args.name ? [args.name[0]] : defaultValues);
		return options;
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var container = $("<div />").addClass("scanResults resultsArea").appendTo(place)[0];
		var options = scanMacro.getOptions(paramString, tiddler);
		scanMacro.scan(container, options);
	}
};

var followersMacro = config.macros.followers = {
	locale: {
		loggedOut: "Please login to see the list of followers",
		noSupport: "We were unable to retrieve followers as your browser does not support following.",
		pleaseWait: "Please wait while we look this up...",
		error: "Error %0 occurred whilst retrieving data from server",
		noone: "None."
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var locale = followersMacro.locale;
		var args = paramString.parseParams("name", null, true, false, true)[0];
		var username = args.name ? args.name[0] : false;
		var container = $('<div class="followers" />').text(locale.pleaseWait).
			appendTo(place)[0];
		var followersCallback = function(user) {
			if(user.anon) {
				$("<span />").text(locale.loggedOut).appendTo(container);
			} else {
				var options = scanMacro.getOptions(paramString);
				$.extend(options, {
					url: "/search?q=title:@%0 OR title:%0 tag:%1 _limit:%2".
						format(user.name, followMacro.followTag, LIMIT_FOLLOWING),
					spaceField: "bag",
					template: options.template ? options.template : "FollowersTemplate"
				});
				scanMacro.scan(container, options);
			}
		};
		return !username ? followersCallback({ name: currentSpace }) : followersCallback({ name: username });
	}
};

var followingMacro = config.macros.following = {
	locale: {
		pleaseWait: followersMacro.locale.pleaseWait,
		loggedOut: "Please login to see who you are following",
		noSupport: followersMacro.locale.noSupport,
		error: followersMacro.locale.error,
		noone: followersMacro.locale.noone
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var locale = followingMacro.locale;
		var args = paramString.parseParams("name", null, true, false, true)[0];
		var fat = args.fat ? true : false;
		var username = args.name ? args.name[0] : false;
		var container = $('<div class="following" />').text(locale.pleaseWait).
			appendTo(place)[0];
		var followingCallback = function(user) {
			if(user.anon) {
				$("<span />").text(locale.loggedOut).appendTo(container);
			} else {
				var options = scanMacro.getOptions(paramString);
				$.extend(options, {
					url: "/search?q=bag:%0_public tag:%1 _limit:%2".format(user.name, followMacro.followTag, LIMIT_FOLLOWING),
					spaceField: "title",
					template: options.template ? options.template : "FollowingTemplate"
				});
				scanMacro.scan(container, options);
			}
		};
		return !username ? followingCallback({ name: currentSpace }) : followingCallback({ name: username });
	}
};

var linkedMacro = config.macros.linkedTiddlers = {
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var args = paramString.parseParams("anon")[0];
		var title = params[0] || tiddler.fields["server.title"] || tiddler.title;
		var tid = store.getTiddler(title);
		var containingTiddler = story.findContainingTiddler(place).getAttribute('tiddler');
		if(tid) {
			followMacro.makeButton(place, {
				spaceField: "recipe",
				url: "/bags/%0/tiddlers/%1/backlinks".format(tid.fields['server.bag'],
					encodeURIComponent(tid.title)),
				blacklisted: followMacro.getBlacklist(),
				title: title,
				containingTiddler: containingTiddler,
				user: params[1] || false,
				consultFollowRelationship: args.follow ? true : false });
		}
	}
};

if(config.options.chkFollowTiddlersIsLinkedTiddlers) {
	merge(config.macros.followTiddlers, config.macros.linkedTiddlers);
	config.shadowTiddlers.FollowTiddlersHeading = "These are the other tiddlers that link to this tiddler.";
}

})(jQuery);
//}}}
<<familytreelist sex:M>>
<<familytreelist sex:F>>
/***
|''Name''|jit-yc|
***/
//{{{
/*
  Copyright (c) 2010, Nicolas Garcia Belmonte
  All rights reserved

  > Redistribution and use in source and binary forms, with or without
  > modification, are permitted provided that the following conditions are met:
  >      * Redistributions of source code must retain the above copyright
  >        notice, this list of conditions and the following disclaimer.
  >      * Redistributions in binary form must reproduce the above copyright
  >        notice, this list of conditions and the following disclaimer in the
  >        documentation and/or other materials provided with the distribution.
  >      * Neither the name of the organization nor the
  >        names of its contributors may be used to endorse or promote products
  >        derived from this software without specific prior written permission.
  >
  >  THIS SOFTWARE IS PROVIDED BY NICOLAS GARCIA BELMONTE ``AS IS'' AND ANY
  >  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  >  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  >  DISCLAIMED. IN NO EVENT SHALL NICOLAS GARCIA BELMONTE BE LIABLE FOR ANY
  >  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  >  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  >  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  >  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  >  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  >  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 (function(){window.$jit=function(x){x=x||window;for(var y in $jit){if($jit[y].$extend){x[y]=$jit[y]}}};$jit.version="2.0.0b";var c=function(w){return document.getElementById(w)};c.empty=function(){};c.extend=function(y,w){for(var x in (w||{})){y[x]=w[x]}return y};c.lambda=function(w){return(typeof w=="function")?w:function(){return w}};c.time=Date.now||function(){return +new Date};c.splat=function(x){var w=c.type(x);return w?((w!="array")?[x]:x):[]};c.type=function(x){var w=c.type.s.call(x).match(/^\[object\s(.*)\]$/)[1].toLowerCase();if(w!="object"){return w}if(x&&x.$$family){return x.$$family}return(x&&x.nodeName&&x.nodeType==1)?"element":w};c.type.s=Object.prototype.toString;c.each=function(B,A){var z=c.type(B);if(z=="object"){for(var y in B){A(B[y],y)}}else{for(var x=0,w=B.length;x<w;x++){A(B[x],x)}}};c.indexOf=function(z,y){if(Array.indexOf){return z.indexOf(y)}for(var x=0,w=z.length;x<w;x++){if(z[x]===y){return x}}return -1};c.map=function(y,x){var w=[];c.each(y,function(A,z){w.push(x(A,z))});return w};c.reduce=function(A,y,x){var w=A.length;if(w==0){return x}var z=arguments.length==3?x:A[--w];while(w--){z=y(z,A[w])}return z};c.merge=function(){var A={};for(var z=0,w=arguments.length;z<w;z++){var x=arguments[z];if(c.type(x)!="object"){continue}for(var y in x){var C=x[y],B=A[y];A[y]=(B&&c.type(C)=="object"&&c.type(B)=="object")?c.merge(B,C):c.unlink(C)}}return A};c.unlink=function(y){var x;switch(c.type(y)){case"object":x={};for(var A in y){x[A]=c.unlink(y[A])}break;case"array":x=[];for(var z=0,w=y.length;z<w;z++){x[z]=c.unlink(y[z])}break;default:return y}return x};c.zip=function(){if(arguments.length===0){return[]}for(var y=0,x=[],w=arguments.length,B=arguments[0].length;y<B;y++){for(var z=0,A=[];z<w;z++){A.push(arguments[z][y])}x.push(A)}return x};c.rgbToHex=function(A,z){if(A.length<3){return null}if(A.length==4&&A[3]==0&&!z){return"transparent"}var x=[];for(var w=0;w<3;w++){var y=(A[w]-0).toString(16);x.push(y.length==1?"0"+y:y)}return z?x:"#"+x.join("")};c.hexToRgb=function(y){if(y.length!=7){y=y.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);y.shift();if(y.length!=3){return null}var w=[];for(var x=0;x<3;x++){var z=y[x];if(z.length==1){z+=z}w.push(parseInt(z,16))}return w}else{y=parseInt(y.slice(1),16);return[y>>16,y>>8&255,y&255]}};c.destroy=function(w){c.clean(w);if(w.parentNode){w.parentNode.removeChild(w)}if(w.clearAttributes){w.clearAttributes()}};c.clean=function(z){for(var y=z.childNodes,x=0,w=y.length;x<w;x++){c.destroy(y[x])}};c.addEvent=function(y,x,w){if(y.addEventListener){y.addEventListener(x,w,false)}else{y.attachEvent("on"+x,w)}};c.addEvents=function(x,y){for(var w in y){c.addEvent(x,w,y[w])}};c.hasClass=function(x,w){return(" "+x.className+" ").indexOf(" "+w+" ")>-1};c.addClass=function(x,w){if(!c.hasClass(x,w)){x.className=(x.className+" "+w)}};c.removeClass=function(x,w){x.className=x.className.replace(new RegExp("(^|\\s)"+w+"(?:\\s|$)"),"$1")};c.getPos=function(y){var B=A(y);var w=z(y);return{x:B.x-w.x,y:B.y-w.y};function A(D){var C={x:0,y:0};while(D&&!x(D)){C.x+=D.offsetLeft;C.y+=D.offsetTop;D=D.offsetParent}return C}function z(D){var C={x:0,y:0};while(D&&!x(D)){C.x+=D.scrollLeft;C.y+=D.scrollTop;D=D.parentNode}return C}function x(C){return(/^(?:body|html)$/i).test(C.tagName)}};c.event={get:function(x,w){w=w||window;return x||w.event},getWheel:function(w){return w.wheelDelta?w.wheelDelta/120:-(w.detail||0)/3},isRightClick:function(w){return(w.which==3||w.button==2)},getPos:function(z,y){y=y||window;z=z||y.event;var x=y.document;x=x.documentElement||x.body;if(z.touches&&z.touches.length){z=z.touches[0]}var w={x:z.pageX||(z.clientX+x.scrollLeft),y:z.pageY||(z.clientY+x.scrollTop)};return w},stop:function(w){if(w.stopPropagation){w.stopPropagation()}w.cancelBubble=true;if(w.preventDefault){w.preventDefault()}else{w.returnValue=false}}};$jit.util=$jit.id=c;var q=function(x){x=x||{};var w=function(){for(var A in this){if(typeof this[A]!="function"){this[A]=c.unlink(this[A])}}this.constructor=w;if(q.prototyping){return this}var z=this.initialize?this.initialize.apply(this,arguments):this;this.$$family="class";return z};for(var y in q.Mutators){if(!x[y]){continue}x=q.Mutators[y](x,x[y]);delete x[y]}c.extend(w,this);w.constructor=q;w.prototype=x;return w};q.Mutators={Implements:function(w,x){c.each(c.splat(x),function(z){q.prototyping=z;var y=(typeof z=="function")?new z:z;for(var A in y){if(!(A in w)){w[A]=y[A]}}delete q.prototyping});return w}};c.extend(q,{inherit:function(w,z){for(var y in z){var x=z[y];var B=w[y];var A=c.type(x);if(B&&A=="function"){if(x!=B){q.override(w,y,x)}}else{if(A=="object"){w[y]=c.merge(B,x)}else{w[y]=x}}}return w},override:function(x,w,A){var z=q.prototyping;if(z&&x[w]!=z[w]){z=null}var y=function(){var B=this.parent;this.parent=z?z[w]:x[w];var C=A.apply(this,arguments);this.parent=B;return C};x[w]=y}});q.prototype.implement=function(){var w=this.prototype;c.each(Array.prototype.slice.call(arguments||[]),function(x){q.inherit(w,x)});return this};$jit.Class=q;$jit.json={prune:function(x,w){this.each(x,function(z,y){if(y==w&&z.children){delete z.children;z.children=[]}})},getParent:function(w,A){if(w.id==A){return false}var z=w.children;if(z&&z.length>0){for(var y=0;y<z.length;y++){if(z[y].id==A){return w}else{var x=this.getParent(z[y],A);if(x){return x}}}}return false},getSubtree:function(w,A){if(w.id==A){return w}for(var y=0,z=w.children;y<z.length;y++){var x=this.getSubtree(z[y],A);if(x!=null){return x}}return null},eachLevel:function(w,B,y,A){if(B<=y){A(w,B);if(!w.children){return}for(var x=0,z=w.children;x<z.length;x++){this.eachLevel(z[x],B+1,y,A)}}},each:function(w,x){this.eachLevel(w,0,Number.MAX_VALUE,x)}};$jit.Trans={$extend:true,linear:function(w){return w}};var i=$jit.Trans;(function(){var w=function(z,y){y=c.splat(y);return c.extend(z,{easeIn:function(A){return z(A,y)},easeOut:function(A){return 1-z(1-A,y)},easeInOut:function(A){return(A<=0.5)?z(2*A,y)/2:(2-z(2*(1-A),y))/2}})};var x={Pow:function(z,y){return Math.pow(z,y[0]||6)},Expo:function(y){return Math.pow(2,8*(y-1))},Circ:function(y){return 1-Math.sin(Math.acos(y))},Sine:function(y){return 1-Math.sin((1-y)*Math.PI/2)},Back:function(z,y){y=y[0]||1.618;return Math.pow(z,2)*((y+1)*z-y)},Bounce:function(B){var A;for(var z=0,y=1;1;z+=y,y/=2){if(B>=(7-4*z)/11){A=y*y-Math.pow((11-6*z-11*B)/4,2);break}}return A},Elastic:function(z,y){return Math.pow(2,10*--z)*Math.cos(20*z*Math.PI*(y[0]||1)/3)}};c.each(x,function(z,y){i[y]=w(z)});c.each(["Quad","Cubic","Quart","Quint"],function(z,y){i[z]=w(function(A){return Math.pow(A,[y+2])})})})();var u=new q({initialize:function(w){this.setOptions(w)},setOptions:function(w){var x={duration:2500,fps:40,transition:i.Quart.easeInOut,compute:c.empty,complete:c.empty,link:"ignore"};this.opt=c.merge(x,w||{});return this},step:function(){var x=c.time(),w=this.opt;if(x<this.time+w.duration){var y=w.transition((x-this.time)/w.duration);w.compute(y)}else{this.timer=clearInterval(this.timer);w.compute(1);w.complete()}},start:function(){if(!this.check()){return this}this.time=0;this.startTimer();return this},startTimer:function(){var w=this,x=this.opt.fps;if(this.timer){return false}this.time=c.time()-this.time;this.timer=setInterval((function(){w.step()}),Math.round(1000/x));return true},pause:function(){this.stopTimer();return this},resume:function(){this.startTimer();return this},stopTimer:function(){if(!this.timer){return false}this.time=c.time()-this.time;this.timer=clearInterval(this.timer);return true},check:function(){if(!this.timer){return true}if(this.opt.link=="cancel"){this.stopTimer();return true}return false}});var n=function(){var y=arguments;for(var A=0,w=y.length,x={};A<w;A++){var z=n[y[A]];if(z.$extend){c.extend(x,z)}else{x[y[A]]=z}}return x};n.AreaChart={$extend:true,animate:true,labelOffset:3,type:"stacked",Tips:{enable:false,onShow:c.empty,onHide:c.empty},Events:{enable:false,onClick:c.empty},selectOnHover:true,showAggregates:true,showLabels:true,filterOnClick:false,restoreOnRightClick:false};n.Margin={$extend:false,top:0,left:0,right:0,bottom:0};n.Canvas={$extend:true,injectInto:"id",width:false,height:false,useCanvas:false,withLabels:true,background:false};n.Tree={$extend:true,orientation:"left",subtreeOffset:8,siblingOffset:5,indent:10,multitree:false,align:"center"};n.Node={$extend:false,overridable:false,type:"circle",color:"#ccb",alpha:1,dim:3,height:20,width:90,autoHeight:false,autoWidth:false,lineWidth:1,transform:true,align:"center",angularWidth:1,span:1,CanvasStyles:{}};n.Edge={$extend:false,overridable:false,type:"line",color:"#ccb",lineWidth:1,dim:15,alpha:1,epsilon:7,CanvasStyles:{}};n.Fx={$extend:true,fps:40,duration:2500,transition:$jit.Trans.Quart.easeInOut,clearCanvas:true};n.Label={$extend:false,overridable:false,type:"HTML",style:" ",size:10,family:"sans-serif",textAlign:"center",textBaseline:"alphabetic",color:"#fff"};n.Tips={$extend:false,enable:false,type:"auto",offsetX:20,offsetY:20,force:false,onShow:c.empty,onHide:c.empty};n.NodeStyles={$extend:false,enable:false,type:"auto",stylesHover:false,stylesClick:false};n.Events={$extend:false,enable:false,enableForEdges:false,type:"auto",onClick:c.empty,onRightClick:c.empty,onMouseMove:c.empty,onMouseEnter:c.empty,onMouseLeave:c.empty,onDragStart:c.empty,onDragMove:c.empty,onDragCancel:c.empty,onDragEnd:c.empty,onTouchStart:c.empty,onTouchMove:c.empty,onTouchEnd:c.empty,onMouseWheel:c.empty};n.Navigation={$extend:false,enable:false,type:"auto",panning:false,zooming:false};n.Controller={$extend:true,onBeforeCompute:c.empty,onAfterCompute:c.empty,onCreateLabel:c.empty,onPlaceLabel:c.empty,onComplete:c.empty,onBeforePlotLine:c.empty,onAfterPlotLine:c.empty,onBeforePlotNode:c.empty,onAfterPlotNode:c.empty,request:false};var t={initialize:function(y,w){this.viz=w;this.canvas=w.canvas;this.config=w.config[y];this.nodeTypes=w.fx.nodeTypes;var x=this.config.type;this.dom=x=="auto"?(w.config.Label.type!="Native"):(x!="Native");this.labelContainer=this.dom&&w.labels.getLabelContainer();this.isEnabled()&&this.initializePost()},initializePost:c.empty,setAsProperty:c.lambda(false),isEnabled:function(){return this.config.enable},isLabel:function(z,y){z=c.event.get(z,y);var w=this.labelContainer,x=z.target||z.srcElement;if(x&&x.parentNode==w){return x}return false}};var h={onMouseUp:c.empty,onMouseDown:c.empty,onMouseMove:c.empty,onMouseOver:c.empty,onMouseOut:c.empty,onMouseWheel:c.empty,onTouchStart:c.empty,onTouchMove:c.empty,onTouchEnd:c.empty,onTouchCancel:c.empty};var s=new q({initialize:function(w){this.viz=w;this.canvas=w.canvas;this.node=false;this.edge=false;this.registeredObjects=[];this.attachEvents()},attachEvents:function(){var y=this.canvas.getElement(),x=this;y.oncontextmenu=c.lambda(false);c.addEvents(y,{mouseup:function(B,A){var z=c.event.get(B,A);x.handleEvent("MouseUp",B,A,x.makeEventObject(B,A),c.event.isRightClick(z))},mousedown:function(B,A){var z=c.event.get(B,A);x.handleEvent("MouseDown",B,A,x.makeEventObject(B,A),c.event.isRightClick(z))},mousemove:function(A,z){x.handleEvent("MouseMove",A,z,x.makeEventObject(A,z))},mouseover:function(A,z){x.handleEvent("MouseOver",A,z,x.makeEventObject(A,z))},mouseout:function(A,z){x.handleEvent("MouseOut",A,z,x.makeEventObject(A,z))},touchstart:function(A,z){x.handleEvent("TouchStart",A,z,x.makeEventObject(A,z))},touchmove:function(A,z){x.handleEvent("TouchMove",A,z,x.makeEventObject(A,z))},touchend:function(A,z){x.handleEvent("TouchEnd",A,z,x.makeEventObject(A,z))}});var w=function(C,B){var A=c.event.get(C,B);var z=c.event.getWheel(A);x.handleEvent("MouseWheel",C,B,z)};if(!document.getBoxObjectFor&&window.mozInnerScreenX==null){c.addEvent(y,"mousewheel",w)}else{y.addEventListener("DOMMouseScroll",w,false)}},register:function(w){this.registeredObjects.push(w)},handleEvent:function(){var x=Array.prototype.slice.call(arguments),A=x.shift();for(var z=0,y=this.registeredObjects,w=y.length;z<w;z++){y[z]["on"+A].apply(y[z],x)}},makeEventObject:function(C,B){var z=this,A=this.viz.graph,y=this.viz.fx,x=y.nodeTypes,w=y.edgeTypes;return{pos:false,node:false,edge:false,contains:false,getNodeCalled:false,getEdgeCalled:false,getPos:function(){var F=z.viz.canvas,G=F.getSize(),H=F.getPos(),E=F.translateOffsetX,D=F.translateOffsetY,K=F.scaleOffsetX,I=F.scaleOffsetY,J=c.event.getPos(C,B);this.pos={x:(J.x-H.x-G.width/2-E)*1/K,y:(J.y-H.y-G.height/2-D)*1/I};return this.pos},getNode:function(){if(this.getNodeCalled){return this.node}this.getNodeCalled=true;for(var G in A.nodes){var F=A.nodes[G],E=F&&x[F.getData("type")],D=E&&E.contains&&E.contains.call(y,F,this.getPos());if(D){this.contains=D;return z.node=this.node=F}}return z.node=this.node=false},getEdge:function(){if(this.getEdgeCalled){return this.edge}this.getEdgeCalled=true;var F={};for(var J in A.edges){var H=A.edges[J];F[J]=true;for(var I in H){if(I in F){continue}var G=H[I],E=G&&w[G.getData("type")],D=E&&E.contains&&E.contains.call(y,G,this.getPos());if(D){this.contains=D;return z.edge=this.edge=G}}}return z.edge=this.edge=false},getContains:function(){if(this.getNodeCalled){return this.contains}this.getNode();return this.contains}}}});var o={initializeExtras:function(){var x=new s(this),w=this;c.each(["NodeStyles","Tips","Navigation","Events"],function(y){var z=new o.Classes[y](y,w);if(z.isEnabled()){x.register(z)}if(z.setAsProperty()){w[y.toLowerCase()]=z}})}};o.Classes={};o.Classes.Events=new q({Implements:[t,h],initializePost:function(){this.fx=this.viz.fx;this.ntypes=this.viz.fx.nodeTypes;this.etypes=this.viz.fx.edgeTypes;this.hovered=false;this.pressed=false;this.touched=false;this.touchMoved=false;this.moved=false},setAsProperty:c.lambda(true),onMouseUp:function(A,z,x,y){var w=c.event.get(A,z);if(!this.moved){if(y){this.config.onRightClick(this.hovered,x,w)}else{this.config.onClick(this.pressed,x,w)}}if(this.pressed){if(this.moved){this.config.onDragEnd(this.pressed,x,w)}else{this.config.onDragCancel(this.pressed,x,w)}this.pressed=this.moved=false}},onMouseOut:function(B,A,z){var x=c.event.get(B,A),y;if(this.dom&&(y=this.isLabel(B,A))){this.config.onMouseLeave(this.viz.graph.getNode(y.id),z,x);this.hovered=false;return}var w=x.relatedTarget,C=this.canvas.getElement();while(w&&w.parentNode){if(C==w.parentNode){return}w=w.parentNode}if(this.hovered){this.config.onMouseLeave(this.hovered,z,x);this.hovered=false}},onMouseOver:function(A,z,y){var w=c.event.get(A,z),x;if(this.dom&&(x=this.isLabel(A,z))){this.hovered=this.viz.graph.getNode(x.id);this.config.onMouseEnter(this.hovered,y,w)}},onMouseMove:function(C,B,A){var x,w=c.event.get(C,B);if(this.pressed){this.moved=true;this.config.onDragMove(this.pressed,A,w);return}if(this.dom){this.config.onMouseMove(this.hovered,A,w)}else{if(this.hovered){var D=this.hovered;var z=D.nodeFrom?this.etypes[D.getData("type")]:this.ntypes[D.getData("type")];var y=z&&z.contains&&z.contains.call(this.fx,D,A.getPos());if(y){this.config.onMouseMove(D,A,w);return}else{this.config.onMouseLeave(D,A,w);this.hovered=false}}if(this.hovered=(A.getNode()||(this.config.enableForEdges&&A.getEdge()))){this.config.onMouseEnter(this.hovered,A,w)}else{this.config.onMouseMove(false,A,w)}}},onMouseWheel:function(x,w,y){this.config.onMouseWheel(y,c.event.get(x,w))},onMouseDown:function(z,y,x){var w=c.event.get(z,y);this.pressed=x.getNode()||(this.config.enableForEdges&&x.getEdge());this.config.onDragStart(this.pressed,x,w)},onTouchStart:function(z,y,x){var w=c.event.get(z,y);this.touched=x.getNode()||(this.config.enableForEdges&&x.getEdge());this.config.onTouchStart(this.touched,x,w)},onTouchMove:function(z,y,x){var w=c.event.get(z,y);if(this.touched){this.touchMoved=true;this.config.onTouchMove(this.touched,x,w)}},onTouchEnd:function(z,y,x){var w=c.event.get(z,y);if(this.touched){if(this.touchMoved){this.config.onTouchEnd(this.touched,x,w)}else{this.config.onTouchCancel(this.touched,x,w)}this.touched=this.touchMoved=false}}});o.Classes.Tips=new q({Implements:[t,h],initializePost:function(){if(document.body){var w=c("_tooltip")||document.createElement("div");w.id="_tooltip";w.className="tip";c.extend(w.style,{position:"absolute",display:"none",zIndex:13000});document.body.appendChild(w);this.tip=w;this.node=false}},setAsProperty:c.lambda(true),onMouseOut:function(y,x){if(this.dom&&this.isLabel(y,x)){this.hide(true);return}var w=y.relatedTarget,z=this.canvas.getElement();while(w&&w.parentNode){if(z==w.parentNode){return}w=w.parentNode}this.hide(false)},onMouseOver:function(y,x){var w;if(this.dom&&(w=this.isLabel(y,x))){this.node=this.viz.graph.getNode(w.id);this.config.onShow(this.tip,this.node,w)}},onMouseMove:function(z,y,w){if(this.dom&&this.isLabel(z,y)){this.setTooltipPosition(c.event.getPos(z,y))}if(!this.dom){var x=w.getNode();if(!x){this.hide(true);return}if(this.config.force||!this.node||this.node.id!=x.id){this.node=x;this.config.onShow(this.tip,x,w.getContains())}this.setTooltipPosition(c.event.getPos(z,y))}},setTooltipPosition:function(F){var B=this.tip,A=B.style,z=this.config;A.display="";var D={height:document.body.clientHeight,width:document.body.clientWidth};var C={width:B.offsetWidth,height:B.offsetHeight};var w=z.offsetX,E=z.offsetY;A.top=((F.y+E+C.height>D.height)?(F.y-C.height-E):F.y+E)+"px";A.left=((F.x+C.width+w>D.width)?(F.x-C.width-w):F.x+w)+"px"},hide:function(w){this.tip.style.display="none";w&&this.config.onHide()}});o.Classes.NodeStyles=new q({Implements:[t,h],initializePost:function(){this.fx=this.viz.fx;this.types=this.viz.fx.nodeTypes;this.nStyles=this.config;this.nodeStylesOnHover=this.nStyles.stylesHover;this.nodeStylesOnClick=this.nStyles.stylesClick;this.hoveredNode=false;this.fx.nodeFxAnimation=new u();this.down=false;this.move=false},onMouseOut:function(y,x){this.down=this.move=false;if(!this.hoveredNode){return}if(this.dom&&this.isLabel(y,x)){this.toggleStylesOnHover(this.hoveredNode,false)}var w=y.relatedTarget,z=this.canvas.getElement();while(w&&w.parentNode){if(z==w.parentNode){return}w=w.parentNode}this.toggleStylesOnHover(this.hoveredNode,false);this.hoveredNode=false},onMouseOver:function(z,y){var w;if(this.dom&&(w=this.isLabel(z,y))){var x=this.viz.graph.getNode(w.id);if(x.selected){return}this.hoveredNode=x;this.toggleStylesOnHover(this.hoveredNode,true)}},onMouseDown:function(A,z,x,y){if(y){return}var w;if(this.dom&&(w=this.isLabel(A,z))){this.down=this.viz.graph.getNode(w.id)}else{if(!this.dom){this.down=x.getNode()}}this.move=false},onMouseUp:function(z,y,w,x){if(x){return}if(!this.move){this.onClick(w.getNode())}this.down=this.move=false},getRestoredStyles:function(x,w){var z={},y=this["nodeStylesOn"+w];for(var A in y){z[A]=x.styles["$"+A]}return z},toggleStylesOnHover:function(w,x){if(this.nodeStylesOnHover){this.toggleStylesOn("Hover",w,x)}},toggleStylesOnClick:function(w,x){if(this.nodeStylesOnClick){this.toggleStylesOn("Click",w,x)}},toggleStylesOn:function(A,w,C){var D=this.viz;var B=this.nStyles;if(C){var z=this;if(!w.styles){w.styles=c.merge(w.data,{})}for(var E in this["nodeStylesOn"+A]){var x="$"+E;if(!(x in w.styles)){w.styles[x]=w.getData(E)}}D.fx.nodeFx(c.extend({elements:{id:w.id,properties:z["nodeStylesOn"+A]},transition:i.Quart.easeOut,duration:300,fps:40},this.config))}else{var y=this.getRestoredStyles(w,A);D.fx.nodeFx(c.extend({elements:{id:w.id,properties:y},transition:i.Quart.easeOut,duration:300,fps:40},this.config))}},onClick:function(w){if(!w){return}var x=this.nodeStylesOnClick;if(!x){return}if(w.selected){this.toggleStylesOnClick(w,false);delete w.selected}else{this.viz.graph.eachNode(function(z){if(z.selected){for(var y in x){z.setData(y,z.styles["$"+y],"end")}delete z.selected}});this.toggleStylesOnClick(w,true);w.selected=true;delete w.hovered;this.hoveredNode=false}},onMouseMove:function(C,B,z){if(this.down){this.move=true}if(this.dom&&this.isLabel(C,B)){return}var A=this.nodeStylesOnHover;if(!A){return}if(!this.dom){if(this.hoveredNode){var x=this.types[this.hoveredNode.getData("type")];var w=x&&x.contains&&x.contains.call(this.fx,this.hoveredNode,z.getPos());if(w){return}}var y=z.getNode();if(!this.hoveredNode&&!y){return}if(y.hovered){return}if(y&&!y.selected){this.fx.nodeFxAnimation.stopTimer();this.viz.graph.eachNode(function(E){if(E.hovered&&!E.selected){for(var D in A){E.setData(D,E.styles["$"+D],"end")}delete E.hovered}});y.hovered=true;this.hoveredNode=y;this.toggleStylesOnHover(y,true)}else{if(this.hoveredNode&&!this.hoveredNode.selected){this.fx.nodeFxAnimation.stopTimer();this.toggleStylesOnHover(this.hoveredNode,false);delete this.hoveredNode.hovered;this.hoveredNode=false}}}}});o.Classes.Navigation=new q({Implements:[t,h],initializePost:function(){this.pos=false;this.pressed=false},onMouseWheel:function(z,y,w){if(!this.config.zooming){return}c.event.stop(c.event.get(z,y));var A=this.config.zooming/1000,x=1+w*A;this.canvas.scale(x,x)},onMouseDown:function(B,A,z){if(!this.config.panning){return}if(this.config.panning=="avoid nodes"&&z.getNode()){return}this.pressed=true;this.pos=z.getPos();var y=this.canvas,x=y.translateOffsetX,w=y.translateOffsetY,D=y.scaleOffsetX,C=y.scaleOffsetY;this.pos.x*=D;this.pos.x+=x;this.pos.y*=C;this.pos.y+=w},onMouseMove:function(D,C,F){if(!this.config.panning){return}if(!this.pressed){return}if(this.config.panning=="avoid nodes"&&F.getNode()){return}var B=this.pos,E=F.getPos(),z=this.canvas,A=z.translateOffsetX,w=z.translateOffsetY,J=z.scaleOffsetX,H=z.scaleOffsetY;E.x*=J;E.y*=H;E.x+=A;E.y+=w;var I=E.x-B.x,G=E.y-B.y;this.pos=E;this.canvas.translate(I*1/J,G*1/H)},onMouseUp:function(z,y,x,w){if(!this.config.panning){return}this.pressed=false}});var l;(function(){var w=typeof HTMLCanvasElement,y=(w=="object"||w=="function");function x(z,A){var B=document.createElement(z);for(var C in A){if(typeof A[C]=="object"){c.extend(B[C],A[C])}else{B[C]=A[C]}}if(z=="canvas"&&!y&&G_vmlCanvasManager){B=G_vmlCanvasManager.initElement(document.body.appendChild(B))}return B}$jit.Canvas=l=new q({canvases:[],pos:false,element:false,labelContainer:false,translateOffsetX:0,translateOffsetY:0,scaleOffsetX:1,scaleOffsetY:1,initialize:function(K,E){this.viz=K;this.opt=E;var B=c.type(E.injectInto)=="string"?E.injectInto:E.injectInto.id,C=B+"-label",z=c(B),D=E.width||z.offsetWidth,L=E.height||z.offsetHeight;this.id=B;var F={injectInto:B,width:D,height:L};this.element=x("div",{id:B+"-canvaswidget",style:{position:"relative",width:D+"px",height:L+"px"}});this.labelContainer=this.createLabelContainer(E.Label.type,C,F);this.canvases.push(new l.Base({config:c.extend({idSuffix:"-canvas"},F),plot:function(M){K.fx.plot()},resize:function(){K.refresh()}}));var G=E.background;if(G){var J=new l.Background[G.type](K,c.extend(G,F));this.canvases.push(new l.Base(J))}var I=this.canvases.length;while(I--){this.element.appendChild(this.canvases[I].canvas);if(I>0){this.canvases[I].plot()}}this.element.appendChild(this.labelContainer);z.appendChild(this.element);var A=null,H=this;c.addEvent(window,"scroll",function(){clearTimeout(A);A=setTimeout(function(){H.getPos(true)},500)})},getCtx:function(z){return this.canvases[z||0].getCtx()},getConfig:function(){return this.opt},getElement:function(){return this.element},getSize:function(z){return this.canvases[z||0].getSize()},resize:function(D,z){this.getPos(true);this.translateOffsetX=this.translateOffsetY=0;this.scaleOffsetX=this.scaleOffsetY=1;for(var B=0,A=this.canvases.length;B<A;B++){this.canvases[B].resize(D,z)}var C=this.element.style;C.width=D+"px";C.height=z+"px";if(this.labelContainer){this.labelContainer.style.width=D+"px"}},translate:function(z,D,C){this.translateOffsetX+=z*this.scaleOffsetX;this.translateOffsetY+=D*this.scaleOffsetY;for(var B=0,A=this.canvases.length;B<A;B++){this.canvases[B].translate(z,D,C)}},scale:function(E,B,C){var F=this.scaleOffsetX*E,D=this.scaleOffsetY*B;var H=this.translateOffsetX*(E-1)/F,G=this.translateOffsetY*(B-1)/D;this.scaleOffsetX=F;this.scaleOffsetY=D;for(var A=0,z=this.canvases.length;A<z;A++){this.canvases[A].scale(E,B,true)}this.translate(H,G,false)},getPos:function(z){if(z||!this.pos){return this.pos=c.getPos(this.getElement())}return this.pos},clear:function(z){this.canvases[z||0].clear()},path:function(A,B){var z=this.canvases[0].getCtx();z.beginPath();B(z);z[A]();z.closePath()},createLabelContainer:function(B,F,E){var D="http://www.w3.org/2000/svg";if(B=="HTML"||B=="Native"){return x("div",{id:F,style:{overflow:"visible",position:"absolute",top:0,left:0,width:E.width+"px",height:0}})}else{if(B=="SVG"){var C=document.createElementNS(D,"svg:svg");C.setAttribute("width",E.width);C.setAttribute("height",E.height);var A=C.style;A.position="absolute";A.left=A.top="0px";var z=document.createElementNS(D,"svg:g");z.setAttribute("width",E.width);z.setAttribute("height",E.height);z.setAttribute("x",0);z.setAttribute("y",0);z.setAttribute("id",F);C.appendChild(z);return C}}}});l.Base=new q({translateOffsetX:0,translateOffsetY:0,scaleOffsetX:1,scaleOffsetY:1,initialize:function(z){this.viz=z;this.opt=z.config;this.size=false;this.createCanvas();this.translateToCenter()},createCanvas:function(){var A=this.opt,B=A.width,z=A.height;this.canvas=x("canvas",{id:A.injectInto+A.idSuffix,width:B,height:z,style:{position:"absolute",top:0,left:0,width:B+"px",height:z+"px"}})},getCtx:function(){if(!this.ctx){return this.ctx=this.canvas.getContext("2d")}return this.ctx},getSize:function(){if(this.size){return this.size}var z=this.canvas;return this.size={width:z.width,height:z.height}},translateToCenter:function(C){var A=this.getSize(),B=C?(A.width-C.width-this.translateOffsetX*2):A.width;height=C?(A.height-C.height-this.translateOffsetY*2):A.height;var z=this.getCtx();C&&z.scale(1/this.scaleOffsetX,1/this.scaleOffsetY);z.translate(B/2,height/2)},resize:function(C,z){var B=this.getSize(),A=this.canvas,D=A.style;this.size=false;A.width=C;A.height=z;D.width=C+"px";D.height=z+"px";if(!y){this.translateToCenter(B)}else{this.translateToCenter()}this.translateOffsetX=this.translateOffsetY=0;this.scaleOffsetX=this.scaleOffsetY=1;this.clear();this.viz.resize(C,z,this)},translate:function(z,D,A){var C=this.scaleOffsetX,B=this.scaleOffsetY;this.translateOffsetX+=z*C;this.translateOffsetY+=D*B;this.getCtx().translate(z,D);!A&&this.plot()},scale:function(z,B,A){this.scaleOffsetX*=z;this.scaleOffsetY*=B;this.getCtx().scale(z,B);!A&&this.plot()},clear:function(){var B=this.getSize(),A=this.translateOffsetX,z=this.translateOffsetY,D=this.scaleOffsetX,C=this.scaleOffsetY;this.getCtx().clearRect((-B.width/2-A)*1/D,(-B.height/2-z)*1/C,B.width*1/D,B.height*1/C)},plot:function(){this.clear();this.viz.plot(this)}});l.Background={};l.Background.Circles=new q({initialize:function(z,A){this.viz=z;this.config=c.merge({idSuffix:"-bkcanvas",levelDistance:100,numberOfCircles:6,CanvasStyles:{},offset:0},A)},resize:function(A,z,B){this.plot(B)},plot:function(z){var A=z.canvas,G=z.getCtx(),D=this.config,F=D.CanvasStyles;for(var H in F){G[H]=F[H]}var B=D.numberOfCircles,E=D.levelDistance;for(var C=1;C<=B;C++){G.beginPath();G.arc(0,0,E*C,0,2*Math.PI,false);G.stroke();G.closePath()}}})})();var b=function(x,w){this.theta=x;this.rho=w};$jit.Polar=b;b.prototype={getc:function(w){return this.toComplex(w)},getp:function(){return this},set:function(w){w=w.getp();this.theta=w.theta;this.rho=w.rho},setc:function(w,z){this.rho=Math.sqrt(w*w+z*z);this.theta=Math.atan2(z,w);if(this.theta<0){this.theta+=Math.PI*2}},setp:function(x,w){this.theta=x;this.rho=w},clone:function(){return new b(this.theta,this.rho)},toComplex:function(A){var w=Math.cos(this.theta)*this.rho;var z=Math.sin(this.theta)*this.rho;if(A){return{x:w,y:z}}return new p(w,z)},add:function(w){return new b(this.theta+w.theta,this.rho+w.rho)},scale:function(w){return new b(this.theta,this.rho*w)},equals:function(w){return this.theta==w.theta&&this.rho==w.rho},$add:function(w){this.theta=this.theta+w.theta;this.rho+=w.rho;return this},$madd:function(w){this.theta=(this.theta+w.theta)%(Math.PI*2);this.rho+=w.rho;return this},$scale:function(w){this.rho*=w;return this},interpolate:function(y,F){var z=Math.PI,C=z*2;var x=function(H){var G=(H<0)?(H%C)+C:H%C;return G};var B=this.theta,E=y.theta;var A,D=Math.abs(B-E);if(D==z){if(B>E){A=x((E+((B-C)-E)*F))}else{A=x((E-C+(B-(E))*F))}}else{if(D>=z){if(B>E){A=x((E+((B-C)-E)*F))}else{A=x((E-C+(B-(E-C))*F))}}else{A=x((E+(B-E)*F))}}var w=(this.rho-y.rho)*F+y.rho;return{theta:A,rho:w}}};var k=function(x,w){return new b(x,w)};b.KER=k(0,0);var p=function(w,z){this.x=w;this.y=z};$jit.Complex=p;p.prototype={getc:function(){return this},getp:function(w){return this.toPolar(w)},set:function(w){w=w.getc(true);this.x=w.x;this.y=w.y},setc:function(w,z){this.x=w;this.y=z},setp:function(x,w){this.x=Math.cos(x)*w;this.y=Math.sin(x)*w},clone:function(){return new p(this.x,this.y)},toPolar:function(y){var w=this.norm();var x=Math.atan2(this.y,this.x);if(x<0){x+=Math.PI*2}if(y){return{theta:x,rho:w}}return new b(x,w)},norm:function(){return Math.sqrt(this.squaredNorm())},squaredNorm:function(){return this.x*this.x+this.y*this.y},add:function(w){return new p(this.x+w.x,this.y+w.y)},prod:function(w){return new p(this.x*w.x-this.y*w.y,this.y*w.x+this.x*w.y)},conjugate:function(){return new p(this.x,-this.y)},scale:function(w){return new p(this.x*w,this.y*w)},equals:function(w){return this.x==w.x&&this.y==w.y},$add:function(w){this.x+=w.x;this.y+=w.y;return this},$prod:function(A){var w=this.x,z=this.y;this.x=w*A.x-z*A.y;this.y=z*A.x+w*A.y;return this},$conjugate:function(){this.y=-this.y;return this},$scale:function(w){this.x*=w;this.y*=w;return this},$div:function(B){var w=this.x,A=this.y;var z=B.squaredNorm();this.x=w*B.x+A*B.y;this.y=A*B.x-w*B.y;return this.$scale(1/z)}};var r=function(x,w){return new p(x,w)};p.KER=r(0,0);$jit.Graph=new q({initialize:function(y,x,w,C){var A={complex:false,Node:{}};this.Node=x;this.Edge=w;this.Label=C;this.opt=c.merge(A,y||{});this.nodes={};this.edges={};var z=this;this.nodeList={};for(var B in j){z.nodeList[B]=(function(D){return function(){var E=Array.prototype.slice.call(arguments);z.eachNode(function(F){F[D].apply(F,E)})}})(B)}},getNode:function(w){if(this.hasNode(w)){return this.nodes[w]}return false},getByName:function(w){for(var y in this.nodes){var x=this.nodes[y];if(x.name==w){return x}}return false},getAdjacence:function(x,w){if(x in this.edges){return this.edges[x][w]}return false},addNode:function(x){if(!this.nodes[x.id]){var w=this.edges[x.id]={};this.nodes[x.id]=new e.Node(c.extend({id:x.id,name:x.name,data:c.merge(x.data||{},{}),adjacencies:w},this.opt.Node),this.opt.complex,this.Node,this.Edge,this.Label)}return this.nodes[x.id]},addAdjacence:function(z,y,x){if(!this.hasNode(z.id)){this.addNode(z)}if(!this.hasNode(y.id)){this.addNode(y)}z=this.nodes[z.id];y=this.nodes[y.id];if(!z.adjacentTo(y)){var A=this.edges[z.id]=this.edges[z.id]||{};var w=this.edges[y.id]=this.edges[y.id]||{};A[y.id]=w[z.id]=new e.Adjacence(z,y,x,this.Edge,this.Label);return A[y.id]}return this.edges[z.id][y.id]},removeNode:function(y){if(this.hasNode(y)){delete this.nodes[y];var x=this.edges[y];for(var w in x){delete this.edges[w][y]}delete this.edges[y]}},removeAdjacence:function(x,w){delete this.edges[x][w];delete this.edges[w][x]},hasNode:function(w){return w in this.nodes},empty:function(){this.nodes={};this.edges={}}});var e=$jit.Graph;var j;(function(){var w=function(D,F,A,C,E){var B;A=A||"current";D="$"+(D?D+"-":"");if(A=="current"){B=this.data}else{if(A=="start"){B=this.startData}else{if(A=="end"){B=this.endData}}}var z=D+F;if(C){return B[z]}if(!this.Config.overridable){return E[F]||0}return(z in B)?B[z]:((z in this.data)?this.data[z]:(E[F]||0))};var y=function(C,D,B,z){z=z||"current";C="$"+(C?C+"-":"");var A;if(z=="current"){A=this.data}else{if(z=="start"){A=this.startData}else{if(z=="end"){A=this.endData}}}A[C+D]=B};var x=function(B,z){B="$"+(B?B+"-":"");var A=this;c.each(z,function(D){var C=B+D;delete A.data[C];delete A.endData[C];delete A.startData[C]})};j={getData:function(B,z,A){return w.call(this,"",B,z,A,this.Config)},setData:function(B,A,z){y.call(this,"",B,A,z)},setDataset:function(C,D){C=c.splat(C);for(var z in D){for(var B=0,E=c.splat(D[z]),A=C.length;B<A;B++){this.setData(z,E[B],C[B])}}},removeData:function(){x.call(this,"",Array.prototype.slice.call(arguments))},getCanvasStyle:function(B,z,A){return w.call(this,"canvas",B,z,A,this.Config.CanvasStyles)},setCanvasStyle:function(B,A,z){y.call(this,"canvas",B,A,z)},setCanvasStyles:function(C,D){C=c.splat(C);for(var z in D){for(var B=0,E=c.splat(D[z]),A=C.length;B<A;B++){this.setCanvasStyle(z,E[B],C[B])}}},removeCanvasStyle:function(){x.call(this,"canvas",Array.prototype.slice.call(arguments))},getLabelData:function(B,z,A){return w.call(this,"label",B,z,A,this.Label)},setLabelData:function(B,A,z){y.call(this,"label",B,A,z)},setLabelDataset:function(C,D){C=c.splat(C);for(var z in D){for(var B=0,E=c.splat(D[z]),A=C.length;B<A;B++){this.setLabelData(z,E[B],C[B])}}},removeLabelData:function(){x.call(this,"label",Array.prototype.slice.call(arguments))}}})();e.Node=new q({initialize:function(y,A,x,w,B){var z={id:"",name:"",data:{},startData:{},endData:{},adjacencies:{},selected:false,drawn:false,exist:false,angleSpan:{begin:0,end:0},pos:(A&&r(0,0))||k(0,0),startPos:(A&&r(0,0))||k(0,0),endPos:(A&&r(0,0))||k(0,0)};c.extend(this,c.extend(z,y));this.Config=this.Node=x;this.Edge=w;this.Label=B},adjacentTo:function(w){return w.id in this.adjacencies},getAdjacency:function(w){return this.adjacencies[w]},getPos:function(w){w=w||"current";if(w=="current"){return this.pos}else{if(w=="end"){return this.endPos}else{if(w=="start"){return this.startPos}}}},setPos:function(x,w){w=w||"current";var y;if(w=="current"){y=this.pos}else{if(w=="end"){y=this.endPos}else{if(w=="start"){y=this.startPos}}}y.set(x)}});e.Node.implement(j);e.Adjacence=new q({initialize:function(x,A,y,w,z){this.nodeFrom=x;this.nodeTo=A;this.data=y||{};this.startData={};this.endData={};this.Config=this.Edge=w;this.Label=z}});e.Adjacence.implement(j);e.Util={filter:function(x){if(!x||!(c.type(x)=="string")){return function(){return true}}var w=x.split(" ");return function(z){for(var y=0;y<w.length;y++){if(z[w[y]]){return false}}return true}},getNode:function(w,x){return w.nodes[x]},eachNode:function(A,z,w){var y=this.filter(w);for(var x in A.nodes){if(y(A.nodes[x])){z(A.nodes[x])}}},eachAdjacency:function(B,C,x){var y=B.adjacencies,A=this.filter(x);for(var D in y){var w=y[D];if(A(w)){if(w.nodeFrom!=B){var z=w.nodeFrom;w.nodeFrom=w.nodeTo;w.nodeTo=z}C(w,D)}}},computeLevels:function(C,D,z,y){z=z||0;var A=this.filter(y);this.eachNode(C,function(E){E._flag=false;E._depth=-1},y);var x=C.getNode(D);x._depth=z;var w=[x];while(w.length!=0){var B=w.pop();B._flag=true;this.eachAdjacency(B,function(E){var F=E.nodeTo;if(F._flag==false&&A(F)){if(F._depth<0){F._depth=B._depth+1+z}w.unshift(F)}},y)}},eachBFS:function(B,C,A,x){var y=this.filter(x);this.clean(B);var w=[B.getNode(C)];while(w.length!=0){var z=w.pop();z._flag=true;A(z,z._depth);this.eachAdjacency(z,function(D){var E=D.nodeTo;if(E._flag==false&&y(E)){E._flag=true;w.unshift(E)}},x)}},eachLevel:function(A,E,x,B,z){var D=A._depth,w=this.filter(z),C=this;x=x===false?Number.MAX_VALUE-D:x;(function y(H,F,G){var I=H._depth;if(I>=F&&I<=G&&w(H)){B(H,I)}if(I<G){C.eachAdjacency(H,function(J){var K=J.nodeTo;if(K._depth>I){y(K,F,G)}})}})(A,E+D,x+D)},eachSubgraph:function(x,y,w){this.eachLevel(x,0,false,y,w)},eachSubnode:function(x,y,w){this.eachLevel(x,1,1,y,w)},anySubnode:function(z,y,x){var w=false;y=y||c.lambda(true);var A=c.type(y)=="string"?function(B){return B[y]}:y;this.eachSubnode(z,function(B){if(A(B)){w=true}},x);return w},getSubnodes:function(B,C,w){var y=[],A=this;C=C||0;var z,x;if(c.type(C)=="array"){z=C[0];x=C[1]}else{z=C;x=Number.MAX_VALUE-B._depth}this.eachLevel(B,z,x,function(D){y.push(D)},w);return y},getParents:function(x){var w=[];this.eachAdjacency(x,function(y){var z=y.nodeTo;if(z._depth<x._depth){w.push(z)}});return w},isDescendantOf:function(z,A){if(z.id==A){return true}var y=this.getParents(z),w=false;for(var x=0;!w&&x<y.length;x++){w=w||this.isDescendantOf(y[x],A)}return w},clean:function(w){this.eachNode(w,function(x){x._flag=false})},getClosestNodeToOrigin:function(x,y,w){return this.getClosestNodeToPos(x,b.KER,y,w)},getClosestNodeToPos:function(y,B,A,w){var x=null;A=A||"current";B=B&&B.getc(true)||p.KER;var z=function(D,C){var F=D.x-C.x,E=D.y-C.y;return F*F+E*E};this.eachNode(y,function(C){x=(x==null||z(C.getPos(A).getc(true),B)<z(x.getPos(A).getc(true),B))?C:x},w);return x}};c.each(["getNode","eachNode","computeLevels","eachBFS","clean","getClosestNodeToPos","getClosestNodeToOrigin"],function(w){e.prototype[w]=function(){return e.Util[w].apply(e.Util,[this].concat(Array.prototype.slice.call(arguments)))}});c.each(["eachAdjacency","eachLevel","eachSubgraph","eachSubnode","anySubnode","getSubnodes","getParents","isDescendantOf"],function(w){e.Node.prototype[w]=function(){return e.Util[w].apply(e.Util,[this].concat(Array.prototype.slice.call(arguments)))}});e.Op={options:{type:"nothing",duration:2000,hideLabels:true,fps:30},initialize:function(w){this.viz=w},removeNode:function(B,z){var w=this.viz;var x=c.merge(this.options,w.controller,z);var D=c.splat(B);var y,A,C;switch(x.type){case"nothing":for(y=0;y<D.length;y++){w.graph.removeNode(D[y])}break;case"replot":this.removeNode(D,{type:"nothing"});w.labels.clearLabels();w.refresh(true);break;case"fade:seq":case"fade":A=this;for(y=0;y<D.length;y++){C=w.graph.getNode(D[y]);C.setData("alpha",0,"end")}w.fx.animate(c.merge(x,{modes:["node-property:alpha"],onComplete:function(){A.removeNode(D,{type:"nothing"});w.labels.clearLabels();w.reposition();w.fx.animate(c.merge(x,{modes:["linear"]}))}}));break;case"fade:con":A=this;for(y=0;y<D.length;y++){C=w.graph.getNode(D[y]);C.setData("alpha",0,"end");C.ignore=true}w.reposition();w.fx.animate(c.merge(x,{modes:["node-property:alpha","linear"],onComplete:function(){A.removeNode(D,{type:"nothing"})}}));break;case"iter":A=this;w.fx.sequence({condition:function(){return D.length!=0},step:function(){A.removeNode(D.shift(),{type:"nothing"});w.labels.clearLabels()},onComplete:function(){x.onComplete()},duration:Math.ceil(x.duration/D.length)});break;default:this.doError()}},removeEdge:function(D,B){var w=this.viz;var z=c.merge(this.options,w.controller,B);var y=(c.type(D[0])=="string")?[D]:D;var A,C,x;switch(z.type){case"nothing":for(A=0;A<y.length;A++){w.graph.removeAdjacence(y[A][0],y[A][1])}break;case"replot":this.removeEdge(y,{type:"nothing"});w.refresh(true);break;case"fade:seq":case"fade":C=this;for(A=0;A<y.length;A++){x=w.graph.getAdjacence(y[A][0],y[A][1]);if(x){x.setData("alpha",0,"end")}}w.fx.animate(c.merge(z,{modes:["edge-property:alpha"],onComplete:function(){C.removeEdge(y,{type:"nothing"});w.reposition();w.fx.animate(c.merge(z,{modes:["linear"]}))}}));break;case"fade:con":C=this;for(A=0;A<y.length;A++){x=w.graph.getAdjacence(y[A][0],y[A][1]);if(x){x.setData("alpha",0,"end");x.ignore=true}}w.reposition();w.fx.animate(c.merge(z,{modes:["edge-property:alpha","linear"],onComplete:function(){C.removeEdge(y,{type:"nothing"})}}));break;case"iter":C=this;w.fx.sequence({condition:function(){return y.length!=0},step:function(){C.removeEdge(y.shift(),{type:"nothing"});w.labels.clearLabels()},onComplete:function(){z.onComplete()},duration:Math.ceil(z.duration/y.length)});break;default:this.doError()}},sum:function(A,z){var w=this.viz;var y=c.merge(this.options,w.controller,z),x=w.root;var C;w.root=z.id||w.root;switch(y.type){case"nothing":C=w.construct(A);C.eachNode(function(E){E.eachAdjacency(function(F){w.graph.addAdjacence(F.nodeFrom,F.nodeTo,F.data)})});break;case"replot":w.refresh(true);this.sum(A,{type:"nothing"});w.refresh(true);break;case"fade:seq":case"fade":case"fade:con":that=this;C=w.construct(A);var D=this.preprocessSum(C);var B=!D?["node-property:alpha"]:["node-property:alpha","edge-property:alpha"];w.reposition();if(y.type!="fade:con"){w.fx.animate(c.merge(y,{modes:["linear"],onComplete:function(){w.fx.animate(c.merge(y,{modes:B,onComplete:function(){y.onComplete()}}))}}))}else{w.graph.eachNode(function(E){if(E.id!=x&&E.pos.getp().equals(b.KER)){E.pos.set(E.endPos);E.startPos.set(E.endPos)}});w.fx.animate(c.merge(y,{modes:["linear"].concat(B)}))}break;default:this.doError()}},morph:function(E,x,z){var B=this.viz;var F=c.merge(this.options,B.controller,x),A=B.root;var C;B.root=x.id||B.root;switch(F.type){case"nothing":C=B.construct(E);C.eachNode(function(I){var H=B.graph.hasNode(I.id);I.eachAdjacency(function(M){var L=!!B.graph.getAdjacence(M.nodeFrom.id,M.nodeTo.id);B.graph.addAdjacence(M.nodeFrom,M.nodeTo,M.data);if(L){var K=B.graph.getAdjacence(M.nodeFrom.id,M.nodeTo.id);for(var N in (M.data||{})){K.data[N]=M.data[N]}}});if(H){var G=B.graph.getNode(I.id);for(var J in (I.data||{})){G.data[J]=I.data[J]}}});B.graph.eachNode(function(G){G.eachAdjacency(function(H){if(!C.getAdjacence(H.nodeFrom.id,H.nodeTo.id)){B.graph.removeAdjacence(H.nodeFrom.id,H.nodeTo.id)}});if(!C.hasNode(G.id)){B.graph.removeNode(G.id)}});break;case"replot":B.labels.clearLabels(true);this.morph(E,{type:"nothing"});B.refresh(true);B.refresh(true);break;case"fade:seq":case"fade":case"fade:con":that=this;C=B.construct(E);var D=z&&("node-property" in z)&&c.map(c.splat(z["node-property"]),function(G){return"$"+G});B.graph.eachNode(function(H){var I=C.getNode(H.id);if(!I){H.setData("alpha",1);H.setData("alpha",1,"start");H.setData("alpha",0,"end");H.ignore=true}else{var G=I.data;for(var J in G){if(D&&(c.indexOf(D,J)>-1)){H.endData[J]=G[J]}else{H.data[J]=G[J]}}}});B.graph.eachNode(function(G){if(G.ignore){return}G.eachAdjacency(function(H){if(H.nodeFrom.ignore||H.nodeTo.ignore){return}var I=C.getNode(H.nodeFrom.id);var J=C.getNode(H.nodeTo.id);if(!I.adjacentTo(J)){var H=B.graph.getAdjacence(I.id,J.id);w=true;H.setData("alpha",1);H.setData("alpha",1,"start");H.setData("alpha",0,"end")}})});var w=this.preprocessSum(C);var y=!w?["node-property:alpha"]:["node-property:alpha","edge-property:alpha"];y[0]=y[0]+((z&&("node-property" in z))?(":"+c.splat(z["node-property"]).join(":")):"");y[1]=(y[1]||"edge-property:alpha")+((z&&("edge-property" in z))?(":"+c.splat(z["edge-property"]).join(":")):"");if(z&&("label-property" in z)){y.push("label-property:"+c.splat(z["label-property"]).join(":"))}B.reposition();B.graph.eachNode(function(G){if(G.id!=A&&G.pos.getp().equals(b.KER)){G.pos.set(G.endPos);G.startPos.set(G.endPos)}});B.fx.animate(c.merge(F,{modes:["polar"].concat(y),onComplete:function(){B.graph.eachNode(function(G){if(G.ignore){B.graph.removeNode(G.id)}});B.graph.eachNode(function(G){G.eachAdjacency(function(H){if(H.ignore){B.graph.removeAdjacence(H.nodeFrom.id,H.nodeTo.id)}})});F.onComplete()}}));break;default:}},contract:function(y,x){var w=this.viz;if(y.collapsed||!y.anySubnode(c.lambda(true))){return}x=c.merge(this.options,w.config,x||{},{modes:["node-property:alpha:span","linear"]});y.collapsed=true;(function z(A){A.eachSubnode(function(B){B.ignore=true;B.setData("alpha",0,x.type=="animate"?"end":"current");z(B)})})(y);if(x.type=="animate"){w.compute("end");if(w.rotated){w.rotate(w.rotated,"none",{property:"end"})}(function z(A){A.eachSubnode(function(B){B.setPos(y.getPos("end"),"end");z(B)})})(y);w.fx.animate(x)}else{if(x.type=="replot"){w.refresh()}}},expand:function(y,x){if(!("collapsed" in y)){return}var w=this.viz;x=c.merge(this.options,w.config,x||{},{modes:["node-property:alpha:span","linear"]});delete y.collapsed;(function z(A){A.eachSubnode(function(B){delete B.ignore;B.setData("alpha",1,x.type=="animate"?"end":"current");z(B)})})(y);if(x.type=="animate"){w.compute("end");if(w.rotated){w.rotate(w.rotated,"none",{property:"end"})}w.fx.animate(x)}else{if(x.type=="replot"){w.refresh()}}},preprocessSum:function(x){var w=this.viz;x.eachNode(function(z){if(!w.graph.hasNode(z.id)){w.graph.addNode(z);var A=w.graph.getNode(z.id);A.setData("alpha",0);A.setData("alpha",0,"start");A.setData("alpha",1,"end")}});var y=false;x.eachNode(function(z){z.eachAdjacency(function(A){var B=w.graph.getNode(A.nodeFrom.id);var C=w.graph.getNode(A.nodeTo.id);if(!B.adjacentTo(C)){var A=w.graph.addAdjacence(B,C,A.data);if(B.startAlpha==B.endAlpha&&C.startAlpha==C.endAlpha){y=true;A.setData("alpha",0);A.setData("alpha",0,"start");A.setData("alpha",1,"end")}}})});return y}};var a={none:{render:c.empty,contains:c.lambda(false)},circle:{render:function(z,A,w,y){var x=y.getCtx();x.beginPath();x.arc(A.x,A.y,w,0,Math.PI*2,true);x.closePath();x[z]()},contains:function(B,A,w){var y=B.x-A.x,x=B.y-A.y,z=y*y+x*x;return z<=w*w}},ellipse:{render:function(A,B,z,w,y){var x=y.getCtx();w/=2;z/=2;x.save();x.scale(z/w,w/z);x.beginPath();x.arc(B.x*(w/z),B.y*(z/w),w,0,Math.PI*2,true);x.closePath();x[A]();x.restore()},contains:function(D,C,z,w){z/=2;w/=2;var B=(z+w)/2,y=D.x-C.x,x=D.y-C.y,A=y*y+x*x;return A<=B*B}},square:{render:function(x,z,y,w){w.getCtx()[x+"Rect"](z.x-y,z.y-y,2*y,2*y)},contains:function(y,x,w){return Math.abs(x.x-y.x)<=w&&Math.abs(x.y-y.y)<=w}},rectangle:{render:function(z,A,y,w,x){x.getCtx()[z+"Rect"](A.x-y/2,A.y-w/2,y,w)},contains:function(z,y,x,w){return Math.abs(y.x-z.x)<=x/2&&Math.abs(y.y-z.y)<=w/2}},triangle:{render:function(C,D,z,w){var G=w.getCtx(),y=D.x,x=D.y-z,F=y-z,E=D.y+z,B=y+z,A=E;G.beginPath();G.moveTo(y,x);G.lineTo(F,E);G.lineTo(B,A);G.closePath();G[C]()},contains:function(y,x,w){return a.circle.contains(y,x,w)}},star:{render:function(A,C,B,x){var w=x.getCtx(),z=Math.PI/5;w.save();w.translate(C.x,C.y);w.beginPath();w.moveTo(B,0);for(var y=0;y<9;y++){w.rotate(z);if(y%2==0){w.lineTo((B/0.525731)*0.200811,0)}else{w.lineTo(B,0)}}w.closePath();w[A]();w.restore()},contains:function(y,x,w){return a.circle.contains(y,x,w)}}};var m={line:{render:function(z,y,x){var w=x.getCtx();w.beginPath();w.moveTo(z.x,z.y);w.lineTo(y.x,y.y);w.stroke()},contains:function(G,y,B,E){var z=Math.min,C=Math.max,x=z(G.x,y.x),F=C(G.x,y.x),w=z(G.y,y.y),D=C(G.y,y.y);if(B.x>=x&&B.x<=F&&B.y>=w&&B.y<=D){if(Math.abs(y.x-G.x)<=E){return true}var A=(y.y-G.y)/(y.x-G.x)*(B.x-G.x)+G.y;return Math.abs(A-B.y)<=E}return false}},arrow:{render:function(F,G,z,x,w){var H=w.getCtx();if(x){var y=F;F=G;G=y}var C=new p(G.x-F.x,G.y-F.y);C.$scale(z/C.norm());var A=new p(G.x-C.x,G.y-C.y),B=new p(-C.y/2,C.x/2),E=A.add(B),D=A.$add(B.$scale(-1));H.beginPath();H.moveTo(F.x,F.y);H.lineTo(G.x,G.y);H.stroke();H.beginPath();H.moveTo(E.x,E.y);H.lineTo(D.x,D.y);H.lineTo(G.x,G.y);H.closePath();H.fill()},contains:function(x,w,z,y){return m.line.contains(x,w,z,y)}},hyperline:{render:function(D,E,w,y){var F=y.getCtx();var z=A(D,E);if(z.a>1000||z.b>1000||z.ratio<0){F.beginPath();F.moveTo(D.x*w,D.y*w);F.lineTo(E.x*w,E.y*w);F.stroke()}else{var C=Math.atan2(E.y-z.y,E.x-z.x);var B=Math.atan2(D.y-z.y,D.x-z.x);var x=x(C,B);F.beginPath();F.arc(z.x*w,z.y*w,z.ratio*w,C,B,x);F.stroke()}function A(S,R){var K=(S.x*R.y-S.y*R.x),G=K;var J=S.squaredNorm(),I=R.squaredNorm();if(K==0){return{x:0,y:0,ratio:-1}}var Q=(S.y*I-R.y*J+S.y-R.y)/K;var O=(R.x*J-S.x*I+R.x-S.x)/G;var P=-Q/2;var N=-O/2;var M=(Q*Q+O*O)/4-1;if(M<0){return{x:0,y:0,ratio:-1}}var L=Math.sqrt(M);var H={x:P,y:N,ratio:L>1000?-1:L,a:Q,b:O};return H}function x(G,H){return(G<H)?((G+Math.PI>H)?false:true):((H+Math.PI>G)?true:false)}},contains:c.lambda(false)}};e.Plot={initialize:function(x,w){this.viz=x;this.config=x.config;this.node=x.config.Node;this.edge=x.config.Edge;this.animation=new u;this.nodeTypes=new w.Plot.NodeTypes;this.edgeTypes=new w.Plot.EdgeTypes;this.labels=x.labels},nodeHelper:a,edgeHelper:m,Interpolator:{map:{border:"color",color:"color",width:"number",height:"number",dim:"number",alpha:"number",lineWidth:"number",angularWidth:"number",span:"number",valueArray:"array-number",dimArray:"array-number"},canvas:{globalAlpha:"number",fillStyle:"color",strokeStyle:"color",lineWidth:"number",shadowBlur:"number",shadowColor:"color",shadowOffsetX:"number",shadowOffsetY:"number",miterLimit:"number"},label:{size:"number",color:"color"},compute:function(y,x,w){return y+(x-y)*w},moebius:function(D,C,F,z){var B=z.scale(-F);if(B.norm()<1){var w=B.x,E=B.y;var A=D.startPos.getc().moebiusTransformation(B);D.pos.setc(A.x,A.y);B.x=w;B.y=E}},linear:function(x,w,A){var z=x.startPos.getc(true);var y=x.endPos.getc(true);x.pos.setc(this.compute(z.x,y.x,A),this.compute(z.y,y.y,A))},polar:function(y,x,B){var A=y.startPos.getp(true);var z=y.endPos.getp();var w=z.interpolate(A,B);y.pos.setp(w.theta,w.rho)},number:function(x,C,B,w,A){var z=x[w](C,"start");var y=x[w](C,"end");x[A](C,this.compute(z,y,B))},color:function(y,w,E,B,z){var C=c.hexToRgb(y[B](w,"start"));var D=c.hexToRgb(y[B](w,"end"));var A=this.compute;var x=c.rgbToHex([parseInt(A(C[0],D[0],E)),parseInt(A(C[1],D[1],E)),parseInt(A(C[2],D[2],E))]);y[z](w,x)},"array-number":function(z,y,J,G,B){var H=z[G](y,"start"),I=z[G](y,"end"),K=[];for(var E=0,A=H.length;E<A;E++){var x=H[E],w=I[E];if(x.length){for(var D=0,F=x.length,C=[];D<F;D++){C.push(this.compute(x[D],w[D],J))}K.push(C)}else{K.push(this.compute(x,w,J))}}z[B](y,K)},node:function(x,C,E,w,D,y){w=this[w];if(C){var B=C.length;for(var z=0;z<B;z++){var A=C[z];this[w[A]](x,A,E,D,y)}}else{for(var A in w){this[w[A]](x,A,E,D,y)}}},edge:function(y,x,D,z,w,C){var B=y.adjacencies;for(var A in B){this["node"](B[A],x,D,z,w,C)}},"node-property":function(x,w,y){this["node"](x,w,y,"map","getData","setData")},"edge-property":function(x,w,y){this["edge"](x,w,y,"map","getData","setData")},"label-property":function(x,w,y){this["node"](x,w,y,"label","getLabelData","setLabelData")},"node-style":function(x,w,y){this["node"](x,w,y,"canvas","getCanvasStyle","setCanvasStyle")},"edge-style":function(x,w,y){this["edge"](x,w,y,"canvas","getCanvasStyle","setCanvasStyle")}},sequence:function(x){var y=this;x=c.merge({condition:c.lambda(false),step:c.empty,onComplete:c.empty,duration:200},x||{});var w=setInterval(function(){if(x.condition()){x.step()}else{clearInterval(w);x.onComplete()}y.viz.refresh(true)},x.duration)},prepare:function(C){var B=this.viz.graph,z={"node-property":{getter:"getData",setter:"setData"},"edge-property":{getter:"getData",setter:"setData"},"node-style":{getter:"getCanvasStyle",setter:"setCanvasStyle"},"edge-style":{getter:"getCanvasStyle",setter:"setCanvasStyle"}};var x={};if(c.type(C)=="array"){for(var A=0,w=C.length;A<w;A++){var y=C[A].split(":");x[y.shift()]=y}}else{for(var D in C){if(D=="position"){x[C.position]=[]}else{x[D]=c.splat(C[D])}}}B.eachNode(function(E){E.startPos.set(E.pos);c.each(["node-property","node-style"],function(H){if(H in x){var I=x[H];for(var G=0,F=I.length;G<F;G++){E[z[H].setter](I[G],E[z[H].getter](I[G]),"start")}}});c.each(["edge-property","edge-style"],function(F){if(F in x){var G=x[F];E.eachAdjacency(function(I){for(var J=0,H=G.length;J<H;J++){I[z[F].setter](G[J],I[z[F].getter](G[J]),"start")}})}})});return x},animate:function(z,y){z=c.merge(this.viz.config,z||{});var A=this,x=this.viz,C=x.graph,D=this.Interpolator,B=z.type==="nodefx"?this.nodeFxAnimation:this.animation;var w=this.prepare(z.modes);if(z.hideLabels){this.labels.hideLabels(true)}B.setOptions(c.merge(z,{$animating:false,compute:function(E){C.eachNode(function(F){for(var G in w){D[G](F,w[G],E,y)}});A.plot(z,this.$animating,E);this.$animating=true},complete:function(){if(z.hideLabels){A.labels.hideLabels(false)}A.plot(z);z.onComplete();z.onAfterCompute()}})).start()},nodeFx:function(y){var D=this.viz,E=D.graph,B=this.nodeFxAnimation,F=c.merge(this.viz.config,{elements:{id:false,properties:{}},reposition:false});y=c.merge(F,y||{},{onBeforeCompute:c.empty,onAfterCompute:c.empty});B.stopTimer();var C=y.elements.properties;if(!y.elements.id){E.eachNode(function(H){for(var G in C){H.setData(G,C[G],"end")}})}else{var w=c.splat(y.elements.id);c.each(w,function(I){var H=E.getNode(I);if(H){for(var G in C){H.setData(G,C[G],"end")}}})}var A=[];for(var x in C){A.push(x)}var z=["node-property:"+A.join(":")];if(y.reposition){z.push("linear");D.compute("end")}this.animate(c.merge(y,{modes:z,type:"nodefx"}))},plot:function(x,G){var E=this.viz,B=E.graph,y=E.canvas,w=E.root,C=this,F=y.getCtx(),A=Math.min,x=x||this.viz.controller;x.clearCanvas&&y.clear();var D=B.getNode(w);if(!D){return}var z=!!D.visited;B.eachNode(function(I){var H=I.getData("alpha");I.eachAdjacency(function(J){var K=J.nodeTo;if(!!K.visited===z&&I.drawn&&K.drawn){!G&&x.onBeforePlotLine(J);F.save();F.globalAlpha=A(H,K.getData("alpha"),J.getData("alpha"));C.plotLine(J,y,G);F.restore();!G&&x.onAfterPlotLine(J)}});F.save();if(I.drawn){!G&&x.onBeforePlotNode(I);C.plotNode(I,y,G);!G&&x.onAfterPlotNode(I)}if(!C.labelsHidden&&x.withLabels){if(I.drawn&&H>=0.95){C.labels.plotLabel(y,I,x)}else{C.labels.hideLabel(I,false)}}F.restore();I.visited=!z})},plotTree:function(A,x,E){var B=this,C=this.viz,y=C.canvas,z=this.config,D=y.getCtx();var w=A.getData("alpha");A.eachSubnode(function(G){if(x.plotSubtree(A,G)&&G.exist&&G.drawn){var F=A.getAdjacency(G.id);!E&&x.onBeforePlotLine(F);D.globalAlpha=Math.min(w,G.getData("alpha"));B.plotLine(F,y,E);!E&&x.onAfterPlotLine(F);B.plotTree(G,x,E)}});if(A.drawn){!E&&x.onBeforePlotNode(A);this.plotNode(A,y,E);!E&&x.onAfterPlotNode(A);if(!x.hideLabels&&x.withLabels&&w>=0.95){this.labels.plotLabel(y,A,x)}else{this.labels.hideLabel(A,false)}}else{this.labels.hideLabel(A,true)}},plotNode:function(y,x,F){var C=y.getData("type"),B=this.node.CanvasStyles;if(C!="none"){var w=y.getData("lineWidth"),A=y.getData("color"),z=y.getData("alpha"),D=x.getCtx();D.lineWidth=w;D.fillStyle=D.strokeStyle=A;D.globalAlpha=z;for(var E in B){D[E]=y.getCanvasStyle(E)}this.nodeTypes[C].render.call(this,y,x,F)}},plotLine:function(B,x,E){var A=B.getData("type"),z=this.edge.CanvasStyles;if(A!="none"){var w=B.getData("lineWidth"),y=B.getData("color"),C=x.getCtx();C.lineWidth=w;C.fillStyle=C.strokeStyle=y;for(var D in z){C[D]=B.getCanvasStyle(D)}this.edgeTypes[A].render.call(this,B,x,E)}}};e.Label={};e.Label.Native=new q({plotLabel:function(y,z,x){var w=y.getCtx();var A=z.pos.getc(true);w.font=z.getLabelData("style")+" "+z.getLabelData("size")+"px "+z.getLabelData("family");w.textAlign=z.getLabelData("textAlign");w.fillStyle=w.strokeStyle=z.getLabelData("color");w.textBaseline=z.getLabelData("textBaseline");this.renderLabel(y,z,x)},renderLabel:function(y,z,x){var w=y.getCtx();var A=z.pos.getc(true);w.fillText(z.name,A.x,A.y+z.getData("height")/2)},hideLabel:c.empty,hideLabels:c.empty});e.Label.DOM=new q({labelsHidden:false,labelContainer:false,labels:{},getLabelContainer:function(){return this.labelContainer?this.labelContainer:this.labelContainer=document.getElementById(this.viz.config.labelContainer)},getLabel:function(w){return(w in this.labels&&this.labels[w]!=null)?this.labels[w]:this.labels[w]=document.getElementById(w)},hideLabels:function(x){var w=this.getLabelContainer();if(x){w.style.display="none"}else{w.style.display=""}this.labelsHidden=x},clearLabels:function(w){for(var x in this.labels){if(w||!this.viz.graph.hasNode(x)){this.disposeLabel(x);delete this.labels[x]}}},disposeLabel:function(x){var w=this.getLabel(x);if(w&&w.parentNode){w.parentNode.removeChild(w)}},hideLabel:function(A,w){A=c.splat(A);var x=w?"":"none",y,z=this;c.each(A,function(C){var B=z.getLabel(C.id);if(B){B.style.display=x}})},fitsInCanvas:function(y,w){var x=w.getSize();if(y.x>=x.width||y.x<0||y.y>=x.height||y.y<0){return false}return true}});e.Label.HTML=new q({Implements:e.Label.DOM,plotLabel:function(z,A,y){var B=A.id,w=this.getLabel(B);if(!w&&!(w=document.getElementById(B))){w=document.createElement("div");var x=this.getLabelContainer();w.id=B;w.className="node";w.style.position="absolute";y.onCreateLabel(w,A);x.appendChild(w);this.labels[A.id]=w}this.placeLabel(w,A,y)}});e.Label.SVG=new q({Implements:e.Label.DOM,plotLabel:function(z,B,y){var D=B.id,w=this.getLabel(D);if(!w&&!(w=document.getElementById(D))){var A="http://www.w3.org/2000/svg";w=document.createElementNS(A,"svg:text");var C=document.createElementNS(A,"svg:tspan");w.appendChild(C);var x=this.getLabelContainer();w.setAttribute("id",D);w.setAttribute("class","node");x.appendChild(w);y.onCreateLabel(w,B);this.labels[B.id]=w}this.placeLabel(w,B,y)}});e.Geom=new q({initialize:function(w){this.viz=w;this.config=w.config;this.node=w.config.Node;this.edge=w.config.Edge},translate:function(x,w){w=c.splat(w);this.viz.graph.eachNode(function(y){c.each(w,function(z){y.getPos(z).$add(x)})})},setRightLevelToShow:function(z,w,B){var A=this.getRightLevelToShow(z,w),y=this.viz.labels,x=c.merge({execShow:true,execHide:true,onHide:c.empty,onShow:c.empty},B||{});z.eachLevel(0,this.config.levelsToShow,function(D){var C=D._depth-z._depth;if(C>A){x.onHide(D);if(x.execHide){D.drawn=false;D.exist=false;y.hideLabel(D,false)}}else{x.onShow(D);if(x.execShow){D.exist=true}}});z.drawn=true},getRightLevelToShow:function(z,x){var w=this.config;var A=w.levelsToShow;var y=w.constrained;if(!y){return A}while(!this.treeFitsInCanvas(z,x,A)&&A>1){A--}return A}});var d={construct:function(x){var y=(c.type(x)=="array");var w=new e(this.graphOptions,this.config.Node,this.config.Edge,this.config.Label);if(!y){(function(z,B){z.addNode(B);if(B.children){for(var A=0,C=B.children;A<C.length;A++){z.addAdjacence(B,C[A]);arguments.callee(z,C[A])}}})(w,x)}else{(function(H,I){var A=function(M){for(var L=0,J=I.length;L<J;L++){if(I[L].id==M){return I[L]}}var K={id:M,name:M};return H.addNode(K)};for(var E=0,B=I.length;E<B;E++){H.addNode(I[E]);var F=I[E].adjacencies;if(F){for(var C=0,G=F.length;C<G;C++){var z=F[C],D={};if(typeof F[C]!="string"){D=c.merge(z.data,{});z=z.nodeTo}H.addAdjacence(I[E],A(z),D)}}}})(w,x)}return w},loadJSON:function(x,w){this.json=x;if(this.labels&&this.labels.clearLabels){this.labels.clearLabels(true)}this.graph=this.construct(x);if(c.type(x)!="array"){this.root=x.id}else{this.root=x[w?w:0].id}},toJSON:function(A){A=A||"tree";if(A=="tree"){var y={};var x=this.graph.getNode(this.root);var y=(function w(D){var B={};B.id=D.id;B.name=D.name;B.data=D.data;var C=[];D.eachSubnode(function(E){C.push(w(E))});B.children=C;return B})(x);return y}else{var y=[];var z=!!this.graph.getNode(this.root).visited;this.graph.eachNode(function(C){var B={};B.id=C.id;B.name=C.name;B.data=C.data;var D=[];C.eachAdjacency(function(E){var G=E.nodeTo;if(!!G.visited===z){var F={};F.nodeTo=G.id;F.data=E.data;D.push(F)}});B.adjacencies=D;y.push(B);C.visited=!z});return y}}};var g=$jit.Layouts={};var f={label:null,compute:function(z,A,x){this.initializeLabel(x);var w=this.label,y=w.style;z.eachNode(function(D){var H=D.getData("autoWidth"),I=D.getData("autoHeight");if(H||I){delete D.data.$width;delete D.data.$height;delete D.data.$dim;var B=D.getData("width"),J=D.getData("height");y.width=H?"auto":B+"px";y.height=I?"auto":J+"px";w.innerHTML=D.name;var F=w.offsetWidth,C=w.offsetHeight;var G=D.getData("type");if(c.indexOf(["circle","square","triangle","star"],G)===-1){D.setData("width",F);D.setData("height",C)}else{var E=F>C?F:C;D.setData("width",E);D.setData("height",E);D.setData("dim",E)}}})},initializeLabel:function(w){if(!this.label){this.label=document.createElement("div");document.body.appendChild(this.label)}this.setLabelStyles(w)},setLabelStyles:function(w){c.extend(this.label.style,{visibility:"hidden",position:"absolute",width:"auto",height:"auto"});this.label.className="jit-autoadjust-label"}};g.Tree=(function(){var F=Array.prototype.slice;function D(P,K,H,N,I){var M=K.Node;var J=K.multitree;if(M.overridable){var O=-1,L=-1;P.eachNode(function(S){if(S._depth==H&&(!J||("$orn" in S.data)&&S.data.$orn==N)){var Q=S.getData("width",I);var R=S.getData("height",I);O=(O<Q)?Q:O;L=(L<R)?R:L}});return{width:O<0?M.width:O,height:L<0?M.height:L}}else{return M}}function G(I,L,K,H){var J=(H=="left"||H=="right")?"y":"x";I.getPos(L)[J]+=K}function B(I,J){var H=[];c.each(I,function(K){K=F.call(K);K[0]+=J;K[1]+=J;H.push(K)});return H}function E(K,H){if(K.length==0){return H}if(H.length==0){return K}var J=K.shift(),I=H.shift();return[[J[0],I[1]]].concat(E(K,H))}function z(H,I){I=I||[];if(H.length==0){return I}var J=H.pop();return z(H,E(J,I))}function C(K,I,L,H,J){if(K.length<=J||I.length<=J){return 0}var N=K[J][1],M=I[J][0];return Math.max(C(K,I,L,H,++J)+L,N-M+H)}function A(K,I,H){function J(N,P,M){if(P.length<=M){return[]}var O=P[M],L=C(N,O,I,H,0);return[L].concat(J(E(N,B(O,L)),P,++M))}return J([],K,0)}function x(L,K,J){function H(O,Q,N){if(Q.length<=N){return[]}var P=Q[N],M=-C(P,O,K,J,0);return[M].concat(H(E(B(P,M),O),Q,++N))}L=F.call(L);var I=H([],L.reverse(),0);return I.reverse()}function w(N,L,I,O){var J=A(N,L,I),M=x(N,L,I);if(O=="left"){M=J}else{if(O=="right"){J=M}}for(var K=0,H=[];K<J.length;K++){H[K]=(J[K]+M[K])/2}return H}function y(H,R,I,Y,W){var K=Y.multitree;var Q=["x","y"],N=["width","height"];var J=+(W=="left"||W=="right");var O=Q[J],X=Q[1-J];var T=Y.Node;var M=N[J],V=N[1-J];var L=Y.siblingOffset;var U=Y.subtreeOffset;var S=Y.align;function P(ab,af,aj){var aa=ab.getData(M,I);var ai=af||(ab.getData(V,I));var am=[],ak=[],ag=false;var Z=ai+Y.levelDistance;ab.eachSubnode(function(ao){if(ao.exist&&(!K||("$orn" in ao.data)&&ao.data.$orn==W)){if(!ag){ag=D(H,Y,ao._depth,W,I)}var an=P(ao,ag[V],aj+Z);am.push(an.tree);ak.push(an.extent)}});var ae=w(ak,U,L,S);for(var ad=0,ac=[],ah=[];ad<am.length;ad++){G(am[ad],I,ae[ad],W);ah.push(B(ak[ad],ae[ad]))}var al=[[-aa/2,aa/2]].concat(z(ah));ab.getPos(I)[O]=0;if(W=="top"||W=="left"){ab.getPos(I)[X]=aj}else{ab.getPos(I)[X]=-aj}return{tree:ab,extent:al}}P(R,false,0)}return new q({compute:function(J,I){var K=J||"start";var H=this.graph.getNode(this.root);c.extend(H,{drawn:true,exist:true,selected:true});f.compute(this.graph,K,this.config);if(!!I||!("_depth" in H)){this.graph.computeLevels(this.root,0,"ignore")}this.computePositions(H,K)},computePositions:function(L,H){var J=this.config;var I=J.multitree;var O=J.align;var K=O!=="center"&&J.indent;var P=J.orientation;var N=I?["top","right","bottom","left"]:[P];var M=this;c.each(N,function(Q){y(M.graph,L,H,M.config,Q,H);var R=["x","y"][+(Q=="left"||Q=="right")];(function S(T){T.eachSubnode(function(U){if(U.exist&&(!I||("$orn" in U.data)&&U.data.$orn==Q)){U.getPos(H)[R]+=T.getPos(H)[R];if(K){U.getPos(H)[R]+=O=="left"?K:-K}S(U)}})})(L)})}})})();$jit.ST=(function(){var x=[];function y(D){D=D||this.clickedNode;if(!this.config.constrained){return[]}var A=this.geom;var H=this.graph;var B=this.canvas;var z=D._depth,E=[];H.eachNode(function(I){if(I.exist&&!I.selected){if(I.isDescendantOf(D.id)){if(I._depth<=z){E.push(I)}}else{E.push(I)}}});var F=A.getRightLevelToShow(D,B);D.eachLevel(F,F,function(I){if(I.exist&&!I.selected){E.push(I)}});for(var G=0;G<x.length;G++){var C=this.graph.getNode(x[G]);if(!C.isDescendantOf(D.id)){E.push(C)}}return E}function w(B){var A=[],z=this.config;B=B||this.clickedNode;this.clickedNode.eachLevel(0,z.levelsToShow,function(C){if(z.multitree&&!("$orn" in C.data)&&C.anySubnode(function(D){return D.exist&&!D.drawn})){A.push(C)}else{if(C.drawn&&!C.anySubnode("drawn")){A.push(C)}}});return A}return new q({Implements:[d,o,g.Tree],initialize:function(z){var B=$jit.ST;var A={levelsToShow:2,levelDistance:30,constrained:true,Node:{type:"rectangle"},duration:700,offsetX:0,offsetY:0};this.controller=this.config=c.merge(n("Canvas","Fx","Tree","Node","Edge","Controller","Tips","NodeStyles","Events","Navigation","Label"),A,z);var C=this.config;if(C.useCanvas){this.canvas=C.useCanvas;this.config.labelContainer=this.canvas.id+"-label"}else{if(C.background){C.background=c.merge({type:"Circles"},C.background)}this.canvas=new l(this,C);this.config.labelContainer=(typeof C.injectInto=="string"?C.injectInto:C.injectInto.id)+"-label"}this.graphOptions={complex:true};this.graph=new e(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new B.Label[C.Label.type](this);this.fx=new B.Plot(this,B);this.op=new B.Op(this);this.group=new B.Group(this);this.geom=new B.Geom(this);this.clickedNode=null;this.initializeExtras()},plot:function(){this.fx.plot(this.controller)},switchPosition:function(E,D,C){var z=this.geom,A=this.fx,B=this;if(!A.busy){A.busy=true;this.contract({onComplete:function(){z.switchOrientation(E);B.compute("end",false);A.busy=false;if(D=="animate"){B.onClick(B.clickedNode.id,C)}else{if(D=="replot"){B.select(B.clickedNode.id,C)}}}},E)}},switchAlignment:function(B,A,z){this.config.align=B;if(A=="animate"){this.select(this.clickedNode.id,z)}else{if(A=="replot"){this.onClick(this.clickedNode.id,z)}}},addNodeInPath:function(z){x.push(z);this.select((this.clickedNode&&this.clickedNode.id)||this.root)},clearNodesInPath:function(z){x.length=0;this.select((this.clickedNode&&this.clickedNode.id)||this.root)},refresh:function(){this.reposition();this.select((this.clickedNode&&this.clickedNode.id)||this.root)},reposition:function(){this.graph.computeLevels(this.root,0,"ignore");this.geom.setRightLevelToShow(this.clickedNode,this.canvas);this.graph.eachNode(function(z){if(z.exist){z.drawn=true}});this.compute("end")},requestNodes:function(B,C){var A=c.merge(this.controller,C),z=this.config.levelsToShow;if(A.request){var E=[],D=B._depth;B.eachLevel(0,z,function(F){if(F.drawn&&!F.anySubnode()){E.push(F);F._level=z-(F._depth-D)}});this.group.requestNodes(E,A)}else{A.onComplete()}},contract:function(D,E){var C=this.config.orientation;var z=this.geom,B=this.group;if(E){z.switchOrientation(E)}var A=y.call(this);if(E){z.switchOrientation(C)}B.contract(A,c.merge(this.controller,D))},move:function(A,B){this.compute("end",false);var z=B.Move,C={x:z.offsetX,y:z.offsetY};if(z.enable){this.geom.translate(A.endPos.add(C).$scale(-1),"end")}this.fx.animate(c.merge(this.controller,{modes:["linear"]},B))},expand:function(A,B){var z=w.call(this,A);this.group.expand(z,c.merge(this.controller,B))},selectPath:function(C){var B=this;this.graph.eachNode(function(E){E.selected=false});function D(F){if(F==null||F.selected){return}F.selected=true;c.each(B.group.getSiblings([F])[F.id],function(G){G.exist=true;G.drawn=true});var E=F.getParents();E=(E.length>0)?E[0]:null;D(E)}for(var z=0,A=[C.id].concat(x);z<A.length;z++){D(this.graph.getNode(A[z]))}},setRoot:function(G,F,E){if(this.busy){return}this.busy=true;var D=this,B=this.canvas;var z=this.graph.getNode(this.root);var A=this.graph.getNode(G);function C(){if(this.config.multitree&&A.data.$orn){var I=A.data.$orn;var J={left:"right",right:"left",top:"bottom",bottom:"top"}[I];z.data.$orn=J;(function H(K){K.eachSubnode(function(L){if(L.id!=G){L.data.$orn=J;H(L)}})})(z);delete A.data.$orn}this.root=G;this.clickedNode=A;this.graph.computeLevels(this.root,0,"ignore");this.geom.setRightLevelToShow(A,B,{execHide:false,onShow:function(K){if(!K.drawn){K.drawn=true;K.setData("alpha",1,"end");K.setData("alpha",0);K.pos.setc(A.pos.x,A.pos.y)}}});this.compute("end");this.busy=true;this.fx.animate({modes:["linear","node-property:alpha"],onComplete:function(){D.busy=false;D.onClick(G,{onComplete:function(){E&&E.onComplete()}})}})}delete z.data.$orns;if(F=="animate"){C.call(this);D.selectPath(A)}else{if(F=="replot"){C.call(this);this.select(this.root)}}},addSubtree:function(z,B,A){if(B=="replot"){this.op.sum(z,c.extend({type:"replot"},A||{}))}else{if(B=="animate"){this.op.sum(z,c.extend({type:"fade:seq"},A||{}))}}},removeSubtree:function(E,A,D,C){var B=this.graph.getNode(E),z=[];B.eachLevel(+!A,false,function(F){z.push(F.id)});if(D=="replot"){this.op.removeNode(z,c.extend({type:"replot"},C||{}))}else{if(D=="animate"){this.op.removeNode(z,c.extend({type:"fade:seq"},C||{}))}}},select:function(z,C){var H=this.group,F=this.geom;var D=this.graph.getNode(z),B=this.canvas;var G=this.graph.getNode(this.root);var A=c.merge(this.controller,C);var E=this;A.onBeforeCompute(D);this.selectPath(D);this.clickedNode=D;this.requestNodes(D,{onComplete:function(){H.hide(H.prepare(y.call(E)),A);F.setRightLevelToShow(D,B);E.compute("current");E.graph.eachNode(function(K){var J=K.pos.getc(true);K.startPos.setc(J.x,J.y);K.endPos.setc(J.x,J.y);K.visited=false});var I={x:A.offsetX,y:A.offsetY};E.geom.translate(D.endPos.add(I).$scale(-1),["start","current","end"]);H.show(w.call(E));E.plot();A.onAfterCompute(E.clickedNode);A.onComplete()}})},onClick:function(A,H){var C=this.canvas,G=this,z=this.geom,D=this.config;var F={Move:{enable:true,offsetX:D.offsetX||0,offsetY:D.offsetY||0},setRightLevelToShowConfig:false,onBeforeRequest:c.empty,onBeforeContract:c.empty,onBeforeMove:c.empty,onBeforeExpand:c.empty};var B=c.merge(this.controller,F,H);if(!this.busy){this.busy=true;var E=this.graph.getNode(A);this.selectPath(E,this.clickedNode);this.clickedNode=E;B.onBeforeCompute(E);B.onBeforeRequest(E);this.requestNodes(E,{onComplete:function(){B.onBeforeContract(E);G.contract({onComplete:function(){z.setRightLevelToShow(E,C,B.setRightLevelToShowConfig);B.onBeforeMove(E);G.move(E,{Move:B.Move,onComplete:function(){B.onBeforeExpand(E);G.expand(E,{onComplete:function(){G.busy=false;B.onAfterCompute(A);B.onComplete()}})}})}})}})}}})})();$jit.ST.$extend=true;$jit.ST.Op=new q({Implements:e.Op});$jit.ST.Group=new q({initialize:function(w){this.viz=w;this.canvas=w.canvas;this.config=w.config;this.animation=new u;this.nodes=null},requestNodes:function(B,A){var z=0,x=B.length,D={};var y=function(){A.onComplete()};var w=this.viz;if(x==0){y()}for(var C=0;C<x;C++){D[B[C].id]=B[C];A.request(B[C].id,B[C]._level,{onComplete:function(F,E){if(E&&E.children){E.id=F;w.op.sum(E,{type:"nothing"})}if(++z==x){w.graph.computeLevels(w.root,0);y()}}})}},contract:function(y,x){var w=this.viz;var z=this;y=this.prepare(y);this.animation.setOptions(c.merge(x,{$animating:false,compute:function(A){if(A==1){A=0.99}z.plotStep(1-A,x,this.$animating);this.$animating="contract"},complete:function(){z.hide(y,x)}})).start()},hide:function(y,x){var w=this.viz;for(var z=0;z<y.length;z++){if(true||!x||!x.request){y[z].eachLevel(1,false,function(B){if(B.exist){c.extend(B,{drawn:false,exist:false})}})}else{var A=[];y[z].eachLevel(1,false,function(B){A.push(B.id)});w.op.removeNode(A,{type:"nothing"});w.labels.clearLabels()}}x.onComplete()},expand:function(x,w){var y=this;this.show(x);this.animation.setOptions(c.merge(w,{$animating:false,compute:function(z){y.plotStep(z,w,this.$animating);this.$animating="expand"},complete:function(){y.plotStep(undefined,w,false);w.onComplete()}})).start()},show:function(w){var x=this.config;this.prepare(w);c.each(w,function(z){if(x.multitree&&!("$orn" in z.data)){delete z.data.$orns;var y=" ";z.eachSubnode(function(A){if(("$orn" in A.data)&&y.indexOf(A.data.$orn)<0&&A.exist&&!A.drawn){y+=A.data.$orn+" "}});z.data.$orns=y}z.eachLevel(0,x.levelsToShow,function(A){if(A.exist){A.drawn=true}})})},prepare:function(w){this.nodes=this.getNodesWithChildren(w);return this.nodes},getNodesWithChildren:function(y){var x=[],A=this.config,w=this.viz.root;y.sort(function(E,D){return(E._depth<=D._depth)-(E._depth>=D._depth)});for(var B=0;B<y.length;B++){if(y[B].anySubnode("exist")){for(var z=B+1,C=false;!C&&z<y.length;z++){if(!A.multitree||"$orn" in y[z].data){C=C||y[B].isDescendantOf(y[z].id)}}if(!C){x.push(y[B])}}}return x},plotStep:function(G,C,I){var F=this.viz,z=this.config,y=F.canvas,H=y.getCtx(),w=this.nodes;var B,A;var x={};for(B=0;B<w.length;B++){A=w[B];x[A.id]=[];var E=z.multitree&&!("$orn" in A.data);var D=E&&A.data.$orns;A.eachSubgraph(function(J){if(E&&D&&D.indexOf(J.data.$orn)>0&&J.drawn){J.drawn=false;x[A.id].push(J)}else{if((!E||!D)&&J.drawn){J.drawn=false;x[A.id].push(J)}}});A.drawn=true}if(w.length>0){F.fx.plot()}for(B in x){c.each(x[B],function(J){J.drawn=true})}for(B=0;B<w.length;B++){A=w[B];H.save();F.fx.plotSubtree(A,C,G,I);H.restore()}},getSiblings:function(w){var x={};c.each(w,function(A){var z=A.getParents();if(z.length==0){x[A.id]=[A]}else{var y=[];z[0].eachSubnode(function(B){y.push(B)});x[A.id]=y}});return x}});$jit.ST.Geom=new q({Implements:e.Geom,switchOrientation:function(w){this.config.orientation=w},dispatch:function(){var x=Array.prototype.slice.call(arguments);var y=x.shift(),w=x.length;var z=function(A){return typeof A=="function"?A():A};if(w==2){return(y=="top"||y=="bottom")?z(x[0]):z(x[1])}else{if(w==4){switch(y){case"top":return z(x[0]);case"right":return z(x[1]);case"bottom":return z(x[2]);case"left":return z(x[3])}}}return undefined},getSize:function(E,D){var C=E.data,z=this.config;var y=z.siblingOffset;var B=(z.multitree&&("$orn" in C)&&C.$orn)||z.orientation;var x=E.getData("width")+y;var A=E.getData("height")+y;if(!D){return this.dispatch(B,A,x)}else{return this.dispatch(B,x,A)}},getTreeBaseSize:function(A,B,x){var y=this.getSize(A,true),w=0,z=this;if(x(B,A)){return y}if(B===0){return 0}A.eachSubnode(function(C){w+=z.getTreeBaseSize(C,B-1,x)});return(y>w?y:w)+this.config.subtreeOffset},getEdge:function(C,B,A){var y=function(E,w){return function(){return C.pos.add(new p(E,w))}};var D=this.node;var x=C.getData("width");var z=C.getData("height");if(B=="begin"){if(D.align=="center"){return this.dispatch(A,y(0,z/2),y(-x/2,0),y(0,-z/2),y(x/2,0))}else{if(D.align=="left"){return this.dispatch(A,y(0,z),y(0,0),y(0,0),y(x,0))}else{if(D.align=="right"){return this.dispatch(A,y(0,0),y(-x,0),y(0,-z),y(0,0))}else{throw"align: not implemented"}}}}else{if(B=="end"){if(D.align=="center"){return this.dispatch(A,y(0,-z/2),y(x/2,0),y(0,z/2),y(-x/2,0))}else{if(D.align=="left"){return this.dispatch(A,y(0,0),y(x,0),y(0,z),y(0,0))}else{if(D.align=="right"){return this.dispatch(A,y(0,-z),y(0,0),y(0,0),y(-x,0))}else{throw"align: not implemented"}}}}}},getScaledTreePosition:function(B,D){var C=this.node;var x=B.getData("width");var A=B.getData("height");var z=(this.config.multitree&&("$orn" in B.data)&&B.data.$orn)||this.config.orientation;var y=function(E,w){return function(){return B.pos.add(new p(E,w)).$scale(1-D)}};if(C.align=="left"){return this.dispatch(z,y(0,A),y(0,0),y(0,0),y(x,0))}else{if(C.align=="center"){return this.dispatch(z,y(0,A/2),y(-x/2,0),y(0,-A/2),y(x/2,0))}else{if(C.align=="right"){return this.dispatch(z,y(0,0),y(-x,0),y(0,-A),y(0,0))}else{throw"align: not implemented"}}}},treeFitsInCanvas:function(B,w,C){var y=w.getSize();var z=(this.config.multitree&&("$orn" in B.data)&&B.data.$orn)||this.config.orientation;var x=this.dispatch(z,y.width,y.height);var A=this.getTreeBaseSize(B,C,function(E,D){return E===0||!D.anySubnode()});return(A<x)}});$jit.ST.Plot=new q({Implements:e.Plot,plotSubtree:function(z,w,A,E){var C=this.viz,x=C.canvas,y=C.config;A=Math.min(Math.max(0.001,A),1);if(A>=0){z.drawn=false;var D=x.getCtx();var B=C.geom.getScaledTreePosition(z,A);D.translate(B.x,B.y);D.scale(A,A)}this.plotTree(z,c.merge(w,{withLabels:true,hideLabels:!!A,plotSubtree:function(I,G){var F=y.multitree&&!("$orn" in z.data);var H=F&&z.getData("orns");return !F||H.indexOf(elem.getData("orn"))>-1}}),E);if(A>=0){z.drawn=true}},getAlignedPos:function(B,z,w){var y=this.node;var A,x;if(y.align=="center"){A={x:B.x-z/2,y:B.y-w/2}}else{if(y.align=="left"){x=this.config.orientation;if(x=="bottom"||x=="top"){A={x:B.x-z/2,y:B.y}}else{A={x:B.x,y:B.y-w/2}}}else{if(y.align=="right"){x=this.config.orientation;if(x=="bottom"||x=="top"){A={x:B.x-z/2,y:B.y-w}}else{A={x:B.x-z,y:B.y-w/2}}}else{throw"align: not implemented"}}}return A},getOrientation:function(w){var y=this.config;var x=y.orientation;if(y.multitree){var z=w.nodeFrom;var A=w.nodeTo;x=(("$orn" in z.data)&&z.data.$orn)||(("$orn" in A.data)&&A.data.$orn)}return x}});$jit.ST.Label={};$jit.ST.Label.Native=new q({Implements:e.Label.Native,renderLabel:function(y,z,x){var w=y.getCtx();var A=z.pos.getc(true);w.fillText(z.name,A.x,A.y)}});$jit.ST.Label.DOM=new q({Implements:e.Label.DOM,placeLabel:function(P,J,F){var B=J.pos.getc(true),O=this.viz.config,K=O.Node,x=this.viz.canvas,C=J.getData("width"),M=J.getData("height"),y=x.getSize(),G,N;var A=x.translateOffsetX,z=x.translateOffsetY,E=x.scaleOffsetX,D=x.scaleOffsetY,I=B.x*E+A,H=B.y*D+z;if(K.align=="center"){G={x:Math.round(I-C/2+y.width/2),y:Math.round(H-M/2+y.height/2)}}else{if(K.align=="left"){N=O.orientation;if(N=="bottom"||N=="top"){G={x:Math.round(I-C/2+y.width/2),y:Math.round(H+y.height/2)}}else{G={x:Math.round(I+y.width/2),y:Math.round(H-M/2+y.height/2)}}}else{if(K.align=="right"){N=O.orientation;if(N=="bottom"||N=="top"){G={x:Math.round(I-C/2+y.width/2),y:Math.round(H-M+y.height/2)}}else{G={x:Math.round(I-C+y.width/2),y:Math.round(H-M/2+y.height/2)}}}else{throw"align: not implemented"}}}var L=P.style;L.left=G.x+"px";L.top=G.y+"px";L.display=this.fitsInCanvas(G,x)?"":"none";F.onPlaceLabel(P,J)}});$jit.ST.Label.SVG=new q({Implements:[$jit.ST.Label.DOM,e.Label.SVG],initialize:function(w){this.viz=w}});$jit.ST.Label.HTML=new q({Implements:[$jit.ST.Label.DOM,e.Label.HTML],initialize:function(w){this.viz=w}});$jit.ST.Plot.NodeTypes=new q({none:{render:c.empty,contains:c.lambda(false)},circle:{render:function(x,w){var z=x.getData("dim"),A=this.getAlignedPos(x.pos.getc(true),z,z),y=z/2;this.nodeHelper.circle.render("fill",{x:A.x+y,y:A.y+y},y,w)},contains:function(w,A){var y=w.getData("dim"),z=this.getAlignedPos(w.pos.getc(true),y,y),x=y/2;this.nodeHelper.circle.contains({x:z.x+x,y:z.y+x},x)}},square:{render:function(x,w){var z=x.getData("dim"),y=z/2,A=this.getAlignedPos(x.pos.getc(true),z,z);this.nodeHelper.square.render("fill",{x:A.x+y,y:A.y+y},y,w)},contains:function(w,A){var y=w.getData("dim"),z=this.getAlignedPos(w.pos.getc(true),y,y),x=y/2;this.nodeHelper.square.contains({x:z.x+x,y:z.y+x},x)}},ellipse:{render:function(z,x){var y=z.getData("width"),w=z.getData("height"),A=this.getAlignedPos(z.pos.getc(true),y,w);this.nodeHelper.ellipse.render("fill",{x:A.x+y/2,y:A.y+w/2},y,w,x)},contains:function(y,A){var x=y.getData("width"),w=y.getData("height"),z=this.getAlignedPos(y.pos.getc(true),x,w);this.nodeHelper.ellipse.contains({x:z.x+x/2,y:z.y+w/2},x,w,canvas)}},rectangle:{render:function(z,x){var y=z.getData("width"),w=z.getData("height"),A=this.getAlignedPos(z.pos.getc(true),y,w);this.nodeHelper.rectangle.render("fill",{x:A.x+y/2,y:A.y+w/2},y,w,x)},contains:function(y,A){var x=y.getData("width"),w=y.getData("height"),z=this.getAlignedPos(y.pos.getc(true),x,w);this.nodeHelper.rectangle.contains({x:z.x+x/2,y:z.y+w/2},x,w,canvas)}}});$jit.ST.Plot.EdgeTypes=new q({none:c.empty,line:{render:function(x,z){var y=this.getOrientation(x),A=x.nodeFrom,B=x.nodeTo,w=A._depth<B._depth,D=this.viz.geom.getEdge(w?A:B,"begin",y),C=this.viz.geom.getEdge(w?B:A,"end",y);this.edgeHelper.line.render(D,C,z)},contains:function(x,D){var y=this.getOrientation(x),z=x.nodeFrom,A=x.nodeTo,w=z._depth<A._depth,C=this.viz.geom.getEdge(w?z:A,"begin",y),B=this.viz.geom.getEdge(w?A:z,"end",y);return this.edgeHelper.line.contains(C,B,D,this.edge.epsilon)}},arrow:{render:function(C,x){var B=this.getOrientation(C),y=C.nodeFrom,w=C.nodeTo,A=C.getData("dim"),E=this.viz.geom.getEdge(y,"begin",B),F=this.viz.geom.getEdge(w,"end",B),D=C.data.$direction,z=(D&&D.length>1&&D[0]!=y.id);this.edgeHelper.arrow.render(E,F,A,z,x)},contains:function(x,D){var y=this.getOrientation(x),z=x.nodeFrom,A=x.nodeTo,w=z._depth<A._depth,C=this.viz.geom.getEdge(w?z:A,"begin",y),B=this.viz.geom.getEdge(w?A:z,"end",y);return this.edgeHelper.arrow.contains(C,B,D,this.edge.epsilon)}},"quadratic:begin":{render:function(C,w){var B=this.getOrientation(C);var A=C.nodeFrom,D=C.nodeTo,F=A._depth<D._depth,x=this.viz.geom.getEdge(F?A:D,"begin",B),y=this.viz.geom.getEdge(F?D:A,"end",B),z=C.getData("dim"),E=w.getCtx();E.beginPath();E.moveTo(x.x,x.y);switch(B){case"left":E.quadraticCurveTo(x.x+z,x.y,y.x,y.y);break;case"right":E.quadraticCurveTo(x.x-z,x.y,y.x,y.y);break;case"top":E.quadraticCurveTo(x.x,x.y+z,y.x,y.y);break;case"bottom":E.quadraticCurveTo(x.x,x.y-z,y.x,y.y);break}E.stroke()}},"quadratic:end":{render:function(C,w){var B=this.getOrientation(C);var A=C.nodeFrom,D=C.nodeTo,F=A._depth<D._depth,x=this.viz.geom.getEdge(F?A:D,"begin",B),y=this.viz.geom.getEdge(F?D:A,"end",B),z=C.getData("dim"),E=w.getCtx();E.beginPath();E.moveTo(x.x,x.y);switch(B){case"left":E.quadraticCurveTo(y.x-z,y.y,y.x,y.y);break;case"right":E.quadraticCurveTo(y.x+z,y.y,y.x,y.y);break;case"top":E.quadraticCurveTo(y.x,y.y-z,y.x,y.y);break;case"bottom":E.quadraticCurveTo(y.x,y.y+z,y.x,y.y);break}E.stroke()}},bezier:{render:function(C,w){var B=this.getOrientation(C),A=C.nodeFrom,D=C.nodeTo,F=A._depth<D._depth,x=this.viz.geom.getEdge(F?A:D,"begin",B),y=this.viz.geom.getEdge(F?D:A,"end",B),z=C.getData("dim"),E=w.getCtx();E.beginPath();E.moveTo(x.x,x.y);switch(B){case"left":E.bezierCurveTo(x.x+z,x.y,y.x-z,y.y,y.x,y.y);break;case"right":E.bezierCurveTo(x.x-z,x.y,y.x+z,y.y,y.x,y.y);break;case"top":E.bezierCurveTo(x.x,x.y+z,y.x,y.y-z,y.x,y.y);break;case"bottom":E.bezierCurveTo(x.x,x.y-z,y.x,y.y+z,y.x,y.y);break}E.stroke()}}});$jit.ST.Plot.NodeTypes.implement({"areachart-stacked":{render:function(V,D){var T=V.pos.getc(true),w=V.getData("width"),A=V.getData("height"),G=this.getAlignedPos(T,w,A),aa=G.x,Z=G.y,L=V.getData("stringArray"),F=V.getData("dimArray"),B=V.getData("valueArray"),ac=c.reduce(B,function(ai,aj){return ai+aj[0]},0),ab=c.reduce(B,function(ai,aj){return ai+aj[1]},0),I=V.getData("colorArray"),C=I.length,X=V.getData("config"),J=V.getData("gradient"),ah=X.showLabels,N=X.showAggregates,ad=X.Label,S=V.getData("prev");var M=D.getCtx(),H=V.getData("border");if(I&&F&&L){for(var ag=0,ae=F.length,K=0,E=0,W=0;ag<ae;ag++){M.fillStyle=M.strokeStyle=I[ag%C];M.save();if(J&&(F[ag][0]>0||F[ag][1]>0)){var Q=K+F[ag][0],O=E+F[ag][1],af=Math.atan((O-Q)/w),Y=55;var U=M.createLinearGradient(aa+w/2,Z-(Q+O)/2,aa+w/2+Y*Math.sin(af),Z-(Q+O)/2+Y*Math.cos(af));var P=c.rgbToHex(c.map(c.hexToRgb(I[ag%C].slice(1)),function(x){return(x*0.85)>>0}));U.addColorStop(0,I[ag%C]);U.addColorStop(1,P);M.fillStyle=U}M.beginPath();M.moveTo(aa,Z-K);M.lineTo(aa+w,Z-E);M.lineTo(aa+w,Z-E-F[ag][1]);M.lineTo(aa,Z-K-F[ag][0]);M.lineTo(aa,Z-K);M.fill();M.restore();if(H){var R=H.name==L[ag];var z=R?0.7:0.8;var P=c.rgbToHex(c.map(c.hexToRgb(I[ag%C].slice(1)),function(x){return(x*z)>>0}));M.strokeStyle=P;M.lineWidth=R?4:1;M.save();M.beginPath();if(H.index===0){M.moveTo(aa,Z-K);M.lineTo(aa,Z-K-F[ag][0])}else{M.moveTo(aa+w,Z-E);M.lineTo(aa+w,Z-E-F[ag][1])}M.stroke();M.restore()}K+=(F[ag][0]||0);E+=(F[ag][1]||0);if(F[ag][0]>0){W+=(B[ag][0]||0)}}if(S&&ad.type=="Native"){M.save();M.beginPath();M.fillStyle=M.strokeStyle=ad.color;M.font=ad.style+" "+ad.size+"px "+ad.family;M.textAlign="center";M.textBaseline="middle";if(N(V.name,ac,ab,V)){M.fillText(W,aa,Z-K-X.labelOffset-ad.size/2,w)}if(ah(V.name,ac,ab,V)){M.fillText(V.name,aa,Z+ad.size/2+X.labelOffset)}M.restore()}}},contains:function(C,E){var J=C.pos.getc(true),z=C.getData("width"),N=C.getData("height"),M=this.getAlignedPos(J,z,N),L=M.x,K=M.y,O=C.getData("dimArray"),w=E.x-L;if(E.x<L||E.x>L+z||E.y>K||E.y<K-N){return false}for(var F=0,D=O.length,I=K,A=K;F<D;F++){var B=O[F];I-=B[0];A-=B[1];var G=I+(A-I)*w/z;if(E.y>=G){var H=+(w>z/2);return{name:C.getData("stringArray")[F],color:C.getData("colorArray")[F],value:C.getData("valueArray")[F][H],index:H}}}return false}}});$jit.AreaChart=new q({st:null,colors:["#416D9C","#70A35E","#EBB056","#C74243","#83548B","#909291","#557EAA"],selected:{},busy:false,initialize:function(y){this.controller=this.config=c.merge(n("Canvas","Margin","Label","AreaChart"),{Label:{type:"Native"}},y);var z=this.config.showLabels,x=c.type(z),A=this.config.showAggregates,w=c.type(A);this.config.showLabels=x=="function"?z:c.lambda(z);this.config.showAggregates=w=="function"?A:c.lambda(A);this.initializeViz()},initializeViz:function(){var y=this.config,B=this,w=y.type.split(":")[0],A={};var x=new $jit.ST({injectInto:y.injectInto,orientation:"bottom",levelDistance:0,siblingOffset:0,subtreeOffset:0,withLabels:y.Label.type!="Native",useCanvas:y.useCanvas,Label:{type:y.Label.type},Node:{overridable:true,type:"areachart-"+w,align:"left",width:1,height:1},Edge:{type:"none"},Tips:{enable:y.Tips.enable,type:"Native",force:true,onShow:function(G,F,D){var E=D;y.Tips.onShow(G,E,F)}},Events:{enable:true,type:"Native",onClick:function(F,G,D){if(!y.filterOnClick&&!y.Events.enable){return}var E=G.getContains();if(E){y.filterOnClick&&B.filter(E.name)}y.Events.enable&&y.Events.onClick(E,G,D)},onRightClick:function(E,F,D){if(!y.restoreOnRightClick){return}B.restore()},onMouseMove:function(F,G,D){if(!y.selectOnHover){return}if(F){var E=G.getContains();B.select(F.id,E.name,E.index)}else{B.select(false,false,false)}}},onCreateLabel:function(J,G){var P=y.Label,O=G.getData("valueArray"),H=c.reduce(O,function(Q,R){return Q+R[0]},0),M=c.reduce(O,function(Q,R){return Q+R[1]},0);if(G.getData("prev")){var L={wrapper:document.createElement("div"),aggregate:document.createElement("div"),label:document.createElement("div")};var D=L.wrapper,N=L.label,E=L.aggregate,F=D.style,K=N.style,I=E.style;A[G.id]=L;D.appendChild(N);D.appendChild(E);if(!y.showLabels(G.name,H,M,G)){N.style.display="none"}if(!y.showAggregates(G.name,H,M,G)){E.style.display="none"}F.position="relative";F.overflow="visible";F.fontSize=P.size+"px";F.fontFamily=P.family;F.color=P.color;F.textAlign="center";I.position=K.position="absolute";J.style.width=G.getData("width")+"px";J.style.height=G.getData("height")+"px";N.innerHTML=G.name;J.appendChild(D)}},onPlaceLabel:function(U,O){if(!O.getData("prev")){return}var S=A[O.id],E=S.wrapper.style,D=S.label.style,N=S.aggregate.style,L=O.getData("width"),J=O.getData("height"),I=O.getData("dimArray"),F=O.getData("valueArray"),K=c.reduce(F,function(V,W){return V+W[0]},0),G=c.reduce(F,function(V,W){return V+W[1]},0),H=parseInt(E.fontSize,10),M=U.style;if(I&&F){if(y.showLabels(O.name,K,G,O)){D.display=""}else{D.display="none"}if(y.showAggregates(O.name,K,G,O)){N.display=""}else{N.display="none"}E.width=N.width=D.width=U.style.width=L+"px";N.left=D.left=-L/2+"px";for(var R=0,P=F.length,Q=0,T=0;R<P;R++){if(I[R][0]>0){Q+=F[R][0];T+=I[R][0]}}N.top=(-H-y.labelOffset)+"px";D.top=(y.labelOffset+T)+"px";U.style.top=parseInt(U.style.top,10)-T+"px";U.style.height=E.height=T+"px";S.aggregate.innerHTML=Q}}});var z=x.canvas.getSize(),C=y.Margin;x.config.offsetY=-z.height/2+C.bottom+(y.showLabels&&(y.labelOffset+y.Label.size));x.config.offsetX=(C.right-C.left)/2;this.st=x;this.canvas=this.st.canvas},loadJSON:function(N){var K=c.time(),B=[],G=this.st,Q=c.splat(N.label),J=c.splat(N.color||this.colors),O=this.config,x=!!O.type.split(":")[1],z=O.animate;for(var L=0,y=N.values,I=y.length;L<I-1;L++){var P=y[L],E=y[L-1],F=y[L+1];var M=c.splat(y[L].values),w=c.splat(y[L+1].values);var A=c.zip(M,w);var D=0,C=0;B.push({id:K+P.label,name:P.label,data:{value:A,"$valueArray":A,"$colorArray":J,"$stringArray":Q,"$next":F.label,"$prev":E?E.label:false,"$config":O,"$gradient":x},children:[]})}var H={id:K+"$root",name:"",data:{"$type":"none","$width":1,"$height":1},children:B};G.loadJSON(H);this.normalizeDims();G.compute();G.select(G.root);if(z){G.fx.animate({modes:["node-property:height:dimArray"],duration:1500})}},updateJSON:function(z,C){if(this.busy){return}this.busy=true;var y=this.st,B=y.graph,D=z.label&&c.splat(z.label),x=z.values,w=this.config.animate,A=this;c.each(x,function(F){var L=B.getByName(F.label);if(L){F.values=c.splat(F.values);var G=L.getData("stringArray"),K=L.getData("valueArray");c.each(K,function(M,N){M[0]=F.values[N];if(D){G[N]=D[N]}});L.setData("valueArray",K);var I=L.getData("prev"),H=L.getData("next"),E=B.getByName(H);if(I){var J=B.getByName(I);if(J){var K=J.getData("valueArray");c.each(K,function(M,N){M[1]=F.values[N]})}}if(!E){var K=L.getData("valueArray");c.each(K,function(M,N){M[1]=F.values[N]})}}});this.normalizeDims();y.compute();y.select(y.root);if(w){y.fx.animate({modes:["node-property:height:dimArray"],duration:1500,onComplete:function(){A.busy=false;C&&C.onComplete()}})}},filter:function(){if(this.busy){return}this.busy=true;if(this.config.Tips.enable){this.st.tips.hide()}this.select(false,false,false);var x=Array.prototype.slice.call(arguments);var w=this.st.graph.getNode(this.st.root);var y=this;w.eachAdjacency(function(z){var C=z.nodeTo,B=C.getData("dimArray"),A=C.getData("stringArray");C.setData("dimArray",c.map(B,function(E,D){return(c.indexOf(x,A[D])>-1)?E:[0,0]}),"end")});this.st.fx.animate({modes:["node-property:dimArray"],duration:1500,onComplete:function(){y.busy=false}})},restore:function(){if(this.busy){return}this.busy=true;if(this.config.Tips.enable){this.st.tips.hide()}this.select(false,false,false);this.normalizeDims();var w=this;this.st.fx.animate({modes:["node-property:height:dimArray"],duration:1500,onComplete:function(){w.busy=false}})},select:function(B,x,w){if(!this.config.selectOnHover){return}var y=this.selected;if(y.id!=B||y.name!=x||y.index!=w){y.id=B;y.name=x;y.index=w;this.st.graph.eachNode(function(C){C.setData("border",false)});if(B){var A=this.st.graph.getNode(B);A.setData("border",y);var z=w===0?"prev":"next";z=A.getData(z);if(z){A=this.st.graph.getByName(z);if(A){A.setData("border",{name:x,index:1-w})}}}this.st.plot()}},getLegend:function(){var y={};var z;this.st.graph.getNode(this.st.root).eachAdjacency(function(A){z=A.nodeTo});var x=z.getData("colorArray"),w=x.length;c.each(z.getData("stringArray"),function(B,A){y[B]=x[A%w]});return y},getMaxValue:function(){var w=0;this.st.graph.eachNode(function(B){var y=B.getData("valueArray"),x=0,A=0;c.each(y,function(C){x+=+C[0];A+=+C[1]});var z=A>x?A:x;w=w>z?w:z});return w},normalizeDims:function(){var C=this.st.graph.getNode(this.st.root),z=0;C.eachAdjacency(function(){z++});var B=this.getMaxValue()||1,F=this.st.canvas.getSize(),y=this.config,A=y.Margin,D=y.labelOffset+y.Label.size,w=(F.width-(A.left+A.right))/z,x=y.animate,E=F.height-(A.top+A.bottom)-(y.showAggregates&&D)-(y.showLabels&&D);this.st.graph.eachNode(function(L){var I=0,K=0,G=[];c.each(L.getData("valueArray"),function(M){I+=+M[0];K+=+M[1];G.push([0,0])});var J=K>I?K:I;L.setData("width",w);if(x){L.setData("height",J*E/B,"end");L.setData("dimArray",c.map(L.getData("valueArray"),function(M){return[M[0]*E/B,M[1]*E/B]}),"end");var H=L.getData("dimArray");if(!H){L.setData("dimArray",G)}}else{L.setData("height",J*E/B);L.setData("dimArray",c.map(L.getData("valueArray"),function(M){return[M[0]*E/B,M[1]*E/B]}))}})}});n.BarChart={$extend:true,animate:true,type:"stacked",labelOffset:3,barsOffset:0,hoveredColor:"#9fd4ff",orientation:"horizontal",showAggregates:true,showLabels:true,Tips:{enable:false,onShow:c.empty,onHide:c.empty},Events:{enable:false,onClick:c.empty}};$jit.ST.Plot.NodeTypes.implement({"barchart-stacked":{render:function(Q,C){var H=Q.pos.getc(true),P=Q.getData("width"),N=Q.getData("height"),L=this.getAlignedPos(H,P,N),K=L.x,J=L.y,M=Q.getData("dimArray"),F=Q.getData("valueArray"),E=Q.getData("colorArray"),B=E.length,X=Q.getData("stringArray");var S=C.getCtx(),w={},T=Q.getData("border"),z=Q.getData("gradient"),Z=Q.getData("config"),A=Z.orientation=="horizontal",D=Z.showAggregates,O=Z.showLabels,I=Z.Label;if(E&&M&&X){for(var W=0,R=M.length,V=0,G=0;W<R;W++){S.fillStyle=S.strokeStyle=E[W%B];if(z){var Y;if(A){Y=S.createLinearGradient(K+V+M[W]/2,J,K+V+M[W]/2,J+N)}else{Y=S.createLinearGradient(K,J-V-M[W]/2,K+P,J-V-M[W]/2)}var U=c.rgbToHex(c.map(c.hexToRgb(E[W%B].slice(1)),function(x){return(x*0.5)>>0}));Y.addColorStop(0,U);Y.addColorStop(0.5,E[W%B]);Y.addColorStop(1,U);S.fillStyle=Y}if(A){S.fillRect(K+V,J,M[W],N)}else{S.fillRect(K,J-V-M[W],P,M[W])}if(T&&T.name==X[W]){w.acum=V;w.dimValue=M[W]}V+=(M[W]||0);G+=(F[W]||0)}if(T){S.save();S.lineWidth=2;S.strokeStyle=T.color;if(A){S.strokeRect(K+w.acum+1,J+1,w.dimValue-2,N-2)}else{S.strokeRect(K+1,J-w.acum-w.dimValue+1,P-2,w.dimValue-2)}S.restore()}if(I.type=="Native"){S.save();S.fillStyle=S.strokeStyle=I.color;S.font=I.style+" "+I.size+"px "+I.family;S.textBaseline="middle";if(D(Q.name,G)){if(A){S.textAlign="right";S.fillText(G,K+V-Z.labelOffset,J+N/2)}else{S.textAlign="center";S.fillText(G,K+P/2,J-N-I.size/2-Z.labelOffset)}}if(O(Q.name,G,Q)){if(A){S.textAlign="center";S.translate(K-Z.labelOffset-I.size/2,J+N/2);S.rotate(Math.PI/2);S.fillText(Q.name,0,0)}else{S.textAlign="center";S.fillText(Q.name,K+P/2,J+I.size/2+Z.labelOffset)}}S.restore()}}},contains:function(D,F){var I=D.pos.getc(true),A=D.getData("width"),N=D.getData("height"),M=this.getAlignedPos(I,A,N),L=M.x,J=M.y,O=D.getData("dimArray"),B=D.getData("config"),z=F.x-L,w=B.orientation=="horizontal";if(w){if(F.x<L||F.x>L+A||F.y>J+N||F.y<J){return false}}else{if(F.x<L||F.x>L+A||F.y>J||F.y<J-N){return false}}for(var G=0,E=O.length,K=(w?L:J);G<E;G++){var C=O[G];if(w){K+=C;var H=K;if(F.x<=H){return{name:D.getData("stringArray")[G],color:D.getData("colorArray")[G],value:D.getData("valueArray")[G],label:D.name}}}else{K-=C;var H=K;if(F.y>=H){return{name:D.getData("stringArray")[G],color:D.getData("colorArray")[G],value:D.getData("valueArray")[G],label:D.name}}}}return false}},"barchart-grouped":{render:function(R,C){var I=R.pos.getc(true),Q=R.getData("width"),O=R.getData("height"),M=this.getAlignedPos(I,Q,O),L=M.x,K=M.y,N=R.getData("dimArray"),G=R.getData("valueArray"),X=G.length,F=R.getData("colorArray"),B=F.length,Z=R.getData("stringArray");var T=C.getCtx(),w={},U=R.getData("border"),z=R.getData("gradient"),ab=R.getData("config"),A=ab.orientation=="horizontal",E=ab.showAggregates,P=ab.showLabels,J=ab.Label,D=(A?O:Q)/X;if(F&&N&&Z){for(var Y=0,S=X,W=0,H=0;Y<S;Y++){T.fillStyle=T.strokeStyle=F[Y%B];if(z){var aa;if(A){aa=T.createLinearGradient(L+N[Y]/2,K+D*Y,L+N[Y]/2,K+D*(Y+1))}else{aa=T.createLinearGradient(L+D*Y,K-N[Y]/2,L+D*(Y+1),K-N[Y]/2)}var V=c.rgbToHex(c.map(c.hexToRgb(F[Y%B].slice(1)),function(x){return(x*0.5)>>0}));aa.addColorStop(0,V);aa.addColorStop(0.5,F[Y%B]);aa.addColorStop(1,V);T.fillStyle=aa}if(A){T.fillRect(L,K+D*Y,N[Y],D)}else{T.fillRect(L+D*Y,K-N[Y],D,N[Y])}if(U&&U.name==Z[Y]){w.acum=D*Y;w.dimValue=N[Y]}W+=(N[Y]||0);H+=(G[Y]||0)}if(U){T.save();T.lineWidth=2;T.strokeStyle=U.color;if(A){T.strokeRect(L+1,K+w.acum+1,w.dimValue-2,D-2)}else{T.strokeRect(L+w.acum+1,K-w.dimValue+1,D-2,w.dimValue-2)}T.restore()}if(J.type=="Native"){T.save();T.fillStyle=T.strokeStyle=J.color;T.font=J.style+" "+J.size+"px "+J.family;T.textBaseline="middle";if(E(R.name,H)){if(A){T.textAlign="right";T.fillText(H,L+Math.max.apply(null,N)-ab.labelOffset,K+O/2)}else{T.textAlign="center";T.fillText(H,L+Q/2,K-Math.max.apply(null,N)-J.size/2-ab.labelOffset)}}if(P(R.name,H,R)){if(A){T.textAlign="center";T.translate(L-ab.labelOffset-J.size/2,K+O/2);T.rotate(Math.PI/2);T.fillText(R.name,0,0)}else{T.textAlign="center";T.fillText(R.name,L+Q/2,K+J.size/2+ab.labelOffset)}}T.restore()}}},contains:function(J,F){var B=J.pos.getc(true),I=J.getData("width"),H=J.getData("height"),E=this.getAlignedPos(B,I,H),D=E.x,C=E.y,G=J.getData("dimArray"),M=G.length,P=J.getData("config"),A=F.x-D,w=P.orientation=="horizontal",z=(w?H:I)/M;if(w){if(F.x<D||F.x>D+I||F.y>C+H||F.y<C){return false}}else{if(F.x<D||F.x>D+I||F.y>C||F.y<C-H){return false}}for(var L=0,K=G.length;L<K;L++){var O=G[L];if(w){var N=C+z*L;if(F.x<=D+O&&F.y>=N&&F.y<=N+z){return{name:J.getData("stringArray")[L],color:J.getData("colorArray")[L],value:J.getData("valueArray")[L],label:J.name}}}else{var N=D+z*L;if(F.x>=N&&F.x<=N+z&&F.y>=C-O){return{name:J.getData("stringArray")[L],color:J.getData("colorArray")[L],value:J.getData("valueArray")[L],label:J.name}}}}return false}}});$jit.BarChart=new q({st:null,colors:["#416D9C","#70A35E","#EBB056","#C74243","#83548B","#909291","#557EAA"],selected:{},busy:false,initialize:function(y){this.controller=this.config=c.merge(n("Canvas","Margin","Label","BarChart"),{Label:{type:"Native"}},y);var z=this.config.showLabels,x=c.type(z),A=this.config.showAggregates,w=c.type(A);this.config.showLabels=x=="function"?z:c.lambda(z);this.config.showAggregates=w=="function"?A:c.lambda(A);this.initializeViz()},initializeViz:function(){var y=this.config,B=this;var w=y.type.split(":")[0],D=y.orientation=="horizontal",A={};var x=new $jit.ST({injectInto:y.injectInto,orientation:D?"left":"bottom",levelDistance:0,siblingOffset:y.barsOffset,subtreeOffset:0,withLabels:y.Label.type!="Native",useCanvas:y.useCanvas,Label:{type:y.Label.type},Node:{overridable:true,type:"barchart-"+w,align:"left",width:1,height:1},Edge:{type:"none"},Tips:{enable:y.Tips.enable,type:"Native",force:true,onShow:function(H,G,E){var F=E;y.Tips.onShow(H,F,G)}},Events:{enable:true,type:"Native",onClick:function(G,H,E){if(!y.Events.enable){return}var F=H.getContains();y.Events.onClick(F,H,E)},onMouseMove:function(G,H,E){if(!y.hoveredColor){return}if(G){var F=H.getContains();B.select(G.id,F.name,F.index)}else{B.select(false,false,false)}}},onCreateLabel:function(J,H){var P=y.Label,N=H.getData("valueArray"),M=c.reduce(N,function(Q,R){return Q+R},0);var L={wrapper:document.createElement("div"),aggregate:document.createElement("div"),label:document.createElement("div")};var E=L.wrapper,O=L.label,F=L.aggregate,G=E.style,K=O.style,I=F.style;A[H.id]=L;E.appendChild(O);E.appendChild(F);if(!y.showLabels(H.name,M,H)){K.display="none"}if(!y.showAggregates(H.name,M,H)){I.display="none"}G.position="relative";G.overflow="visible";G.fontSize=P.size+"px";G.fontFamily=P.family;G.color=P.color;G.textAlign="center";I.position=K.position="absolute";J.style.width=H.getData("width")+"px";J.style.height=H.getData("height")+"px";I.left=K.left="0px";O.innerHTML=H.name;J.appendChild(E)},onPlaceLabel:function(L,H){if(!A[H.id]){return}var N=A[H.id],I=N.wrapper.style,P=N.label.style,M=N.aggregate.style,Q=y.type.split(":")[0]=="grouped",E=y.orientation=="horizontal",T=H.getData("dimArray"),U=H.getData("valueArray"),F=(Q&&E)?Math.max.apply(null,T):H.getData("width"),S=(Q&&!E)?Math.max.apply(null,T):H.getData("height"),G=parseInt(I.fontSize,10),O=L.style;if(T&&U){I.width=M.width=P.width=L.style.width=F+"px";for(var K=0,J=U.length,R=0;K<J;K++){if(T[K]>0){R+=U[K]}}if(y.showLabels(H.name,R,H)){P.display=""}else{P.display="none"}if(y.showAggregates(H.name,R,H)){M.display=""}else{M.display="none"}if(y.orientation=="horizontal"){M.textAlign="right";P.textAlign="left";P.textIndex=M.textIndent=y.labelOffset+"px";M.top=P.top=(S-G)/2+"px";L.style.height=I.height=S+"px"}else{M.top=(-G-y.labelOffset)+"px";P.top=(y.labelOffset+S)+"px";L.style.top=parseInt(L.style.top,10)-S+"px";L.style.height=I.height=S+"px"}N.aggregate.innerHTML=R}}});var z=x.canvas.getSize(),C=y.Margin;if(D){x.config.offsetX=z.width/2-C.left-(y.showLabels&&(y.labelOffset+y.Label.size));x.config.offsetY=(C.bottom-C.top)/2}else{x.config.offsetY=-z.height/2+C.bottom+(y.showLabels&&(y.labelOffset+y.Label.size));x.config.offsetX=(C.right-C.left)/2}this.st=x;this.canvas=this.st.canvas},loadJSON:function(K){if(this.busy){return}this.busy=true;var I=c.time(),C=[],D=this.st,N=c.splat(K.label),H=c.splat(K.color||this.colors),L=this.config,w=!!L.type.split(":")[1],z=L.animate,y=L.orientation=="horizontal",A=this;for(var J=0,x=K.values,F=x.length;J<F;J++){var M=x[J];var B=c.splat(x[J].values);var G=0;C.push({id:I+M.label,name:M.label,data:{value:B,"$valueArray":B,"$colorArray":H,"$stringArray":N,"$gradient":w,"$config":L},children:[]})}var E={id:I+"$root",name:"",data:{"$type":"none","$width":1,"$height":1},children:C};D.loadJSON(E);this.normalizeDims();D.compute();D.select(D.root);if(z){if(y){D.fx.animate({modes:["node-property:width:dimArray"],duration:1500,onComplete:function(){A.busy=false}})}else{D.fx.animate({modes:["node-property:height:dimArray"],duration:1500,onComplete:function(){A.busy=false}})}}else{this.busy=false}},updateJSON:function(z,C){if(this.busy){return}this.busy=true;var y=this.st;var B=y.graph;var x=z.values;var w=this.config.animate;var A=this;var D=this.config.orientation=="horizontal";c.each(x,function(E){var F=B.getByName(E.label);if(F){F.setData("valueArray",c.splat(E.values));if(z.label){F.setData("stringArray",c.splat(z.label))}}});this.normalizeDims();y.compute();y.select(y.root);if(w){if(D){y.fx.animate({modes:["node-property:width:dimArray"],duration:1500,onComplete:function(){A.busy=false;C&&C.onComplete()}})}else{y.fx.animate({modes:["node-property:height:dimArray"],duration:1500,onComplete:function(){A.busy=false;C&&C.onComplete()}})}}},select:function(y,w){if(!this.config.hoveredColor){return}var x=this.selected;if(x.id!=y||x.name!=w){x.id=y;x.name=w;x.color=this.config.hoveredColor;this.st.graph.eachNode(function(z){if(y==z.id){z.setData("border",x)}else{z.setData("border",false)}});this.st.plot()}},getLegend:function(){var y={};var z;this.st.graph.getNode(this.st.root).eachAdjacency(function(A){z=A.nodeTo});var x=z.getData("colorArray"),w=x.length;c.each(z.getData("stringArray"),function(B,A){y[B]=x[A%w]});return y},getMaxValue:function(){var x=0,w=this.config.type.split(":")[0]=="stacked";this.st.graph.eachNode(function(A){var y=A.getData("valueArray"),z=0;if(!y){return}if(w){c.each(y,function(B){z+=+B})}else{z=Math.max.apply(null,y)}x=x>z?x:z});return x},setBarType:function(w){this.config.type=w;this.st.config.Node.type="barchart-"+w.split(":")[0]},normalizeDims:function(){var G=this.st.graph.getNode(this.st.root),B=0;G.eachAdjacency(function(){B++});var D=this.getMaxValue()||1,J=this.st.canvas.getSize(),z=this.config,C=z.Margin,H=C.left+C.right,A=C.top+C.bottom,x=z.orientation=="horizontal",w=(J[x?"height":"width"]-(x?A:H)-(B-1)*z.barsOffset)/B,y=z.animate,I=J[x?"width":"height"]-(x?H:A)-(!x&&z.showAggregates&&(z.Label.size+z.labelOffset))-(z.showLabels&&(z.Label.size+z.labelOffset)),F=x?"height":"width",E=x?"width":"height";this.st.graph.eachNode(function(N){var M=0,K=[];c.each(N.getData("valueArray"),function(O){M+=+O;K.push(0)});N.setData(F,w);if(y){N.setData(E,M*I/D,"end");N.setData("dimArray",c.map(N.getData("valueArray"),function(O){return O*I/D}),"end");var L=N.getData("dimArray");if(!L){N.setData("dimArray",K)}}else{N.setData(E,M*I/D);N.setData("dimArray",c.map(N.getData("valueArray"),function(O){return O*I/D}))}})}});n.PieChart={$extend:true,animate:true,offset:25,sliceOffset:0,labelOffset:3,type:"stacked",hoveredColor:"#9fd4ff",Events:{enable:false,onClick:c.empty},Tips:{enable:false,onShow:c.empty,onHide:c.empty},showLabels:true,resizeLabels:false,updateHeights:false};g.Radial=new q({compute:function(x){var y=c.splat(x||["current","start","end"]);f.compute(this.graph,y,this.config);this.graph.computeLevels(this.root,0,"ignore");var w=this.createLevelDistanceFunc();this.computeAngularWidths(y);this.computePositions(y,w)},computePositions:function(D,A){var F=D;var E=this.graph;var B=E.getNode(this.root);var C=this.parent;var w=this.config;for(var y=0,x=F.length;y<x;y++){var z=F[y];B.setPos(k(0,0),z);B.setData("span",Math.PI*2,z)}B.angleSpan={begin:0,end:2*Math.PI};E.eachBFS(this.root,function(K){var Q=K.angleSpan.end-K.angleSpan.begin;var S=K.angleSpan.begin;var R=A(K);var T=0,G=[],J={};K.eachSubnode(function(W){T+=W._treeAngularWidth;for(var X=0,V=F.length;X<V;X++){var Z=F[X],Y=W.getData("dim",Z);J[Z]=(Z in J)?(Y>J[Z]?Y:J[Z]):Y}G.push(W)},"ignore");if(C&&C.id==K.id&&G.length>0&&G[0].dist){G.sort(function(W,V){return(W.dist>=V.dist)-(W.dist<=V.dist)})}for(var M=0,O=G.length;M<O;M++){var I=G[M];if(!I._flag){var U=I._treeAngularWidth/T*Q;var H=S+U/2;for(var N=0,L=F.length;N<L;N++){var P=F[N];I.setPos(k(H,R),P);I.setData("span",U,P);I.setData("dim-quotient",I.getData("dim",P)/J[P],P)}I.angleSpan={begin:S,end:S+U};S+=U}}},"ignore")},setAngularWidthForNodes:function(w){this.graph.eachBFS(this.root,function(z,x){var y=z.getData("angularWidth",w[0])||5;z._angularWidth=y/x},"ignore")},setSubtreesAngularWidth:function(){var w=this;this.graph.eachNode(function(x){w.setSubtreeAngularWidth(x)},"ignore")},setSubtreeAngularWidth:function(z){var y=this,x=z._angularWidth,w=0;z.eachSubnode(function(A){y.setSubtreeAngularWidth(A);w+=A._treeAngularWidth},"ignore");z._treeAngularWidth=Math.max(x,w)},computeAngularWidths:function(w){this.setAngularWidthForNodes(w);this.setSubtreesAngularWidth()}});$jit.Sunburst=new q({Implements:[d,o,g.Radial],initialize:function(w){var y=$jit.Sunburst;var x={interpolation:"linear",levelDistance:100,Node:{type:"multipie",height:0},Edge:{type:"none"},Label:{textAlign:"start",textBaseline:"middle"}};this.controller=this.config=c.merge(n("Canvas","Node","Edge","Fx","Tips","NodeStyles","Events","Navigation","Controller","Label"),x,w);var z=this.config;if(z.useCanvas){this.canvas=z.useCanvas;this.config.labelContainer=this.canvas.id+"-label"}else{if(z.background){z.background=c.merge({type:"Circles"},z.background)}this.canvas=new l(this,z);this.config.labelContainer=(typeof z.injectInto=="string"?z.injectInto:z.injectInto.id)+"-label"}this.graphOptions={complex:false,Node:{selected:false,exist:true,drawn:true}};this.graph=new e(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new y.Label[z.Label.type](this);this.fx=new y.Plot(this,y);this.op=new y.Op(this);this.json=null;this.root=null;this.rotated=null;this.busy=false;this.initializeExtras()},createLevelDistanceFunc:function(){var w=this.config.levelDistance;return function(x){return(x._depth+1)*w}},refresh:function(){this.compute();this.plot()},reposition:function(){this.compute("end")},rotate:function(y,z,x){var w=y.getPos(x.property||"current").getp(true).theta;this.rotated=y;this.rotateAngle(-w,z,x)},rotateAngle:function(y,B,x){var z=this;var w=c.merge(this.config,x||{},{modes:["polar"]});var A=x.property||(B==="animate"?"end":"current");if(B==="animate"){this.fx.animation.pause()}this.graph.eachNode(function(D){var C=D.getPos(A);C.theta+=y;if(C.theta<0){C.theta+=Math.PI*2}});if(B=="animate"){this.fx.animate(w)}else{if(B=="replot"){this.fx.plot();this.busy=false}}},plot:function(){this.fx.plot()}});$jit.Sunburst.$extend=true;(function(w){w.Op=new q({Implements:e.Op});w.Plot=new q({Implements:e.Plot});w.Label={};w.Label.Native=new q({Implements:e.Label.Native,initialize:function(x){this.viz=x;this.label=x.config.Label;this.config=x.config},renderLabel:function(C,E,G){var N=E.getData("span");if(N<Math.PI/2&&Math.tan(N)*this.config.levelDistance*E._depth<10){return}var O=C.getCtx();var A=O.measureText(E.name);if(E.id==this.viz.root){var M=-A.width/2,K=0,L=0;var z=0}else{var D=5;var z=G.levelDistance-D;var J=E.pos.clone();J.rho+=D;var B=J.getp(true);var H=J.getc(true);var M=H.x,K=H.y;var F=Math.PI;var I=(B.theta>F/2&&B.theta<3*F/2);var L=I?B.theta+F:B.theta;if(I){M-=Math.abs(Math.cos(B.theta)*A.width);K+=Math.sin(B.theta)*A.width}else{if(E.id==this.viz.root){M-=A.width/2}}}O.save();O.translate(M,K);O.rotate(L);O.fillText(E.name,0,0);O.restore()}});w.Label.SVG=new q({Implements:e.Label.SVG,initialize:function(x){this.viz=x},placeLabel:function(N,C,E){var J=C.pos.getc(true),M=this.viz,A=this.viz.canvas;var F=A.getSize();var B={x:Math.round(J.x+F.width/2),y:Math.round(J.y+F.height/2)};N.setAttribute("x",B.x);N.setAttribute("y",B.y);var G=N.getBBox();if(G){var L=N.getAttribute("x");var I=N.getAttribute("y");var z=C.pos.getp(true);var D=Math.PI;var H=(z.theta>D/2&&z.theta<3*D/2);if(H){N.setAttribute("x",L-G.width);N.setAttribute("y",I-G.height)}else{if(C.id==M.root){N.setAttribute("x",L-G.width/2)}}var K=H?z.theta+D:z.theta;if(C._depth){N.setAttribute("transform","rotate("+K*360/(2*D)+" "+L+" "+I+")")}}E.onPlaceLabel(N,C)}});w.Label.HTML=new q({Implements:e.Label.HTML,initialize:function(x){this.viz=x},placeLabel:function(G,A,C){var E=A.pos.clone(),y=this.viz.canvas,F=A.getData("height"),B=((F||A._depth==0)?F:this.viz.config.levelDistance)/2,D=y.getSize();E.rho+=B;E=E.getc(true);var z={x:Math.round(E.x+D.width/2),y:Math.round(E.y+D.height/2)};var x=G.style;x.left=z.x+"px";x.top=z.y+"px";x.display=this.fitsInCanvas(z,y)?"":"none";C.onPlaceLabel(G,A)}});w.Plot.NodeTypes=new q({none:{render:c.empty,contains:c.lambda(false),anglecontains:function(B,D){var A=B.getData("span")/2,y=B.pos.theta;var z=y-A,x=y+A;if(z<0){z+=Math.PI*2}var C=Math.atan2(D.y,D.x);if(C<0){C+=Math.PI*2}if(z>x){return(C>z&&C<=Math.PI*2)||C<x}else{return C>z&&C<x}}},pie:{render:function(C,A){var G=C.getData("span")/2,z=C.pos.theta;var B=z-G,D=z+G;var F=C.pos.getp(true);var x=new b(F.rho,B);var y=x.getc(true);x.theta=D;var E=x.getc(true);var H=A.getCtx();H.beginPath();H.moveTo(0,0);H.lineTo(y.x,y.y);H.moveTo(0,0);H.lineTo(E.x,E.y);H.moveTo(0,0);H.arc(0,0,F.rho*C.getData("dim-quotient"),B,D,false);H.fill()},contains:function(z,B){if(this.nodeTypes.none.anglecontains.call(this,z,B)){var x=Math.sqrt(B.x*B.x+B.y*B.y);var y=this.config.levelDistance,A=z._depth;return(x<=y*A)}return false}},multipie:{render:function(D,B){var K=D.getData("height");var E=K?K:this.config.levelDistance;var J=D.getData("span")/2,A=D.pos.theta;var C=A-J,G=A+J;var I=D.pos.getp(true);var y=new b(I.rho,C);var z=y.getc(true);y.theta=G;var H=y.getc(true);y.rho+=E;var x=y.getc(true);y.theta=C;var F=y.getc(true);var L=B.getCtx();L.moveTo(0,0);L.beginPath();L.arc(0,0,I.rho,C,G,false);L.arc(0,0,I.rho+E,G,C,true);L.moveTo(z.x,z.y);L.lineTo(F.x,F.y);L.moveTo(H.x,H.y);L.lineTo(x.x,x.y);L.fill();if(D.collapsed){L.save();L.lineWidth=2;L.moveTo(0,0);L.beginPath();L.arc(0,0,I.rho+E+5,G-0.01,C+0.01,true);L.stroke();L.restore()}},contains:function(A,D){if(this.nodeTypes.none.anglecontains.call(this,A,D)){var y=Math.sqrt(D.x*D.x+D.y*D.y);var x=A.getData("height");var B=x?x:this.config.levelDistance;var z=this.config.levelDistance,C=A._depth;return(y>=z*C)&&(y<=(z*C+B))}return false}},"gradient-multipie":{render:function(A,x){var F=x.getCtx();var E=A.getData("height");var B=E?E:this.config.levelDistance;var y=F.createRadialGradient(0,0,A.getPos().rho,0,0,A.getPos().rho+B);var D=c.hexToRgb(A.getData("color")),C=[];c.each(D,function(G){C.push(parseInt(G*0.5,10))});var z=c.rgbToHex(C);y.addColorStop(0,z);y.addColorStop(1,A.getData("color"));F.fillStyle=y;this.nodeTypes.multipie.render.call(this,A,x)},contains:function(x,y){return this.nodeTypes.multipie.contains.call(this,x,y)}},"gradient-pie":{render:function(C,z){var x=z.getCtx();var D=x.createRadialGradient(0,0,0,0,0,C.getPos().rho);var B=c.hexToRgb(C.getData("color")),y=[];c.each(B,function(E){y.push(parseInt(E*0.5,10))});var A=c.rgbToHex(y);D.addColorStop(1,A);D.addColorStop(0,C.getData("color"));x.fillStyle=D;this.nodeTypes.pie.render.call(this,C,z)},contains:function(x,y){return this.nodeTypes.pie.contains.call(this,x,y)}}});w.Plot.EdgeTypes=new q({none:c.empty,line:{render:function(x,y){var A=x.nodeFrom.pos.getc(true),z=x.nodeTo.pos.getc(true);this.edgeHelper.line.render(A,z,y)},contains:function(x,A){var z=x.nodeFrom.pos.getc(true),y=x.nodeTo.pos.getc(true);return this.edgeHelper.line.contains(z,y,A,this.edge.epsilon)}},arrow:{render:function(y,z){var D=y.nodeFrom.pos.getc(true),C=y.nodeTo.pos.getc(true),B=y.getData("dim"),A=y.data.$direction,x=(A&&A.length>1&&A[0]!=y.nodeFrom.id);this.edgeHelper.arrow.render(D,C,B,x,z)},contains:function(x,A){var z=x.nodeFrom.pos.getc(true),y=x.nodeTo.pos.getc(true);return this.edgeHelper.arrow.contains(z,y,A,this.edge.epsilon)}},hyperline:{render:function(x,y){var B=x.nodeFrom.pos.getc(),A=x.nodeTo.pos.getc(),z=Math.max(B.norm(),A.norm());this.edgeHelper.hyperline.render(B.$scale(1/z),A.$scale(1/z),z,y)},contains:c.lambda(false)}})})($jit.Sunburst);$jit.Sunburst.Plot.NodeTypes.implement({"piechart-stacked":{render:function(U,A){var T=U.pos.getp(true),C=U.getData("dimArray"),S=U.getData("valueArray"),G=U.getData("colorArray"),z=G.length,M=U.getData("stringArray"),P=U.getData("span")/2,K=U.pos.theta,F=K-P,J=K+P,R=new b;var N=A.getCtx(),L={},I=U.getData("gradient"),D=U.getData("border"),Z=U.getData("config"),ai=Z.showLabels,Y=Z.resizeLabels,ab=Z.Label;var ae=Z.sliceOffset*Math.cos((F+J)/2);var E=Z.sliceOffset*Math.sin((F+J)/2);if(G&&C&&M){for(var af=0,ac=C.length,w=0,X=0;af<ac;af++){var B=C[af],ag=G[af%z];if(B<=0){continue}N.fillStyle=N.strokeStyle=ag;if(I&&B){var ad=N.createRadialGradient(ae,E,w+Z.sliceOffset,ae,E,w+B+Z.sliceOffset);var x=c.hexToRgb(ag),W=c.map(x,function(al){return(al*0.8)>>0}),y=c.rgbToHex(W);ad.addColorStop(0,ag);ad.addColorStop(0.5,ag);ad.addColorStop(1,y);N.fillStyle=ad}R.rho=w+Z.sliceOffset;R.theta=F;var ah=R.getc(true);R.theta=J;var O=R.getc(true);R.rho+=B;var aj=R.getc(true);R.theta=F;var Q=R.getc(true);N.beginPath();N.arc(ae,E,w+0.01,F,J,false);N.arc(ae,E,w+B+0.01,J,F,true);N.fill();if(D&&D.name==M[af]){L.acum=w;L.dimValue=C[af];L.begin=F;L.end=J}w+=(B||0);X+=(S[af]||0)}if(D){N.save();N.globalCompositeOperation="source-over";N.lineWidth=2;N.strokeStyle=D.color;var aa=F<J?1:-1;N.beginPath();N.arc(ae,E,L.acum+0.01+1,L.begin,L.end,false);N.arc(ae,E,L.acum+L.dimValue+0.01-1,L.end,L.begin,true);N.closePath();N.stroke();N.restore()}if(ai&&ab.type=="Native"){N.save();N.fillStyle=N.strokeStyle=ab.color;var V=Y?U.getData("normalizedDim"):1,H=(ab.size*V)>>0;H=H<+Y?+Y:H;N.font=ab.style+" "+H+"px "+ab.family;N.textBaseline="middle";N.textAlign="center";R.rho=w+Z.labelOffset+Z.sliceOffset;R.theta=U.pos.theta;var ak=R.getc(true);N.fillText(U.name,ak.x,ak.y);N.restore()}}},contains:function(z,D){if(this.nodeTypes.none.anglecontains.call(this,z,D)){var F=Math.sqrt(D.x*D.x+D.y*D.y);var w=this.config.levelDistance,C=z._depth;var x=z.getData("config");if(F<=w*C+x.sliceOffset){var G=z.getData("dimArray");for(var B=0,A=G.length,E=x.sliceOffset;B<A;B++){var y=G[B];if(F>=E&&F<=E+y){return{name:z.getData("stringArray")[B],color:z.getData("colorArray")[B],value:z.getData("valueArray")[B],label:z.name}}E+=y}}return false}return false}}});$jit.PieChart=new q({sb:null,colors:["#416D9C","#70A35E","#EBB056","#C74243","#83548B","#909291","#557EAA"],selected:{},busy:false,initialize:function(w){this.controller=this.config=c.merge(n("Canvas","PieChart","Label"),{Label:{type:"Native"}},w);this.initializeViz()},initializeViz:function(){var x=this.config,A=this;var w=x.type.split(":")[0];var B=new $jit.Sunburst({injectInto:x.injectInto,useCanvas:x.useCanvas,withLabels:x.Label.type!="Native",Label:{type:x.Label.type},Node:{overridable:true,type:"piechart-"+w,width:1,height:1},Edge:{type:"none"},Tips:{enable:x.Tips.enable,type:"Native",force:true,onShow:function(F,E,C){var D=C;x.Tips.onShow(F,D,E)}},Events:{enable:true,type:"Native",onClick:function(E,F,C){if(!x.Events.enable){return}var D=F.getContains();x.Events.onClick(D,F,C)},onMouseMove:function(E,F,C){if(!x.hoveredColor){return}if(E){var D=F.getContains();A.select(E.id,D.name,D.index)}else{A.select(false,false,false)}}},onCreateLabel:function(F,E){var C=x.Label;if(x.showLabels){var D=F.style;D.fontSize=C.size+"px";D.fontFamily=C.family;D.color=C.color;D.textAlign="center";F.innerHTML=E.name}},onPlaceLabel:function(S,M){if(!x.showLabels){return}var G=M.pos.getp(true),J=M.getData("dimArray"),P=M.getData("span")/2,H=M.pos.theta,R=H-P,D=H+P,U=new b;var L=x.showLabels,F=x.resizeLabels,I=x.Label;if(J){for(var Q=0,N=J.length,O=0;Q<N;Q++){O+=J[Q]}var T=F?M.getData("normalizedDim"):1,C=(I.size*T)>>0;C=C<+F?+F:C;S.style.fontSize=C+"px";U.rho=O+x.labelOffset+x.sliceOffset;U.theta=(R+D)/2;var G=U.getc(true);var E=A.canvas.getSize();var K={x:Math.round(G.x+E.width/2),y:Math.round(G.y+E.height/2)};S.style.left=K.x+"px";S.style.top=K.y+"px"}}});var z=B.canvas.getSize(),y=Math.min;B.config.levelDistance=y(z.width,z.height)/2-x.offset-x.sliceOffset;this.sb=B;this.canvas=this.sb.canvas;this.canvas.getCtx().globalCompositeOperation="lighter"},loadJSON:function(K){var I=c.time(),C=[],w=this.sb,N=c.splat(K.label),E=N.length,H=c.splat(K.color||this.colors),z=H.length,L=this.config,x=!!L.type.split(":")[1],A=L.animate,G=E==1;for(var J=0,y=K.values,F=y.length;J<F;J++){var M=y[J];var B=c.splat(M.values);C.push({id:I+M.label,name:M.label,data:{value:B,"$valueArray":B,"$colorArray":G?c.splat(H[J%z]):H,"$stringArray":N,"$gradient":x,"$config":L,"$angularWidth":c.reduce(B,function(O,P){return O+P})},children:[]})}var D={id:I+"$root",name:"",data:{"$type":"none","$width":1,"$height":1},children:C};w.loadJSON(D);this.normalizeDims();w.refresh();if(A){w.fx.animate({modes:["node-property:dimArray"],duration:1500})}},updateJSON:function(y,B){if(this.busy){return}this.busy=true;var C=this.sb;var A=C.graph;var x=y.values;var w=this.config.animate;var z=this;c.each(x,function(D){var F=A.getByName(D.label),E=c.splat(D.values);if(F){F.setData("valueArray",E);F.setData("angularWidth",c.reduce(E,function(G,H){return G+H}));if(y.label){F.setData("stringArray",c.splat(y.label))}}});this.normalizeDims();if(w){C.compute("end");C.fx.animate({modes:["node-property:dimArray:span","linear"],duration:1500,onComplete:function(){z.busy=false;B&&B.onComplete()}})}else{C.refresh()}},select:function(y,w){if(!this.config.hoveredColor){return}var x=this.selected;if(x.id!=y||x.name!=w){x.id=y;x.name=w;x.color=this.config.hoveredColor;this.sb.graph.eachNode(function(z){if(y==z.id){z.setData("border",x)}else{z.setData("border",false)}});this.sb.plot()}},getLegend:function(){var y={};var z;this.sb.graph.getNode(this.sb.root).eachAdjacency(function(A){z=A.nodeTo});var x=z.getData("colorArray"),w=x.length;c.each(z.getData("stringArray"),function(B,A){y[B]=x[A%w]});return y},getMaxValue:function(){var w=0;this.sb.graph.eachNode(function(z){var x=z.getData("valueArray"),y=0;c.each(x,function(A){y+=+A});w=w>y?w:y});return w},normalizeDims:function(){var x=this.sb.graph.getNode(this.sb.root),w=0;x.eachAdjacency(function(){w++});var B=this.getMaxValue()||1,A=this.config,y=A.animate,z=this.sb.config.levelDistance;this.sb.graph.eachNode(function(G){var F=0,C=[];c.each(G.getData("valueArray"),function(H){F+=+H;C.push(1)});var E=(C.length==1)&&!A.updateHeights;if(y){G.setData("dimArray",c.map(G.getData("valueArray"),function(H){return E?z:(H*z/B)}),"end");var D=G.getData("dimArray");if(!D){G.setData("dimArray",C)}}else{G.setData("dimArray",c.map(G.getData("valueArray"),function(H){return E?z:(H*z/B)}))}G.setData("normalizedDim",F/B)})}});g.TM={};g.TM.SliceAndDice=new q({compute:function(B){var x=this.graph.getNode(this.clickedNode&&this.clickedNode.id||this.root);this.controller.onBeforeCompute(x);var z=this.canvas.getSize(),y=this.config,A=z.width,w=z.height;this.graph.computeLevels(this.root,0,"ignore");x.getPos(B).setc(-A/2,-w/2);x.setData("width",A,B);x.setData("height",w+y.titleHeight,B);this.computePositions(x,x,this.layout.orientation,B);this.controller.onAfterCompute(x)},computePositions:function(F,D,P,y){var M=0;F.eachSubnode(function(R){M+=R.getData("area",y)});var Q=this.config,N=Q.offset,J=F.getData("width",y),H=F.getData("height",y)-Q.titleHeight,x=F==D?1:(D.getData("area",y)/M);var I,G,L,B,A,E,C;var O=(P=="h");if(O){P="v";I=H;G=J*x;L="height";B="y";A="x";E=Q.titleHeight;C=0}else{P="h";I=H*x;G=J;L="width";B="x";A="y";E=0;C=Q.titleHeight}var w=D.getPos(y);D.setData("width",G,y);D.setData("height",I,y);var K=0,z=this;D.eachSubnode(function(S){var R=S.getPos(y);R[B]=K+w[B]+E;R[A]=w[A]+C;z.computePositions(D,S,P,y);K+=S.getData(L,y)})}});g.TM.Area={compute:function(w){w=w||"current";var C=this.graph.getNode(this.clickedNode&&this.clickedNode.id||this.root);this.controller.onBeforeCompute(C);var y=this.config,F=this.canvas.getSize(),x=F.width,E=F.height,D=y.offset,z=x-D,B=E-D;this.graph.computeLevels(this.root,0,"ignore");C.getPos(w).setc(-x/2,-E/2);C.setData("width",x,w);C.setData("height",E,w);var A={top:-E/2+y.titleHeight,left:-x/2,width:z,height:B-y.titleHeight};this.computePositions(C,A,w);this.controller.onAfterCompute(C)},computeDim:function(B,C,E,A,z,x){if(B.length+C.length==1){var y=(B.length==1)?B:C;this.layoutLast(y,E,A,x);return}if(B.length>=2&&C.length==0){C=[B.shift()]}if(B.length==0){if(C.length>0){this.layoutRow(C,E,A,x)}return}var D=B[0];if(z(C,E)>=z([D].concat(C),E)){this.computeDim(B.slice(1),C.concat([D]),E,A,z,x)}else{var F=this.layoutRow(C,E,A,x);this.computeDim(B,[],F.dim,F,z,x)}},worstAspectRatio:function(x,F){if(!x||x.length==0){return Number.MAX_VALUE}var y=0,G=0,B=Number.MAX_VALUE;for(var D=0,C=x.length;D<C;D++){var z=x[D]._area;y+=z;B=B<z?B:z;G=G>z?G:z}var E=F*F,A=y*y;return Math.max(E*G/A,A/(E*B))},avgAspectRatio:function(B,y){if(!B||B.length==0){return Number.MAX_VALUE}var D=0;for(var z=0,x=B.length;z<x;z++){var C=B[z]._area;var A=C/y;D+=y>A?y/A:A/y}return D/x},layoutLast:function(y,x,B,A){var z=y[0];z.getPos(A).setc(B.left,B.top);z.setData("width",B.width,A);z.setData("height",B.height,A)}};g.TM.Squarified=new q({Implements:g.TM.Area,computePositions:function(A,D,x){var z=this.config;if(D.width>=D.height){this.layout.orientation="h"}else{this.layout.orientation="v"}var w=A.getSubnodes([1,1],"ignore");if(w.length>0){this.processChildrenLayout(A,w,D,x);for(var C=0,B=w.length;C<B;C++){var F=w[C];var G=z.offset,H=F.getData("height",x)-G-z.titleHeight,y=F.getData("width",x)-G;var E=F.getPos(x);D={width:y,height:H,top:E.y+z.titleHeight,left:E.x};this.computePositions(F,D,x)}}},processChildrenLayout:function(G,w,C,x){var A=C.width*C.height;var B,y=w.length,D=0,H=[];for(B=0;B<y;B++){H[B]=parseFloat(w[B].getData("area",x));D+=H[B]}for(B=0;B<y;B++){w[B]._area=A*H[B]/D}var z=this.layout.horizontal()?C.height:C.width;w.sort(function(J,I){var K=I._area-J._area;return K?K:(I.id==J.id?0:(I.id<J.id?1:-1))});var F=[w[0]];var E=w.slice(1);this.squarify(E,F,z,C,x)},squarify:function(y,B,x,A,z){this.computeDim(y,B,x,A,this.worstAspectRatio,z)},layoutRow:function(y,x,A,z){if(this.layout.horizontal()){return this.layoutV(y,x,A,z)}else{return this.layoutH(y,x,A,z)}},layoutV:function(x,I,E,y){var J=0,A=function(w){return w};c.each(x,function(w){J+=w._area});var z=A(J/I),F=0;for(var C=0,B=x.length;C<B;C++){var D=A(x[C]._area/z);var G=x[C];G.getPos(y).setc(E.left,E.top+F);G.setData("width",z,y);G.setData("height",D,y);F+=D}var H={height:E.height,width:E.width-z,top:E.top,left:E.left+z};H.dim=Math.min(H.width,H.height);if(H.dim!=H.height){this.layout.change()}return H},layoutH:function(x,G,C,y){var I=0;c.each(x,function(w){I+=w._area});var H=I/G,D=C.top,z=0;for(var B=0,A=x.length;B<A;B++){var E=x[B];var G=E._area/H;E.getPos(y).setc(C.left+z,D);E.setData("width",G,y);E.setData("height",H,y);z+=G}var F={height:C.height-H,width:C.width,top:C.top+H,left:C.left};F.dim=Math.min(F.width,F.height);if(F.dim!=F.width){this.layout.change()}return F}});g.TM.Strip=new q({Implements:g.TM.Area,computePositions:function(A,D,x){var w=A.getSubnodes([1,1],"ignore"),z=this.config;if(w.length>0){this.processChildrenLayout(A,w,D,x);for(var C=0,B=w.length;C<B;C++){var F=w[C];var G=z.offset,H=F.getData("height",x)-G-z.titleHeight,y=F.getData("width",x)-G;var E=F.getPos(x);D={width:y,height:H,top:E.y+z.titleHeight,left:E.x};this.computePositions(F,D,x)}}},processChildrenLayout:function(G,w,B,x){var z=B.width*B.height;var A,y=w.length,C=0,H=[];for(A=0;A<y;A++){H[A]=+w[A].getData("area",x);C+=H[A]}for(A=0;A<y;A++){w[A]._area=z*H[A]/C}var F=this.layout.horizontal()?B.width:B.height;var E=[w[0]];var D=w.slice(1);this.stripify(D,E,F,B,x)},stripify:function(y,B,x,A,z){this.computeDim(y,B,x,A,this.avgAspectRatio,z)},layoutRow:function(y,x,A,z){if(this.layout.horizontal()){return this.layoutH(y,x,A,z)}else{return this.layoutV(y,x,A,z)}},layoutV:function(x,G,D,y){var H=0;c.each(x,function(w){H+=w._area});var z=H/G,E=0;for(var B=0,A=x.length;B<A;B++){var F=x[B];var C=F._area/z;F.getPos(y).setc(D.left,D.top+(G-C-E));F.setData("width",z,y);F.setData("height",C,y);E+=C}return{height:D.height,width:D.width-z,top:D.top,left:D.left+z,dim:G}},layoutH:function(x,F,C,y){var H=0;c.each(x,function(w){H+=w._area});var G=H/F,D=C.height-G,z=0;for(var B=0,A=x.length;B<A;B++){var E=x[B];var I=E._area/G;E.getPos(y).setc(C.left+z,C.top+D);E.setData("width",I,y);E.setData("height",G,y);z+=I}return{height:C.height-G,width:C.width,top:C.top,left:C.left,dim:F}}});g.Icicle=new q({compute:function(E){E=E||"current";var D=this.graph.getNode(this.root),z=this.config,H=this.canvas.getSize(),w=H.width,G=H.height,A=z.offset,C=z.constrained?z.levelsToShow:Number.MAX_VALUE;this.controller.onBeforeCompute(D);e.Util.computeLevels(this.graph,D.id,0,"ignore");var F=0;e.Util.eachLevel(D,0,false,function(J,I){if(I>F){F=I}});var y=this.graph.getNode(this.clickedNode&&this.clickedNode.id||D.id);var x=Math.min(F,C-1);var B=y._depth;if(this.layout.horizontal()){this.computeSubtree(y,-w/2,-G/2,w/(x+1),G,B,x,E)}else{this.computeSubtree(y,-w/2,-G/2,w,G/(x+1),B,x,E)}},computeSubtree:function(G,I,F,w,L,E,A,H){G.getPos(H).setc(I,F);G.setData("width",w,H);G.setData("height",L,H);var C,K=0,J=0;var z=e.Util.getSubnodes(G,[1,1]);if(!z.length){return}c.each(z,function(x){J+=x.getData("dim")});for(var D=0,B=z.length;D<B;D++){if(this.layout.horizontal()){C=L*z[D].getData("dim")/J;this.computeSubtree(z[D],I+w,F,w,C,E,A,H);F+=C}else{C=w*z[D].getData("dim")/J;this.computeSubtree(z[D],I,F+L,C,L,E,A,H);I+=C}}}});$jit.Icicle=new q({Implements:[d,o,g.Icicle],layout:{orientation:"h",vertical:function(){return this.orientation=="v"},horizontal:function(){return this.orientation=="h"},change:function(){this.orientation=this.vertical()?"h":"v"}},initialize:function(w){var x={animate:false,orientation:"h",offset:2,levelsToShow:Number.MAX_VALUE,constrained:false,Node:{type:"rectangle",overridable:true},Edge:{type:"none"},Label:{type:"Native"},duration:700,fps:45};var z=n("Canvas","Node","Edge","Fx","Tips","NodeStyles","Events","Navigation","Controller","Label");this.controller=this.config=c.merge(z,x,w);this.layout.orientation=this.config.orientation;var y=this.config;if(y.useCanvas){this.canvas=y.useCanvas;this.config.labelContainer=this.canvas.id+"-label"}else{this.canvas=new l(this,y);this.config.labelContainer=(typeof y.injectInto=="string"?y.injectInto:y.injectInto.id)+"-label"}this.graphOptions={complex:true,Node:{selected:false,exist:true,drawn:true}};this.graph=new e(this.graphOptions,this.config.Node,this.config.Edge,this.config.Label);this.labels=new $jit.Icicle.Label[this.config.Label.type](this);this.fx=new $jit.Icicle.Plot(this,$jit.Icicle);this.op=new $jit.Icicle.Op(this);this.group=new $jit.Icicle.Group(this);this.clickedNode=null;this.initializeExtras()},refresh:function(){var w=this.config.Label.type;if(w!="Native"){var x=this;this.graph.eachNode(function(y){x.labels.hideLabel(y,false)})}this.compute();this.plot()},plot:function(){this.fx.plot(this.config)},enter:function(y){if(this.busy){return}this.busy=true;var x=this,w=this.config;var z={onComplete:function(){if(w.request){x.compute()}if(w.animate){x.graph.nodeList.setDataset(["current","end"],{alpha:[1,0]});e.Util.eachSubgraph(y,function(A){A.setData("alpha",1,"end")},"ignore");x.fx.animate({duration:500,modes:["node-property:alpha"],onComplete:function(){x.clickedNode=y;x.compute("end");x.fx.animate({modes:["linear","node-property:width:height"],duration:1000,onComplete:function(){x.busy=false;x.clickedNode=y}})}})}else{x.clickedNode=y;x.busy=false;x.refresh()}}};if(w.request){this.requestNodes(clickedNode,z)}else{z.onComplete()}},out:function(){if(this.busy){return}var B=this,A=e.Util,y=this.config,D=this.graph,x=A.getParents(D.getNode(this.clickedNode&&this.clickedNode.id||this.root)),z=x[0],w=z,C=this.clickedNode;this.busy=true;this.events.hoveredNode=false;if(!z){this.busy=false;return}callback={onComplete:function(){B.clickedNode=z;if(y.request){B.requestNodes(z,{onComplete:function(){B.compute();B.plot();B.busy=false}})}else{B.compute();B.plot();B.busy=false}}};if(y.animate){this.clickedNode=w;this.compute("end");this.clickedNode=C;this.fx.animate({modes:["linear","node-property:width:height"],duration:1000,onComplete:function(){B.clickedNode=w;D.nodeList.setDataset(["current","end"],{alpha:[0,1]});A.eachSubgraph(C,function(E){E.setData("alpha",1)},"ignore");B.fx.animate({duration:500,modes:["node-property:alpha"],onComplete:function(){callback.onComplete()}})}})}else{callback.onComplete()}},requestNodes:function(y,z){var x=c.merge(this.controller,z),w=this.config.constrained?this.config.levelsToShow:Number.MAX_VALUE;if(x.request){var B=[],A=y._depth;e.Util.eachLevel(y,0,w,function(C){if(C.drawn&&!e.Util.anySubnode(C)){B.push(C);C._level=C._depth-A;if(this.config.constrained){C._level=w-C._level}}});this.group.requestNodes(B,x)}else{x.onComplete()}}});$jit.Icicle.Op=new q({Implements:e.Op});$jit.Icicle.Group=new q({initialize:function(w){this.viz=w;this.canvas=w.canvas;this.config=w.config},requestNodes:function(B,A){var z=0,x=B.length,D={};var y=function(){A.onComplete()};var w=this.viz;if(x==0){y()}for(var C=0;C<x;C++){D[B[C].id]=B[C];A.request(B[C].id,B[C]._level,{onComplete:function(F,E){if(E&&E.children){E.id=F;w.op.sum(E,{type:"nothing"})}if(++z==x){e.Util.computeLevels(w.graph,w.root,0);y()}}})}}});$jit.Icicle.Plot=new q({Implements:e.Plot,plot:function(A,y){A=A||this.viz.controller;var w=this.viz,B=w.graph,x=B.getNode(w.clickedNode&&w.clickedNode.id||w.root),z=x._depth;w.canvas.clear();this.plotTree(x,c.merge(A,{withLabels:true,hideLabels:false,plotSubtree:function(C,D){return !w.config.constrained||(D._depth-z<w.config.levelsToShow)}}),y)}});$jit.Icicle.Label={};$jit.Icicle.Label.Native=new q({Implements:e.Label.Native,renderLabel:function(x,y,A){var D=x.getCtx(),w=y.getData("width"),C=y.getData("height"),E=y.getLabelData("size"),z=D.measureText(y.name);if(C<(E*1.5)||w<z.width){return}var B=y.pos.getc(true);D.fillText(y.name,B.x+w/2,B.y+C/2)}});$jit.Icicle.Label.SVG=new q({Implements:e.Label.SVG,initialize:function(w){this.viz=w},placeLabel:function(x,A,y){var C=A.pos.getc(true),z=this.viz.canvas;var w=z.getSize();var B={x:Math.round(C.x+w.width/2),y:Math.round(C.y+w.height/2)};x.setAttribute("x",B.x);x.setAttribute("y",B.y);y.onPlaceLabel(x,A)}});$jit.Icicle.Label.HTML=new q({Implements:e.Label.HTML,initialize:function(w){this.viz=w},placeLabel:function(x,B,y){var D=B.pos.getc(true),z=this.viz.canvas;var w=z.getSize();var C={x:Math.round(D.x+w.width/2),y:Math.round(D.y+w.height/2)};var A=x.style;A.left=C.x+"px";A.top=C.y+"px";A.display="";y.onPlaceLabel(x,B)}});$jit.Icicle.Plot.NodeTypes=new q({none:{render:c.empty},rectangle:{render:function(z,x,K){var y=this.viz.config;var C=y.offset;var w=z.getData("width");var H=z.getData("height");var B=z.getData("border");var G=z.pos.getc(true);var F=G.x+C/2,D=G.y+C/2;var J=x.getCtx();if(w-C<2||H-C<2){return}if(y.cushion){var A=z.getData("color");var I=J.createRadialGradient(F+(w-C)/2,D+(H-C)/2,1,F+(w-C)/2,D+(H-C)/2,w<H?H:w);var E=c.rgbToHex(c.map(c.hexToRgb(A),function(L){return L*0.3>>0}));I.addColorStop(0,A);I.addColorStop(1,E);J.fillStyle=I}if(B){J.strokeStyle=B;J.lineWidth=3}J.fillRect(F,D,Math.max(0,w-C),Math.max(0,H-C));B&&J.strokeRect(G.x,G.y,w,H)},contains:function(y,A){if(this.viz.clickedNode&&!$jit.Graph.Util.isDescendantOf(y,this.viz.clickedNode.id)){return false}var z=y.pos.getc(true),x=y.getData("width"),w=y.getData("height");return this.nodeHelper.rectangle.contains({x:z.x+x/2,y:z.y+w/2},A,x,w)}}});$jit.Icicle.Plot.EdgeTypes=new q({none:c.empty});g.ForceDirected=new q({getOptions:function(D){var B=this.canvas.getSize();var y=B.width,A=B.height;var C=0;this.graph.eachNode(function(w){C++});var E=y*A/C,z=Math.sqrt(E);var x=this.config.levelDistance;return{width:y,height:A,tstart:y*0.1,nodef:function(w){return E/(w||1)},edgef:function(w){return z*(w-x)}}},compute:function(x,y){var z=c.splat(x||["current","start","end"]);var w=this.getOptions();f.compute(this.graph,z,this.config);this.graph.computeLevels(this.root,0,"ignore");this.graph.eachNode(function(A){c.each(z,function(B){var C=A.getPos(B);if(C.equals(p.KER)){C.x=w.width/5*(Math.random()-0.5);C.y=w.height/5*(Math.random()-0.5)}A.disp={};c.each(z,function(D){A.disp[D]=r(0,0)})})});this.computePositions(z,w,y)},computePositions:function(A,y,B){var C=this.config.iterations,x=0,z=this;if(B){(function w(){for(var E=B.iter,D=0;D<E;D++){y.t=y.tstart*(1-x++/(C-1));z.computePositionStep(A,y);if(x>=C){B.onComplete();return}}B.onStep(Math.round(x/(C-1)*100));setTimeout(w,1)})()}else{for(;x<C;x++){y.t=y.tstart*(1-x/(C-1));this.computePositionStep(A,y)}}},computePositionStep:function(D,w){var E=this.graph;var y=Math.min,C=Math.max;var B=r(0,0);E.eachNode(function(G){c.each(D,function(H){G.disp[H].x=0;G.disp[H].y=0});E.eachNode(function(H){if(H.id!=G.id){c.each(D,function(L){var J=G.getPos(L),I=H.getPos(L);B.x=J.x-I.x;B.y=J.y-I.y;var K=B.norm()||1;G.disp[L].$add(B.$scale(w.nodef(K)/K))})}})});var x=!!E.getNode(this.root).visited;E.eachNode(function(G){G.eachAdjacency(function(H){var I=H.nodeTo;if(!!I.visited===x){c.each(D,function(M){var K=G.getPos(M),J=I.getPos(M);B.x=K.x-J.x;B.y=K.y-J.y;var L=B.norm()||1;G.disp[M].$add(B.$scale(-w.edgef(L)/L));I.disp[M].$add(B.$scale(-1))})}});G.visited=!x});var F=w.t,z=w.width/2,A=w.height/2;E.eachNode(function(G){c.each(D,function(J){var H=G.disp[J];var I=H.norm()||1;var J=G.getPos(J);J.$add(r(H.x*y(Math.abs(H.x),F)/I,H.y*y(Math.abs(H.y),F)/I));J.x=y(z,C(-z,J.x));J.y=y(A,C(-A,J.y))})})}});$jit.ForceDirected=new q({Implements:[d,o,g.ForceDirected],initialize:function(x){var w=$jit.ForceDirected;var y={iterations:50,levelDistance:50};this.controller=this.config=c.merge(n("Canvas","Node","Edge","Fx","Tips","NodeStyles","Events","Navigation","Controller","Label"),y,x);var z=this.config;if(z.useCanvas){this.canvas=z.useCanvas;this.config.labelContainer=this.canvas.id+"-label"}else{if(z.background){z.background=c.merge({type:"Circles"},z.background)}this.canvas=new l(this,z);this.config.labelContainer=(typeof z.injectInto=="string"?z.injectInto:z.injectInto.id)+"-label"}this.graphOptions={complex:true,Node:{selected:false,exist:true,drawn:true}};this.graph=new e(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new w.Label[z.Label.type](this);this.fx=new w.Plot(this,w);this.op=new w.Op(this);this.json=null;this.busy=false;this.initializeExtras()},refresh:function(){this.compute();this.plot()},reposition:function(){this.compute("end")},computeIncremental:function(w){w=c.merge({iter:20,property:"end",onStep:c.empty,onComplete:c.empty},w||{});this.config.onBeforeCompute(this.graph.getNode(this.root));this.compute(w.property,w)},plot:function(){this.fx.plot()},animate:function(w){this.fx.animate(c.merge({modes:["linear"]},w||{}))}});$jit.ForceDirected.$extend=true;(function(w){w.Op=new q({Implements:e.Op});w.Plot=new q({Implements:e.Plot});w.Label={};w.Label.Native=new q({Implements:e.Label.Native});w.Label.SVG=new q({Implements:e.Label.SVG,initialize:function(x){this.viz=x},placeLabel:function(H,B,C){var F=B.pos.getc(true),y=this.viz.canvas,z=y.translateOffsetX,x=y.translateOffsetY,G=y.scaleOffsetX,E=y.scaleOffsetY,D=y.getSize();var A={x:Math.round(F.x*G+z+D.width/2),y:Math.round(F.y*E+x+D.height/2)};H.setAttribute("x",A.x);H.setAttribute("y",A.y);C.onPlaceLabel(H,B)}});w.Label.HTML=new q({Implements:e.Label.HTML,initialize:function(x){this.viz=x},placeLabel:function(I,C,D){var G=C.pos.getc(true),z=this.viz.canvas,A=z.translateOffsetX,y=z.translateOffsetY,H=z.scaleOffsetX,F=z.scaleOffsetY,E=z.getSize();var B={x:Math.round(G.x*H+A+E.width/2),y:Math.round(G.y*F+y+E.height/2)};var x=I.style;x.left=B.x+"px";x.top=B.y+"px";x.display=this.fitsInCanvas(B,z)?"":"none";D.onPlaceLabel(I,C)}});w.Plot.NodeTypes=new q({none:{render:c.empty,contains:c.lambda(false)},circle:{render:function(y,x){var A=y.pos.getc(true),z=y.getData("dim");this.nodeHelper.circle.render("fill",A,z,x)},contains:function(x,A){var z=x.pos.getc(true),y=x.getData("dim");return this.nodeHelper.circle.contains(z,A,y)}},ellipse:{render:function(A,y){var B=A.pos.getc(true),z=A.getData("width"),x=A.getData("height");this.nodeHelper.ellipse.render("fill",B,z,x,y)},contains:function(z,B){var A=z.pos.getc(true),y=z.getData("width"),x=z.getData("height");return this.nodeHelper.ellipse.contains(A,B,y,x)}},square:{render:function(y,x){var A=y.pos.getc(true),z=y.getData("dim");this.nodeHelper.square.render("fill",A,z,x)},contains:function(x,A){var z=x.pos.getc(true),y=x.getData("dim");return this.nodeHelper.square.contains(z,A,y)}},rectangle:{render:function(A,y){var B=A.pos.getc(true),z=A.getData("width"),x=A.getData("height");this.nodeHelper.rectangle.render("fill",B,z,x,y)},contains:function(z,B){var A=z.pos.getc(true),y=z.getData("width"),x=z.getData("height");return this.nodeHelper.rectangle.contains(A,B,y,x)}},triangle:{render:function(y,x){var A=y.pos.getc(true),z=y.getData("dim");this.nodeHelper.triangle.render("fill",A,z,x)},contains:function(x,A){var z=x.pos.getc(true),y=x.getData("dim");return this.nodeHelper.triangle.contains(z,A,y)}},star:{render:function(y,x){var A=y.pos.getc(true),z=y.getData("dim");this.nodeHelper.star.render("fill",A,z,x)},contains:function(x,A){var z=x.pos.getc(true),y=x.getData("dim");return this.nodeHelper.star.contains(z,A,y)}}});w.Plot.EdgeTypes=new q({none:c.empty,line:{render:function(x,y){var A=x.nodeFrom.pos.getc(true),z=x.nodeTo.pos.getc(true);this.edgeHelper.line.render(A,z,y)},contains:function(x,A){var z=x.nodeFrom.pos.getc(true),y=x.nodeTo.pos.getc(true);return this.edgeHelper.line.contains(z,y,A,this.edge.epsilon)}},arrow:{render:function(y,z){var D=y.nodeFrom.pos.getc(true),C=y.nodeTo.pos.getc(true),B=y.getData("dim"),A=y.data.$direction,x=(A&&A.length>1&&A[0]!=y.nodeFrom.id);this.edgeHelper.arrow.render(D,C,B,x,z)},contains:function(x,A){var z=x.nodeFrom.pos.getc(true),y=x.nodeTo.pos.getc(true);return this.edgeHelper.arrow.contains(z,y,A,this.edge.epsilon)}}})})($jit.ForceDirected);$jit.TM={};var v=$jit.TM;$jit.TM.$extend=true;v.Base={layout:{orientation:"h",vertical:function(){return this.orientation=="v"},horizontal:function(){return this.orientation=="h"},change:function(){this.orientation=this.vertical()?"h":"v"}},initialize:function(w){var x={orientation:"h",titleHeight:13,offset:2,levelsToShow:0,constrained:false,animate:false,Node:{type:"rectangle",overridable:true,width:3,height:3,color:"#444"},Label:{textAlign:"center",textBaseline:"top"},Edge:{type:"none"},duration:700,fps:45};this.controller=this.config=c.merge(n("Canvas","Node","Edge","Fx","Controller","Tips","NodeStyles","Events","Navigation","Label"),x,w);this.layout.orientation=this.config.orientation;var y=this.config;if(y.useCanvas){this.canvas=y.useCanvas;this.config.labelContainer=this.canvas.id+"-label"}else{if(y.background){y.background=c.merge({type:"Circles"},y.background)}this.canvas=new l(this,y);this.config.labelContainer=(typeof y.injectInto=="string"?y.injectInto:y.injectInto.id)+"-label"}this.graphOptions={complex:true,Node:{selected:false,exist:true,drawn:true}};this.graph=new e(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new v.Label[y.Label.type](this);this.fx=new v.Plot(this);this.op=new v.Op(this);this.group=new v.Group(this);this.geom=new v.Geom(this);this.clickedNode=null;this.busy=false;this.initializeExtras()},refresh:function(){if(this.busy){return}this.busy=true;var x=this;if(this.config.animate){this.compute("end");this.config.levelsToShow>0&&this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode&&this.clickedNode.id||this.root));this.fx.animate(c.merge(this.config,{modes:["linear","node-property:width:height"],onComplete:function(){x.busy=false}}))}else{var w=this.config.Label.type;if(w!="Native"){var x=this;this.graph.eachNode(function(y){x.labels.hideLabel(y,false)})}this.busy=false;this.compute();this.config.levelsToShow>0&&this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode&&this.clickedNode.id||this.root));this.plot()}},plot:function(){this.fx.plot()},leaf:function(w){return w.getSubnodes([1,1],"ignore").length==0},enter:function(C){if(this.busy){return}this.busy=true;var y=this,x=this.config,A=this.graph,w=C,z=this.clickedNode;var B={onComplete:function(){if(x.levelsToShow>0){y.geom.setRightLevelToShow(C)}if(x.levelsToShow>0||x.request){y.compute()}if(x.animate){A.nodeList.setData("alpha",0,"end");C.eachSubgraph(function(D){D.setData("alpha",1,"end")},"ignore");y.fx.animate({duration:500,modes:["node-property:alpha"],onComplete:function(){y.clickedNode=w;y.compute("end");y.clickedNode=z;y.fx.animate({modes:["linear","node-property:width:height"],duration:1000,onComplete:function(){y.busy=false;y.clickedNode=w}})}})}else{y.busy=false;y.clickedNode=C;y.refresh()}}};if(x.request){this.requestNodes(w,B)}else{B.onComplete()}},out:function(){if(this.busy){return}this.busy=true;this.events.hoveredNode=false;var A=this,y=this.config,C=this.graph,x=C.getNode(this.clickedNode&&this.clickedNode.id||this.root).getParents(),z=x[0],w=z,B=this.clickedNode;if(!z){this.busy=false;return}callback={onComplete:function(){A.clickedNode=z;if(y.request){A.requestNodes(z,{onComplete:function(){A.compute();A.plot();A.busy=false}})}else{A.compute();A.plot();A.busy=false}}};if(y.levelsToShow>0){this.geom.setRightLevelToShow(z)}if(y.animate){this.clickedNode=w;this.compute("end");this.clickedNode=B;this.fx.animate({modes:["linear","node-property:width:height"],duration:1000,onComplete:function(){A.clickedNode=w;C.eachNode(function(D){D.setDataset(["current","end"],{alpha:[0,1]})},"ignore");B.eachSubgraph(function(D){D.setData("alpha",1)},"ignore");A.fx.animate({duration:500,modes:["node-property:alpha"],onComplete:function(){callback.onComplete()}})}})}else{callback.onComplete()}},requestNodes:function(y,z){var x=c.merge(this.controller,z),w=this.config.levelsToShow;if(x.request){var B=[],A=y._depth;y.eachLevel(0,w,function(D){var C=w-(D._depth-A);if(D.drawn&&!D.anySubnode()&&C>0){B.push(D);D._level=C}});this.group.requestNodes(B,x)}else{x.onComplete()}}};v.Op=new q({Implements:e.Op,initialize:function(w){this.viz=w}});v.Geom=new q({Implements:e.Geom,getRightLevelToShow:function(){return this.viz.config.levelsToShow},setRightLevelToShow:function(x){var y=this.getRightLevelToShow(),w=this.viz.labels;x.eachLevel(0,y+1,function(A){var z=A._depth-x._depth;if(z>y){A.drawn=false;A.exist=false;A.ignore=true;w.hideLabel(A,false)}else{A.drawn=true;A.exist=true;delete A.ignore}});x.drawn=true;delete x.ignore}});v.Group=new q({initialize:function(w){this.viz=w;this.canvas=w.canvas;this.config=w.config},requestNodes:function(B,A){var z=0,x=B.length,D={};var y=function(){A.onComplete()};var w=this.viz;if(x==0){y()}for(var C=0;C<x;C++){D[B[C].id]=B[C];A.request(B[C].id,B[C]._level,{onComplete:function(F,E){if(E&&E.children){E.id=F;w.op.sum(E,{type:"nothing"})}if(++z==x){w.graph.computeLevels(w.root,0);y()}}})}}});v.Plot=new q({Implements:e.Plot,initialize:function(w){this.viz=w;this.config=w.config;this.node=this.config.Node;this.edge=this.config.Edge;this.animation=new u;this.nodeTypes=new v.Plot.NodeTypes;this.edgeTypes=new v.Plot.EdgeTypes;this.labels=w.labels},plot:function(y,x){var w=this.viz,z=w.graph;w.canvas.clear();this.plotTree(z.getNode(w.clickedNode&&w.clickedNode.id||w.root),c.merge(w.config,y||{},{withLabels:true,hideLabels:false,plotSubtree:function(B,A){return B.anySubnode("exist")}}),x)}});v.Label={};v.Label.Native=new q({Implements:e.Label.Native,initialize:function(w){this.config=w.config;this.leaf=w.leaf},renderLabel:function(z,A,B){if(!this.leaf(A)&&!this.config.titleHeight){return}var D=A.pos.getc(true),G=z.getCtx(),w=A.getData("width"),F=A.getData("height"),E=D.x+w/2,C=D.y;G.fillText(A.name,E,C,w)}});v.Label.SVG=new q({Implements:e.Label.SVG,initialize:function(w){this.viz=w;this.leaf=w.leaf;this.config=w.config},placeLabel:function(G,A,B){var E=A.pos.getc(true),x=this.viz.canvas,y=x.translateOffsetX,w=x.translateOffsetY,F=x.scaleOffsetX,D=x.scaleOffsetY,C=x.getSize();var z={x:Math.round(E.x*F+y+C.width/2),y:Math.round(E.y*D+w+C.height/2)};G.setAttribute("x",z.x);G.setAttribute("y",z.y);if(!this.leaf(A)&&!this.config.titleHeight){G.style.display="none"}B.onPlaceLabel(G,A)}});v.Label.HTML=new q({Implements:e.Label.HTML,initialize:function(w){this.viz=w;this.leaf=w.leaf;this.config=w.config},placeLabel:function(H,B,C){var F=B.pos.getc(true),y=this.viz.canvas,z=y.translateOffsetX,x=y.translateOffsetY,G=y.scaleOffsetX,E=y.scaleOffsetY,D=y.getSize();var A={x:Math.round(F.x*G+z+D.width/2),y:Math.round(F.y*E+x+D.height/2)};var w=H.style;w.left=A.x+"px";w.top=A.y+"px";w.width=B.getData("width")*G+"px";w.height=B.getData("height")*E+"px";w.zIndex=B._depth*100;w.display="";if(!this.leaf(B)&&!this.config.titleHeight){H.style.display="none"}C.onPlaceLabel(H,B)}});v.Plot.NodeTypes=new q({none:{render:c.empty},rectangle:{render:function(z,x,M){var D=this.viz.leaf(z),y=this.config,I=y.offset,C=y.titleHeight,H=z.pos.getc(true),w=z.getData("width"),J=z.getData("height"),B=z.getData("border"),L=x.getCtx(),G=H.x+I/2,E=H.y+I/2;if(w<=I||J<=I){return}if(D){if(y.cushion){var K=L.createRadialGradient(G+(w-I)/2,E+(J-I)/2,1,G+(w-I)/2,E+(J-I)/2,w<J?J:w);var A=z.getData("color");var F=c.rgbToHex(c.map(c.hexToRgb(A),function(N){return N*0.2>>0}));K.addColorStop(0,A);K.addColorStop(1,F);L.fillStyle=K}L.fillRect(G,E,w-I,J-I);if(B){L.save();L.strokeStyle=B;L.strokeRect(G,E,w-I,J-I);L.restore()}}else{if(C>0){L.fillRect(H.x+I/2,H.y+I/2,w-I,C-I);if(B){L.save();L.strokeStyle=B;L.strokeRect(H.x+I/2,H.y+I/2,w-I,J-I);L.restore()}}}},contains:function(z,B){if(this.viz.clickedNode&&!z.isDescendantOf(this.viz.clickedNode.id)||z.ignore){return false}var A=z.pos.getc(true),y=z.getData("width"),x=this.viz.leaf(z),w=x?z.getData("height"):this.config.titleHeight;return this.nodeHelper.rectangle.contains({x:A.x+y/2,y:A.y+w/2},B,y,w)}}});v.Plot.EdgeTypes=new q({none:c.empty});v.SliceAndDice=new q({Implements:[d,o,v.Base,g.TM.SliceAndDice]});v.Squarified=new q({Implements:[d,o,v.Base,g.TM.Squarified]});v.Strip=new q({Implements:[d,o,v.Base,g.TM.Strip]});$jit.RGraph=new q({Implements:[d,o,g.Radial],initialize:function(w){var x=$jit.RGraph;var y={interpolation:"linear",levelDistance:100};this.controller=this.config=c.merge(n("Canvas","Node","Edge","Fx","Controller","Tips","NodeStyles","Events","Navigation","Label"),y,w);var z=this.config;if(z.useCanvas){this.canvas=z.useCanvas;this.config.labelContainer=this.canvas.id+"-label"}else{if(z.background){z.background=c.merge({type:"Circles"},z.background)}this.canvas=new l(this,z);this.config.labelContainer=(typeof z.injectInto=="string"?z.injectInto:z.injectInto.id)+"-label"}this.graphOptions={complex:false,Node:{selected:false,exist:true,drawn:true}};this.graph=new e(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new x.Label[z.Label.type](this);this.fx=new x.Plot(this,x);this.op=new x.Op(this);this.json=null;this.root=null;this.busy=false;this.parent=false;this.initializeExtras()},createLevelDistanceFunc:function(){var w=this.config.levelDistance;return function(x){return(x._depth+1)*w}},refresh:function(){this.compute();this.plot()},reposition:function(){this.compute("end")},plot:function(){this.fx.plot()},getNodeAndParentAngle:function(D){var y=false;var C=this.graph.getNode(D);var A=C.getParents();var z=(A.length>0)?A[0]:false;if(z){var w=z.pos.getc(),B=C.pos.getc();var x=w.add(B.scale(-1));y=Math.atan2(x.y,x.x);if(y<0){y+=2*Math.PI}}return{parent:z,theta:y}},tagChildren:function(A,C){if(A.angleSpan){var B=[];A.eachAdjacency(function(D){B.push(D.nodeTo)},"ignore");var w=B.length;for(var z=0;z<w&&C!=B[z].id;z++){}for(var y=(z+1)%w,x=0;C!=B[y].id;y=(y+1)%w){B[y].dist=x++}}},onClick:function(A,x){if(this.root!=A&&!this.busy){this.busy=true;this.root=A;that=this;this.controller.onBeforeCompute(this.graph.getNode(A));var y=this.getNodeAndParentAngle(A);this.tagChildren(y.parent,A);this.parent=y.parent;this.compute("end");var w=y.theta-y.parent.endPos.theta;this.graph.eachNode(function(B){B.endPos.set(B.endPos.getp().add(k(w,0)))});var z=this.config.interpolation;x=c.merge({onComplete:c.empty},x||{});this.fx.animate(c.merge({hideLabels:true,modes:[z]},x,{onComplete:function(){that.busy=false;x.onComplete()}}))}}});$jit.RGraph.$extend=true;(function(w){w.Op=new q({Implements:e.Op});w.Plot=new q({Implements:e.Plot});w.Label={};w.Label.Native=new q({Implements:e.Label.Native});w.Label.SVG=new q({Implements:e.Label.SVG,initialize:function(x){this.viz=x},placeLabel:function(H,B,C){var F=B.pos.getc(true),y=this.viz.canvas,z=y.translateOffsetX,x=y.translateOffsetY,G=y.scaleOffsetX,E=y.scaleOffsetY,D=y.getSize();var A={x:Math.round(F.x*G+z+D.width/2),y:Math.round(F.y*E+x+D.height/2)};H.setAttribute("x",A.x);H.setAttribute("y",A.y);C.onPlaceLabel(H,B)}});w.Label.HTML=new q({Implements:e.Label.HTML,initialize:function(x){this.viz=x},placeLabel:function(I,C,D){var G=C.pos.getc(true),z=this.viz.canvas,A=z.translateOffsetX,y=z.translateOffsetY,H=z.scaleOffsetX,F=z.scaleOffsetY,E=z.getSize();var B={x:Math.round(G.x*H+A+E.width/2),y:Math.round(G.y*F+y+E.height/2)};var x=I.style;x.left=B.x+"px";x.top=B.y+"px";x.display=this.fitsInCanvas(B,z)?"":"none";D.onPlaceLabel(I,C)}});w.Plot.NodeTypes=new q({none:{render:c.empty,contains:c.lambda(false)},circle:{render:function(y,x){var A=y.pos.getc(true),z=y.getData("dim");this.nodeHelper.circle.render("fill",A,z,x)},contains:function(x,A){var z=x.pos.getc(true),y=x.getData("dim");return this.nodeHelper.circle.contains(z,A,y)}},ellipse:{render:function(A,y){var B=A.pos.getc(true),z=A.getData("width"),x=A.getData("height");this.nodeHelper.ellipse.render("fill",B,z,x,y)},contains:function(z,B){var A=z.pos.getc(true),y=z.getData("width"),x=z.getData("height");return this.nodeHelper.ellipse.contains(A,B,y,x)}},square:{render:function(y,x){var A=y.pos.getc(true),z=y.getData("dim");this.nodeHelper.square.render("fill",A,z,x)},contains:function(x,A){var z=x.pos.getc(true),y=x.getData("dim");return this.nodeHelper.square.contains(z,A,y)}},rectangle:{render:function(A,y){var B=A.pos.getc(true),z=A.getData("width"),x=A.getData("height");this.nodeHelper.rectangle.render("fill",B,z,x,y)},contains:function(z,B){var A=z.pos.getc(true),y=z.getData("width"),x=z.getData("height");return this.nodeHelper.rectangle.contains(A,B,y,x)}},triangle:{render:function(y,x){var A=y.pos.getc(true),z=y.getData("dim");this.nodeHelper.triangle.render("fill",A,z,x)},contains:function(x,A){var z=x.pos.getc(true),y=x.getData("dim");return this.nodeHelper.triangle.contains(z,A,y)}},star:{render:function(y,x){var A=y.pos.getc(true),z=y.getData("dim");this.nodeHelper.star.render("fill",A,z,x)},contains:function(x,A){var z=x.pos.getc(true),y=x.getData("dim");return this.nodeHelper.star.contains(z,A,y)}}});w.Plot.EdgeTypes=new q({none:c.empty,line:{render:function(x,y){var A=x.nodeFrom.pos.getc(true),z=x.nodeTo.pos.getc(true);this.edgeHelper.line.render(A,z,y)},contains:function(x,A){var z=x.nodeFrom.pos.getc(true),y=x.nodeTo.pos.getc(true);return this.edgeHelper.line.contains(z,y,A,this.edge.epsilon)}},arrow:{render:function(y,z){var D=y.nodeFrom.pos.getc(true),C=y.nodeTo.pos.getc(true),B=y.getData("dim"),A=y.data.$direction,x=(A&&A.length>1&&A[0]!=y.nodeFrom.id);this.edgeHelper.arrow.render(D,C,B,x,z)},contains:function(x,A){var z=x.nodeFrom.pos.getc(true),y=x.nodeTo.pos.getc(true);return this.edgeHelper.arrow.contains(z,y,A,this.edge.epsilon)}}})})($jit.RGraph);p.prototype.moebiusTransformation=function(y){var w=this.add(y);var x=y.$conjugate().$prod(this);x.x++;return w.$div(x)};e.Util.moebiusTransformation=function(y,A,z,x,w){this.eachNode(y,function(C){for(var B=0;B<z.length;B++){var E=A[B].scale(-1),D=x?x:z[B];C.getPos(z[B]).set(C.getPos(D).getc().moebiusTransformation(E))}},w)};$jit.Hypertree=new q({Implements:[d,o,g.Radial],initialize:function(w){var z=$jit.Hypertree;var x={radius:"auto",offset:0,Edge:{type:"hyperline"},duration:1500,fps:35};this.controller=this.config=c.merge(n("Canvas","Node","Edge","Fx","Tips","NodeStyles","Events","Navigation","Controller","Label"),x,w);var y=this.config;if(y.useCanvas){this.canvas=y.useCanvas;this.config.labelContainer=this.canvas.id+"-label"}else{if(y.background){y.background=c.merge({type:"Circles"},y.background)}this.canvas=new l(this,y);this.config.labelContainer=(typeof y.injectInto=="string"?y.injectInto:y.injectInto.id)+"-label"}this.graphOptions={complex:false,Node:{selected:false,exist:true,drawn:true}};this.graph=new e(this.graphOptions,this.config.Node,this.config.Edge);this.labels=new z.Label[y.Label.type](this);this.fx=new z.Plot(this,z);this.op=new z.Op(this);this.json=null;this.root=null;this.busy=false;this.initializeExtras()},createLevelDistanceFunc:function(){var A=this.getRadius();var C=0,w=Math.max,x=this.config;this.graph.eachNode(function(D){C=w(D._depth,C)},"ignore");C++;var B=function(D){return function(F){F.scale=A;var H=F._depth+1;var G=0,E=Math.pow;while(H){G+=E(D,H--)}return G-x.offset}};for(var z=0.51;z<=1;z+=0.01){var y=(1-Math.pow(z,C))/(1-z);if(y>=2){return B(z-0.01)}}return B(0.75)},getRadius:function(){var w=this.config.radius;if(w!=="auto"){return w}var x=this.canvas.getSize();return Math.min(x.width,x.height)/2},refresh:function(w){if(w){this.reposition();this.graph.eachNode(function(x){x.startPos.rho=x.pos.rho=x.endPos.rho;x.startPos.theta=x.pos.theta=x.endPos.theta})}else{this.compute()}this.plot()},reposition:function(){this.compute("end");var w=this.graph.getNode(this.root).pos.getc().scale(-1);e.Util.moebiusTransformation(this.graph,[w],["end"],"end","ignore");this.graph.eachNode(function(x){if(x.ignore){x.endPos.rho=x.pos.rho;x.endPos.theta=x.pos.theta}})},plot:function(){this.fx.plot()},onClick:function(y,w){var x=this.graph.getNode(y).pos.getc(true);this.move(x,w)},move:function(A,y){var x=r(A.x,A.y);if(this.busy===false&&x.norm()<1){this.busy=true;var w=this.graph.getClosestNodeToPos(x),z=this;this.graph.computeLevels(w.id,0);this.controller.onBeforeCompute(w);y=c.merge({onComplete:c.empty},y||{});this.fx.animate(c.merge({modes:["moebius"],hideLabels:true},y,{onComplete:function(){z.busy=false;y.onComplete()}}),x)}}});$jit.Hypertree.$extend=true;(function(w){w.Op=new q({Implements:e.Op});w.Plot=new q({Implements:e.Plot});w.Label={};w.Label.Native=new q({Implements:e.Label.Native,initialize:function(x){this.viz=x},renderLabel:function(z,B,y){var x=z.getCtx();var C=B.pos.getc(true);var A=this.viz.getRadius();x.fillText(B.name,C.x*A,C.y*A)}});w.Label.SVG=new q({Implements:e.Label.SVG,initialize:function(x){this.viz=x},placeLabel:function(I,C,D){var G=C.pos.getc(true),z=this.viz.canvas,A=z.translateOffsetX,y=z.translateOffsetY,H=z.scaleOffsetX,F=z.scaleOffsetY,E=z.getSize(),x=this.viz.getRadius();var B={x:Math.round((G.x*H)*x+A+E.width/2),y:Math.round((G.y*F)*x+y+E.height/2)};I.setAttribute("x",B.x);I.setAttribute("y",B.y);D.onPlaceLabel(I,C)}});w.Label.HTML=new q({Implements:e.Label.HTML,initialize:function(x){this.viz=x},placeLabel:function(J,D,E){var H=D.pos.getc(true),A=this.viz.canvas,B=A.translateOffsetX,z=A.translateOffsetY,I=A.scaleOffsetX,G=A.scaleOffsetY,F=A.getSize(),x=this.viz.getRadius();var C={x:Math.round((H.x*I)*x+B+F.width/2),y:Math.round((H.y*G)*x+z+F.height/2)};var y=J.style;y.left=C.x+"px";y.top=C.y+"px";y.display=this.fitsInCanvas(C,A)?"":"none";E.onPlaceLabel(J,D)}});w.Plot.NodeTypes=new q({none:{render:c.empty,contains:c.lambda(false)},circle:{render:function(z,x){var y=this.node,B=z.getData("dim"),A=z.pos.getc();B=y.transform?B*(1-A.squaredNorm()):B;A.$scale(z.scale);if(B>0.2){this.nodeHelper.circle.render("fill",A,B,x)}},contains:function(x,A){var y=x.getData("dim"),z=x.pos.getc().$scale(x.scale);return this.nodeHelper.circle.contains(z,A,y)}},ellipse:{render:function(A,y){var B=A.pos.getc().$scale(A.scale),z=A.getData("width"),x=A.getData("height");this.nodeHelper.ellipse.render("fill",B,z,x,y)},contains:function(z,B){var y=z.getData("width"),x=z.getData("height"),A=z.pos.getc().$scale(z.scale);return this.nodeHelper.circle.contains(A,B,y,x)}},square:{render:function(z,x){var y=this.node,B=z.getData("dim"),A=z.pos.getc();B=y.transform?B*(1-A.squaredNorm()):B;A.$scale(z.scale);if(B>0.2){this.nodeHelper.square.render("fill",A,B,x)}},contains:function(x,A){var y=x.getData("dim"),z=x.pos.getc().$scale(x.scale);return this.nodeHelper.square.contains(z,A,y)}},rectangle:{render:function(B,y){var A=this.node,z=B.getData("width"),x=B.getData("height"),C=B.pos.getc();z=A.transform?z*(1-C.squaredNorm()):z;x=A.transform?x*(1-C.squaredNorm()):x;C.$scale(B.scale);if(z>0.2&&x>0.2){this.nodeHelper.rectangle.render("fill",C,z,x,y)}},contains:function(z,B){var y=z.getData("width"),x=z.getData("height"),A=z.pos.getc().$scale(z.scale);return this.nodeHelper.square.contains(A,B,y,x)}},triangle:{render:function(z,x){var y=this.node,B=z.getData("dim"),A=z.pos.getc();B=y.transform?B*(1-A.squaredNorm()):B;A.$scale(z.scale);if(B>0.2){this.nodeHelper.triangle.render("fill",A,B,x)}},contains:function(x,A){var y=x.getData("dim"),z=x.pos.getc().$scale(x.scale);return this.nodeHelper.triangle.contains(z,A,y)}},star:{render:function(z,x){var y=this.node,B=z.getData("dim"),A=z.pos.getc();B=y.transform?B*(1-A.squaredNorm()):B;A.$scale(z.scale);if(B>0.2){this.nodeHelper.star.render("fill",A,B,x)}},contains:function(x,A){var y=x.getData("dim"),z=x.pos.getc().$scale(x.scale);return this.nodeHelper.star.contains(z,A,y)}}});w.Plot.EdgeTypes=new q({none:c.empty,line:{render:function(x,y){var B=x.nodeFrom.pos.getc(true),A=x.nodeTo.pos.getc(true),z=x.nodeFrom.scale;this.edgeHelper.line.render({x:B.x*z,y:B.y*z},{x:A.x*z,y:A.y*z},y)},contains:function(x,B){var A=x.nodeFrom.pos.getc(true),z=x.nodeTo.pos.getc(true),y=x.nodeFrom.scale;this.edgeHelper.line.contains({x:A.x*y,y:A.y*y},{x:z.x*y,y:z.y*y},B,this.edge.epsilon)}},arrow:{render:function(y,z){var E=y.nodeFrom.pos.getc(true),D=y.nodeTo.pos.getc(true),A=y.nodeFrom.scale,C=y.getData("dim"),B=y.data.$direction,x=(B&&B.length>1&&B[0]!=y.nodeFrom.id);this.edgeHelper.arrow.render({x:E.x*A,y:E.y*A},{x:D.x*A,y:D.y*A},C,x,z)},contains:function(x,B){var A=x.nodeFrom.pos.getc(true),z=x.nodeTo.pos.getc(true),y=x.nodeFrom.scale;this.edgeHelper.arrow.contains({x:A.x*y,y:A.y*y},{x:z.x*y,y:z.y*y},B,this.edge.epsilon)}},hyperline:{render:function(x,y){var B=x.nodeFrom.pos.getc(),A=x.nodeTo.pos.getc(),z=this.viz.getRadius();this.edgeHelper.hyperline.render(B,A,z,y)},contains:c.lambda(false)}})})($jit.Hypertree)})();

//}}}
/***
https://github.com/tiddlyweb/chrjs/raw/master/users.js
***/
//{{{
// chrjs users extension
// v0.5.0
//
// requires tiddlywebplugins.socialusers
// http://pypi.python.org/pypi/tiddlywebplugins.socialusers

/*jslint vars: true */
/*global jQuery, tiddlyweb */

(function($, tw) {

"use strict";

tw.routes.users = "{host}/users";
tw.routes.user = "{host}/users/{username}";

tw.User = function(username, password, host) {
	tw.Resource.apply(this, ["user", host]);
	this.username = username;
	this.password = password;
};
tw.User.prototype = new tw.Resource();
$.extend(tw.User.prototype, {
	create: function(callback, errback) {
		var uri = this.route().split("/"); // XXX: hacky!?
		uri.pop();
		uri = uri.join("/");
		var data = {
			username: this.username,
			password: this.password
		};
		var self = this;
		return $.ajax({
			url: uri,
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify(data),
			success: callback,
			error: function(xhr, error, exc) {
				errback(xhr, error, exc, self);
			}
		});
	},
	setPassword: function(newPass, callback, errback) {
		this.old_password = this.password; // XXX: should not use underscore (consistency)
		this.password = newPass;
		return this.put(callback, errback);
	},
	data: ["password", "old_password"]
});

}(jQuery, tiddlyweb));
//}}}
//
// Please note:
//
// * This code is designed to be readable but for compactness it only includes brief comments. You can see fuller comments
//   in the project repository at https://github.com/TiddlyWiki/tiddlywiki
//
// * You should never need to modify this source code directly. TiddlyWiki is carefully designed to allow deep customisation
//   without changing the core code. Please consult the development group at http://groups.google.com/group/TiddlyWikiDev
//
// JSLint directives
/*global jQuery:false, version:false */
/*jslint bitwise:true, browser:true, confusion:true, eqeq:true, evil:true, forin:true, maxerr:100, plusplus:true, regexp:true, sloppy:true, sub:true, undef:true, unparam:true, vars:true, white:true */
//--
//-- Configuration repository
//--

// Miscellaneous options
var config = {
	numRssItems: 20, // Number of items in the RSS feed
	animDuration: 400, // Duration of UI animations in milliseconds
	cascadeFast: 20, // Speed for cascade animations (higher == slower)
	cascadeSlow: 60, // Speed for EasterEgg cascade animations
	cascadeDepth: 5, // Depth of cascade animation
	locale: "en" // W3C language tag
};

// Hashmap of alternative parsers for the wikifier
config.parsers = {};

// Adaptors
config.adaptors = {};
config.defaultAdaptor = null;

// Backstage tasks
config.tasks = {};

// Annotations
config.annotations = {};

// Custom fields to be automatically added to new tiddlers
config.defaultCustomFields = {};

// Messages
config.messages = {
	messageClose: {},
	dates: {},
	tiddlerPopup: {}
};

// Options that can be set in the options panel and/or cookies
config.options = {
	chkRegExpSearch: false,
	chkCaseSensitiveSearch: false,
	chkIncrementalSearch: true,
	chkAnimate: true,
	chkSaveBackups: true,
	chkAutoSave: false,
	chkGenerateAnRssFeed: false,
	chkSaveEmptyTemplate: false,
	chkOpenInNewWindow: true,
	chkToggleLinks: false,
	chkHttpReadOnly: false,
	chkForceMinorUpdate: false,
	chkConfirmDelete: true,
	chkInsertTabs: false,
	chkUsePreForStorage: true, // Whether to use <pre> format for storage
	chkDisplayInstrumentation: false,
	txtBackupFolder: "",
	txtEditorFocus: "text",
	txtMainTab: "tabTimeline",
	txtMoreTab: "moreTabAll",
	txtMaxEditRows: "30",
	txtFileSystemCharSet: "UTF-8",
	txtTheme: ""
	};
config.optionsDesc = {};

config.optionsSource = {};

// Default tiddler templates
var DEFAULT_VIEW_TEMPLATE = 1;
var DEFAULT_EDIT_TEMPLATE = 2;
config.tiddlerTemplates = {
	1: "ViewTemplate",
	2: "EditTemplate"
};

// More messages (rather a legacy layout that should not really be like this)
config.views = {
	wikified: {
		tag: {}
	},
	editor: {
		tagChooser: {}
	}
};

// Backstage tasks
config.backstageTasks = ["save","sync","importTask","tweak","plugins"];

// Extensions
config.extensions = {};

// Macros; each has a 'handler' member that is inserted later
config.macros = {
	today: {},
	version: {},
	search: {sizeTextbox: 15},
	tiddler: {},
	tag: {},
	tags: {},
	tagging: {},
	timeline: {},
	allTags: {},
	list: {
		all: {},
		missing: {},
		orphans: {},
		shadowed: {},
		touched: {},
		filter: {}
	},
	closeAll: {},
	permaview: {},
	saveChanges: {},
	slider: {},
	option: {},
	options: {},
	newTiddler: {},
	newJournal: {},
	tabs: {},
	gradient: {},
	message: {},
	view: {defaultView: "text"},
	edit: {},
	tagChooser: {},
	toolbar: {},
	plugins: {},
	refreshDisplay: {},
	importTiddlers: {},
	upgrade: {
		source: "http://tiddlywiki-releases.tiddlyspace.com/upgrade",
		backupExtension: "pre.core.upgrade"
	},
	sync: {},
	annotations: {}
};

// Commands supported by the toolbar macro
config.commands = {
	closeTiddler: {},
	closeOthers: {},
	editTiddler: {},
	saveTiddler: {hideReadOnly: true},
	cancelTiddler: {},
	deleteTiddler: {hideReadOnly: true},
	permalink: {},
	references: {type: "popup"},
	jump: {type: "popup"},
	syncing: {type: "popup"},
	fields: {type: "popup"}
};

// Control of macro parameter evaluation
config.evaluateMacroParameters = "all";

// Basic regular expressions
config.textPrimitives = {
	upperLetter: "[A-Z\u00c0-\u00de\u0150\u0170]",
	lowerLetter: "[a-z0-9_\\-\u00df-\u00ff\u0151\u0171]",
	anyLetter:   "[A-Za-z0-9_\\-\u00c0-\u00de\u00df-\u00ff\u0150\u0170\u0151\u0171]",
	anyLetterStrict: "[A-Za-z0-9\u00c0-\u00de\u00df-\u00ff\u0150\u0170\u0151\u0171]"
};
if(!((new RegExp("[\u0150\u0170]","g")).test("\u0150"))) {
	config.textPrimitives = {
		upperLetter: "[A-Z\u00c0-\u00de]",
		lowerLetter: "[a-z0-9_\\-\u00df-\u00ff]",
		anyLetter:   "[A-Za-z0-9_\\-\u00c0-\u00de\u00df-\u00ff]",
		anyLetterStrict: "[A-Za-z0-9\u00c0-\u00de\u00df-\u00ff]"
	};
}
config.textPrimitives.sliceSeparator = "::";
config.textPrimitives.sectionSeparator = "##";
config.textPrimitives.urlPattern = "(?:file|http|https|mailto|ftp|irc|news|data):[^\\s'\"]+(?:/|\\b)";
config.textPrimitives.unWikiLink = "~";
config.textPrimitives.wikiLink = "(?:(?:" + config.textPrimitives.upperLetter + "+" +
	config.textPrimitives.lowerLetter + "+" +
	config.textPrimitives.upperLetter +
	config.textPrimitives.anyLetter + "*)|(?:" +
	config.textPrimitives.upperLetter + "{2,}" +
	config.textPrimitives.lowerLetter + "+))";

config.textPrimitives.cssLookahead = "(?:(" + config.textPrimitives.anyLetter + "+)\\(([^\\)\\|\\n]+)(?:\\):))|(?:(" + config.textPrimitives.anyLetter + "+):([^;\\|\\n]+);)";
config.textPrimitives.cssLookaheadRegExp = new RegExp(config.textPrimitives.cssLookahead,"mg");

config.textPrimitives.brackettedLink = "\\[\\[([^\\]]+)\\]\\]";
config.textPrimitives.titledBrackettedLink = "\\[\\[([^\\[\\]\\|]+)\\|([^\\[\\]\\|]+)\\]\\]";
config.textPrimitives.tiddlerForcedLinkRegExp = new RegExp("(?:" + config.textPrimitives.titledBrackettedLink + ")|(?:" +
	config.textPrimitives.brackettedLink + ")|(?:" +
	config.textPrimitives.urlPattern + ")","mg");
config.textPrimitives.tiddlerAnyLinkRegExp = new RegExp("("+ config.textPrimitives.wikiLink + ")|(?:" +
	config.textPrimitives.titledBrackettedLink + ")|(?:" +
	config.textPrimitives.brackettedLink + ")|(?:" +
	config.textPrimitives.urlPattern + ")","mg");

config.glyphs = {
	currBrowser: null,
	browsers: [],
	codes: {}
};

//--
//-- Shadow tiddlers
//--

config.shadowTiddlers = {
	StyleSheet: "",
	MarkupPreHead: "",
	MarkupPostHead: "",
	MarkupPreBody: "",
	MarkupPostBody: "",
	TabTimeline: '<<timeline>>',
	TabAll: '<<list all>>',
	TabTags: '<<allTags excludeLists>>',
	TabMoreMissing: '<<list missing>>',
	TabMoreOrphans: '<<list orphans>>',
	TabMoreShadowed: '<<list shadowed>>',
	AdvancedOptions: '<<options>>',
	PluginManager: '<<plugins>>',
	SystemSettings: '',
	ToolbarCommands: '|~ViewToolbar|closeTiddler closeOthers +editTiddler > fields syncing permalink references jump|\n|~EditToolbar|+saveTiddler -cancelTiddler deleteTiddler|',
	WindowTitle: '<<tiddler SiteTitle>> - <<tiddler SiteSubtitle>>'
};

// Browser detection... In a very few places, there's nothing else for it but to know what browser we're using.
config.userAgent = navigator.userAgent.toLowerCase();
config.browser = {
	isIE: config.userAgent.indexOf("msie") != -1 && config.userAgent.indexOf("opera") == -1,
	isGecko: navigator.product == "Gecko" && config.userAgent.indexOf("WebKit") == -1,
	ieVersion: /MSIE (\d.\d)/i.exec(config.userAgent), // config.browser.ieVersion[1], if it exists, will be the IE version string, eg "6.0"
	isSafari: config.userAgent.indexOf("applewebkit") != -1,
	isBadSafari: !((new RegExp("[\u0150\u0170]","g")).test("\u0150")),
	firefoxDate: /gecko\/(\d{8})/i.exec(config.userAgent), // config.browser.firefoxDate[1], if it exists, will be Firefox release date as "YYYYMMDD"
	isOpera: config.userAgent.indexOf("opera") != -1,
	isChrome: config.userAgent.indexOf('chrome') > -1,
	isLinux: config.userAgent.indexOf("linux") != -1,
	isUnix: config.userAgent.indexOf("x11") != -1,
	isMac: config.userAgent.indexOf("mac") != -1,
	isWindows: config.userAgent.indexOf("win") != -1
};

merge(config.glyphs,{
	browsers: [
		function() {return config.browser.isIE;},
		function() {return true;}
		],
	codes: {
		downTriangle: ["\u25BC","\u25BE"],
		downArrow: ["\u2193","\u2193"],
		bentArrowLeft: ["\u2190","\u21A9"],
		bentArrowRight: ["\u2192","\u21AA"]
	}
});

//--
//-- Translateable strings
//--

// Strings in "double quotes" should be translated; strings in 'single quotes' should be left alone

merge(config.options,{
	txtUserName: "YourName"});

merge(config.tasks,{
	save: {text: "save", tooltip: "Save your changes to this TiddlyWiki"},
	importTask: {text: "import", tooltip: "Import tiddlers and plugins from other TiddlyWiki files and servers", content: '<<importTiddlers>>'},
	tweak: {text: "tweak", tooltip: "Tweak the appearance and behaviour of TiddlyWiki", content: '<<options>>'},
	upgrade: {text: "upgrade", tooltip: "Upgrade TiddlyWiki core code", content: '<<upgrade>>'},
	plugins: {text: "plugins", tooltip: "Manage installed plugins", content: '<<plugins>>'}
});

// Options that can be set in the options panel and/or cookies
merge(config.optionsDesc,{
	txtUserName: "Username for signing your edits",
	chkRegExpSearch: "Enable regular expressions for searches",
	chkCaseSensitiveSearch: "Case-sensitive searching",
	chkIncrementalSearch: "Incremental key-by-key searching",
	chkAnimate: "Enable animations",
	chkSaveBackups: "Keep backup file when saving changes",
	chkAutoSave: "Automatically save changes",
	chkGenerateAnRssFeed: "Generate an RSS feed when saving changes",
	chkSaveEmptyTemplate: "Generate an empty template when saving changes",
	chkOpenInNewWindow: "Open external links in a new window",
	chkToggleLinks: "Clicking on links to open tiddlers causes them to close",
	chkHttpReadOnly: "Hide editing features when viewed over HTTP",
	chkForceMinorUpdate: "Don't update modifier username and date when editing tiddlers",
	chkConfirmDelete: "Require confirmation before deleting tiddlers",
	chkInsertTabs: "Use the tab key to insert tab characters instead of moving between fields",
	txtBackupFolder: "Name of folder to use for backups",
	txtMaxEditRows: "Maximum number of rows in edit boxes",
	txtTheme: "Name of the theme to use",
	txtFileSystemCharSet: "Default character set for saving changes (Firefox/Mozilla only)"});

merge(config.messages,{
	customConfigError: "Problems were encountered loading plugins. See PluginManager for details",
	pluginError: "Error: %0",
	pluginDisabled: "Not executed because disabled via 'systemConfigDisable' tag",
	pluginForced: "Executed because forced via 'systemConfigForce' tag",
	pluginVersionError: "Not executed because this plugin needs a newer version of TiddlyWiki",
	nothingSelected: "Nothing is selected. You must select one or more items first",
	savedSnapshotError: "It appears that this TiddlyWiki has been incorrectly saved. Please see http://www.tiddlywiki.com/#Download for details",
	subtitleUnknown: "(unknown)",
	undefinedTiddlerToolTip: "The tiddler '%0' doesn't yet exist",
	shadowedTiddlerToolTip: "The tiddler '%0' doesn't yet exist, but has a pre-defined shadow value",
	tiddlerLinkTooltip: "%0 - %1, %2",
	externalLinkTooltip: "External link to %0",
	noTags: "There are no tagged tiddlers",
	notFileUrlError: "You need to save this TiddlyWiki to a file before you can save changes",
	cantSaveError: "It's not possible to save changes. Possible reasons include:\n- your browser doesn't support saving (Firefox, Internet Explorer, Safari and Opera all work if properly configured)\n- the pathname to your TiddlyWiki file contains illegal characters\n- the TiddlyWiki HTML file has been moved or renamed",
	invalidFileError: "The original file '%0' does not appear to be a valid TiddlyWiki",
	backupSaved: "Backup saved",
	backupFailed: "Failed to save backup file",
	rssSaved: "RSS feed saved",
	rssFailed: "Failed to save RSS feed file",
	emptySaved: "Empty template saved",
	emptyFailed: "Failed to save empty template file",
	mainSaved: "Main TiddlyWiki file saved",
	mainFailed: "Failed to save main TiddlyWiki file. Your changes have not been saved",
	macroError: "Error in macro <<%0>>",
	macroErrorDetails: "Error while executing macro <<%0>>:\n%1",
	missingMacro: "No such macro",
	overwriteWarning: "A tiddler named '%0' already exists. Choose OK to overwrite it",
	unsavedChangesWarning: "WARNING! There are unsaved changes in TiddlyWiki\n\nChoose OK to save\nChoose CANCEL to discard",
	confirmExit: "--------------------------------\n\nThere are unsaved changes in TiddlyWiki. If you continue you will lose those changes\n\n--------------------------------",
	saveInstructions: "SaveChanges",
	unsupportedTWFormat: "Unsupported TiddlyWiki format '%0'",
	tiddlerSaveError: "Error when saving tiddler '%0'",
	tiddlerLoadError: "Error when loading tiddler '%0'",
	wrongSaveFormat: "Cannot save with storage format '%0'. Using standard format for save.",
	invalidFieldName: "Invalid field name %0",
	fieldCannotBeChanged: "Field '%0' cannot be changed",
	loadingMissingTiddler: "Attempting to retrieve the tiddler '%0' from the '%1' server at:\n\n'%2' in the workspace '%3'",
	upgradeDone: "The upgrade to version %0 is now complete\n\nClick 'OK' to reload the newly upgraded TiddlyWiki",
	invalidCookie: "Invalid cookie '%0'"});

merge(config.messages.messageClose,{
	text: "close",
	tooltip: "close this message area"});

config.messages.backstage = {
	open: {text: "backstage", tooltip: "Open the backstage area to perform authoring and editing tasks"},
	close: {text: "close", tooltip: "Close the backstage area"},
	prompt: "backstage: ",
	decal: {
		edit: {text: "edit", tooltip: "Edit the tiddler '%0'"}
	}
};

config.messages.listView = {
	tiddlerTooltip: "Click for the full text of this tiddler",
	previewUnavailable: "(preview not available)"
};

config.messages.dates.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"];
config.messages.dates.days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
config.messages.dates.shortMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
config.messages.dates.shortDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
// suffixes for dates, eg "1st","2nd","3rd"..."30th","31st"
config.messages.dates.daySuffixes = ["st","nd","rd","th","th","th","th","th","th","th",
		"th","th","th","th","th","th","th","th","th","th",
		"st","nd","rd","th","th","th","th","th","th","th",
		"st"];
config.messages.dates.am = "am";
config.messages.dates.pm = "pm";

merge(config.messages.tiddlerPopup,{
	});

merge(config.views.wikified.tag,{
	labelNoTags: "no tags",
	labelTags: "tags: ",
	openTag: "Open tag '%0'",
	tooltip: "Show tiddlers tagged with '%0'",
	openAllText: "Open all",
	openAllTooltip: "Open all of these tiddlers",
	popupNone: "No other tiddlers tagged with '%0'"});

merge(config.views.wikified,{
	defaultText: "The tiddler '%0' doesn't yet exist. Double-click to create it",
	defaultModifier: "(missing)",
	shadowModifier: "(built-in shadow tiddler)",
	dateFormat: "DD MMM YYYY",
	createdPrompt: "created"});

merge(config.views.editor,{
	tagPrompt: "Type tags separated with spaces, [[use double square brackets]] if necessary, or add existing",
	defaultText: "Type the text for '%0'"});

merge(config.views.editor.tagChooser,{
	text: "tags",
	tooltip: "Choose existing tags to add to this tiddler",
	popupNone: "There are no tags defined",
	tagTooltip: "Add the tag '%0'"});

merge(config.messages,{
	sizeTemplates:
		[
		{unit: 1024*1024*1024, template: "%0\u00a0GB"},
		{unit: 1024*1024, template: "%0\u00a0MB"},
		{unit: 1024, template: "%0\u00a0KB"},
		{unit: 1, template: "%0\u00a0B"}
		]});

merge(config.macros.search,{
	label: "search",
	prompt: "Search this TiddlyWiki",
	placeholder: "",
	accessKey: "F",
	successMsg: "%0 tiddlers found matching %1",
	failureMsg: "No tiddlers found matching %0"});

merge(config.macros.tagging,{
	label: "tagging: ",
	labelNotTag: "not tagging",
	tooltip: "List of tiddlers tagged with '%0'"});

merge(config.macros.timeline,{
	dateFormat: "DD MMM YYYY"});

merge(config.macros.allTags,{
	tooltip: "Show tiddlers tagged with '%0'",
	noTags: "There are no tagged tiddlers"});

config.macros.list.all.prompt = "All tiddlers in alphabetical order";
config.macros.list.missing.prompt = "Tiddlers that have links to them but are not defined";
config.macros.list.orphans.prompt = "Tiddlers that are not linked to from any other tiddlers";
config.macros.list.shadowed.prompt = "Tiddlers shadowed with default contents";
config.macros.list.touched.prompt = "Tiddlers that have been modified locally";

merge(config.macros.closeAll,{
	label: "close all",
	prompt: "Close all displayed tiddlers (except any that are being edited)"});

merge(config.macros.permaview,{
	label: "permaview",
	prompt: "Link to an URL that retrieves all the currently displayed tiddlers"});

merge(config.macros.saveChanges,{
	label: "save changes",
	prompt: "Save all tiddlers to create a new TiddlyWiki",
	accessKey: "S"});

merge(config.macros.newTiddler,{
	label: "new tiddler",
	prompt: "Create a new tiddler",
	title: "New Tiddler",
	accessKey: "N"});

merge(config.macros.newJournal,{
	label: "new journal",
	prompt: "Create a new tiddler from the current date and time",
	accessKey: "J"});

merge(config.macros.options,{
	wizardTitle: "Tweak advanced options",
	step1Title: "These options are saved in cookies in your browser",
	step1Html: "<input type='hidden' name='markList'></input><br><input type='checkbox' checked='false' name='chkUnknown'>Show unknown options</input>",
	unknownDescription: "//(unknown)//",
	listViewTemplate: {
		columns: [
			{name: 'Option', field: 'option', title: "Option", type: 'String'},
			{name: 'Description', field: 'description', title: "Description", type: 'WikiText'},
			{name: 'Name', field: 'name', title: "Name", type: 'String'}
			],
		rowClasses: [
			{className: 'lowlight', field: 'lowlight'}
			]}
	});

merge(config.macros.plugins,{
	wizardTitle: "Manage plugins",
	step1Title: "Currently loaded plugins",
	step1Html: "<input type='hidden' name='markList'></input>", // DO NOT TRANSLATE
	skippedText: "(This plugin has not been executed because it was added since startup)",
	noPluginText: "There are no plugins installed",
	confirmDeleteText: "Are you sure you want to delete these plugins:\n\n%0",
	removeLabel: "remove systemConfig tag",
	removePrompt: "Remove systemConfig tag",
	deleteLabel: "delete",
	deletePrompt: "Delete these tiddlers forever",
	listViewTemplate: {
		columns: [
			{name: 'Selected', field: 'Selected', rowName: 'title', type: 'Selector'},
			{name: 'Tiddler', field: 'tiddler', title: "Tiddler", type: 'Tiddler'},
			{name: 'Description', field: 'Description', title: "Description", type: 'String'},
			{name: 'Version', field: 'Version', title: "Version", type: 'String'},
			{name: 'Size', field: 'size', tiddlerLink: 'size', title: "Size", type: 'Size'},
			{name: 'Forced', field: 'forced', title: "Forced", tag: 'systemConfigForce', type: 'TagCheckbox'},
			{name: 'Disabled', field: 'disabled', title: "Disabled", tag: 'systemConfigDisable', type: 'TagCheckbox'},
			{name: 'Executed', field: 'executed', title: "Loaded", type: 'Boolean', trueText: "Yes", falseText: "No"},
			{name: 'Startup Time', field: 'startupTime', title: "Startup Time", type: 'String'},
			{name: 'Error', field: 'error', title: "Status", type: 'Boolean', trueText: "Error", falseText: "OK"},
			{name: 'Log', field: 'log', title: "Log", type: 'StringList'}
			],
		rowClasses: [
			{className: 'error', field: 'error'},
			{className: 'warning', field: 'warning'}
			]},
	listViewTemplateReadOnly: {
		columns: [
			{name: 'Tiddler', field: 'tiddler', title: "Tiddler", type: 'Tiddler'},
			{name: 'Description', field: 'Description', title: "Description", type: 'String'},
			{name: 'Version', field: 'Version', title: "Version", type: 'String'},
			{name: 'Size', field: 'size', tiddlerLink: 'size', title: "Size", type: 'Size'},
			{name: 'Executed', field: 'executed', title: "Loaded", type: 'Boolean', trueText: "Yes", falseText: "No"},
			{name: 'Startup Time', field: 'startupTime', title: "Startup Time", type: 'String'},
			{name: 'Error', field: 'error', title: "Status", type: 'Boolean', trueText: "Error", falseText: "OK"},
			{name: 'Log', field: 'log', title: "Log", type: 'StringList'}
			],
		rowClasses: [
			{className: 'error', field: 'error'},
			{className: 'warning', field: 'warning'}
			]}
	});

merge(config.macros.toolbar,{
	moreLabel: "more",
	morePrompt: "Show additional commands",
	lessLabel: "less",
	lessPrompt: "Hide additional commands",
	separator: "|"
	});

merge(config.macros.refreshDisplay,{
	label: "refresh",
	prompt: "Redraw the entire TiddlyWiki display"
	});

merge(config.macros.importTiddlers,{
	readOnlyWarning: "You cannot import into a read-only TiddlyWiki file. Try opening it from a file:// URL",
	wizardTitle: "Import tiddlers from another file or server",
	step1Title: "Step 1: Locate the server or TiddlyWiki file",
	step1Html: "Specify the type of the server: <select name='selTypes'><option value=''>Choose...</option></select><br>Enter the URL or pathname here: <input type='text' size=50 name='txtPath'><br>...or browse for a file: <input type='file' size=50 name='txtBrowse'><br><hr>...or select a pre-defined feed: <select name='selFeeds'><option value=''>Choose...</option></select>",
	openLabel: "open",
	openPrompt: "Open the connection to this file or server",
	statusOpenHost: "Opening the host",
	statusGetWorkspaceList: "Getting the list of available workspaces",
	step2Title: "Step 2: Choose the workspace",
	step2Html: "Enter a workspace name: <input type='text' size=50 name='txtWorkspace'><br>...or select a workspace: <select name='selWorkspace'><option value=''>Choose...</option></select>",
	cancelLabel: "cancel",
	cancelPrompt: "Cancel this import",
	statusOpenWorkspace: "Opening the workspace",
	statusGetTiddlerList: "Getting the list of available tiddlers",
	errorGettingTiddlerList: "Error getting list of tiddlers, click Cancel to try again",
	errorGettingTiddlerListHttp404: "Error retrieving tiddlers from url, please ensure the url exists. Click Cancel to try again.",
	errorGettingTiddlerListHttp: "Error retrieving tiddlers from url, please ensure this url exists and is <a href='http://enable-cors.org/'>CORS</a> enabled",
	errorGettingTiddlerListFile: "Error retrieving tiddlers from local file, please make sure the file is in the same directory as your TiddlyWiki. Click Cancel to try again.",
	step3Title: "Step 3: Choose the tiddlers to import",
	step3Html: "<input type='hidden' name='markList'></input><br><input type='checkbox' checked='true' name='chkSync'>Keep these tiddlers linked to this server so that you can synchronise subsequent changes</input><br><input type='checkbox' name='chkSave'>Save the details of this server in a 'systemServer' tiddler called:</input> <input type='text' size=25 name='txtSaveTiddler'>",
	importLabel: "import",
	importPrompt: "Import these tiddlers",
	confirmOverwriteText: "Are you sure you want to overwrite these tiddlers:\n\n%0",
	step4Title: "Step 4: Importing %0 tiddler(s)",
	step4Html: "<input type='hidden' name='markReport'></input>", // DO NOT TRANSLATE
	doneLabel: "done",
	donePrompt: "Close this wizard",
	statusDoingImport: "Importing tiddlers",
	statusDoneImport: "All tiddlers imported",
	systemServerNamePattern: "%2 on %1",
	systemServerNamePatternNoWorkspace: "%1",
	confirmOverwriteSaveTiddler: "The tiddler '%0' already exists. Click 'OK' to overwrite it with the details of this server, or 'Cancel' to leave it unchanged",
	serverSaveTemplate: "|''Type:''|%0|\n|''URL:''|%1|\n|''Workspace:''|%2|\n\nThis tiddler was automatically created to record the details of this server",
	serverSaveModifier: "(System)",
	listViewTemplate: {
		columns: [
			{name: 'Selected', field: 'Selected', rowName: 'title', type: 'Selector'},
			{name: 'Tiddler', field: 'tiddler', title: "Tiddler", type: 'Tiddler'},
			{name: 'Size', field: 'size', tiddlerLink: 'size', title: "Size", type: 'Size'},
			{name: 'Tags', field: 'tags', title: "Tags", type: 'Tags'}
			],
		rowClasses: [
			]}
	});

merge(config.macros.upgrade,{
	wizardTitle: "Upgrade TiddlyWiki core code",
	step1Title: "Update or repair this TiddlyWiki to the latest release",
	step1Html: "You are about to upgrade to the latest release of the TiddlyWiki core code (from <a href='%0' class='externalLink' target='_blank'>%1</a>). Your content will be preserved across the upgrade.<br><br>Note that core upgrades have been known to interfere with older plugins. If you run into problems with the upgraded file, see <a href='http://www.tiddlywiki.org/wiki/CoreUpgrades' class='externalLink' target='_blank'>http://www.tiddlywiki.org/wiki/CoreUpgrades</a>",
	errorCantUpgrade: "Unable to upgrade this TiddlyWiki. You can only perform upgrades on TiddlyWiki files stored locally",
	errorNotSaved: "You must save changes before you can perform an upgrade",
	step2Title: "Confirm the upgrade details",
	step2Html_downgrade: "You are about to downgrade to TiddlyWiki version %0 from %1.<br><br>Downgrading to an earlier version of the core code is not recommended",
	step2Html_restore: "This TiddlyWiki appears to be already using the latest version of the core code (%0).<br><br>You can continue to upgrade anyway to ensure that the core code hasn't been corrupted or damaged",
	step2Html_upgrade: "You are about to upgrade to TiddlyWiki version %0 from %1",
	upgradeLabel: "upgrade",
	upgradePrompt: "Prepare for the upgrade process",
	statusPreparingBackup: "Preparing backup",
	statusSavingBackup: "Saving backup file",
	errorSavingBackup: "There was a problem saving the backup file",
	statusLoadingCore: "Loading core code",
	errorLoadingCore: "Error loading the core code",
	errorCoreFormat: "Error with the new core code",
	statusSavingCore: "Saving the new core code",
	statusReloadingCore: "Reloading the new core code",
	startLabel: "start",
	startPrompt: "Start the upgrade process",
	cancelLabel: "cancel",
	cancelPrompt: "Cancel the upgrade process",
	step3Title: "Upgrade cancelled",
	step3Html: "You have cancelled the upgrade process"
	});

merge(config.macros.annotations,{
	});

merge(config.commands.closeTiddler,{
	text: "close",
	tooltip: "Close this tiddler"});

merge(config.commands.closeOthers,{
	text: "close others",
	tooltip: "Close all other tiddlers"});

merge(config.commands.editTiddler,{
	text: "edit",
	tooltip: "Edit this tiddler",
	readOnlyText: "view",
	readOnlyTooltip: "View the source of this tiddler"});

merge(config.commands.saveTiddler,{
	text: "done",
	tooltip: "Save changes to this tiddler"});

merge(config.commands.cancelTiddler,{
	text: "cancel",
	tooltip: "Undo changes to this tiddler",
	warning: "Are you sure you want to abandon your changes to '%0'?",
	readOnlyText: "done",
	readOnlyTooltip: "View this tiddler normally"});

merge(config.commands.deleteTiddler,{
	text: "delete",
	tooltip: "Delete this tiddler",
	warning: "Are you sure you want to delete '%0'?"});

merge(config.commands.permalink,{
	text: "permalink",
	tooltip: "Permalink for this tiddler"});

merge(config.commands.references,{
	text: "references",
	tooltip: "Show tiddlers that link to this one",
	popupNone: "No references"});

merge(config.commands.jump,{
	text: "jump",
	tooltip: "Jump to another open tiddler"});

merge(config.commands.fields,{
	text: "fields",
	tooltip: "Show the extended fields of this tiddler",
	emptyText: "There are no extended fields for this tiddler",
	listViewTemplate: {
		columns: [
			{name: 'Field', field: 'field', title: "Field", type: 'String'},
			{name: 'Value', field: 'value', title: "Value", type: 'String'}
			],
		rowClasses: [
			],
		buttons: [
			]}});

merge(config.shadowTiddlers,{
	DefaultTiddlers: "[[GettingStarted]]",
	MainMenu: "[[GettingStarted]]",
	SiteTitle: "My TiddlyWiki",
	SiteSubtitle: "a reusable non-linear personal web notebook",
	SiteUrl: "",
	SideBarOptions: '<<search>><<closeAll>><<permaview>><<newTiddler>><<newJournal "DD MMM YYYY" "journal">><<saveChanges>><<slider chkSliderOptionsPanel OptionsPanel "options \u00bb" "Change TiddlyWiki advanced options">>',
	SideBarTabs: '<<tabs txtMainTab "Timeline" "Timeline" TabTimeline "All" "All tiddlers" TabAll "Tags" "All tags" TabTags "More" "More lists" TabMore>>',
	TabMore: '<<tabs txtMoreTab "Missing" "Missing tiddlers" TabMoreMissing "Orphans" "Orphaned tiddlers" TabMoreOrphans "Shadowed" "Shadowed tiddlers" TabMoreShadowed>>'
	});

merge(config.annotations,{
	AdvancedOptions: "This shadow tiddler provides access to several advanced options",
	ColorPalette: "These values in this shadow tiddler determine the colour scheme of the ~TiddlyWiki user interface",
	DefaultTiddlers: "The tiddlers listed in this shadow tiddler will be automatically displayed when ~TiddlyWiki starts up",
	EditTemplate: "The HTML template in this shadow tiddler determines how tiddlers look while they are being edited",
	GettingStarted: "This shadow tiddler provides basic usage instructions",
	ImportTiddlers: "This shadow tiddler provides access to importing tiddlers",
	MainMenu: "This shadow tiddler is used as the contents of the main menu in the left-hand column of the screen",
	MarkupPreHead: "This tiddler is inserted at the top of the <head> section of the TiddlyWiki HTML file",
	MarkupPostHead: "This tiddler is inserted at the bottom of the <head> section of the TiddlyWiki HTML file",
	MarkupPreBody: "This tiddler is inserted at the top of the <body> section of the TiddlyWiki HTML file",
	MarkupPostBody: "This tiddler is inserted at the end of the <body> section of the TiddlyWiki HTML file immediately after the script block",
	OptionsPanel: "This shadow tiddler is used as the contents of the options panel slider in the right-hand sidebar",
	PageTemplate: "The HTML template in this shadow tiddler determines the overall ~TiddlyWiki layout",
	PluginManager: "This shadow tiddler provides access to the plugin manager",
	SideBarOptions: "This shadow tiddler is used as the contents of the option panel in the right-hand sidebar",
	SideBarTabs: "This shadow tiddler is used as the contents of the tabs panel in the right-hand sidebar",
	SiteSubtitle: "This shadow tiddler is used as the second part of the page title",
	SiteTitle: "This shadow tiddler is used as the first part of the page title",
	SiteUrl: "This shadow tiddler should be set to the full target URL for publication",
	StyleSheetColors: "This shadow tiddler contains CSS definitions related to the color of page elements. ''DO NOT EDIT THIS TIDDLER'', instead make your changes in the StyleSheet shadow tiddler",
	StyleSheet: "This tiddler can contain custom CSS definitions",
	StyleSheetLayout: "This shadow tiddler contains CSS definitions related to the layout of page elements. ''DO NOT EDIT THIS TIDDLER'', instead make your changes in the StyleSheet shadow tiddler",
	StyleSheetLocale: "This shadow tiddler contains CSS definitions related to the translation locale",
	StyleSheetPrint: "This shadow tiddler contains CSS definitions for printing",
	SystemSettings: "This tiddler is used to store configuration options for this TiddlyWiki document",
	TabAll: "This shadow tiddler contains the contents of the 'All' tab in the right-hand sidebar",
	TabMore: "This shadow tiddler contains the contents of the 'More' tab in the right-hand sidebar",
	TabMoreMissing: "This shadow tiddler contains the contents of the 'Missing' tab in the right-hand sidebar",
	TabMoreOrphans: "This shadow tiddler contains the contents of the 'Orphans' tab in the right-hand sidebar",
	TabMoreShadowed: "This shadow tiddler contains the contents of the 'Shadowed' tab in the right-hand sidebar",
	TabTags: "This shadow tiddler contains the contents of the 'Tags' tab in the right-hand sidebar",
	TabTimeline: "This shadow tiddler contains the contents of the 'Timeline' tab in the right-hand sidebar",
	ToolbarCommands: "This shadow tiddler determines which commands are shown in tiddler toolbars",
	ViewTemplate: "The HTML template in this shadow tiddler determines how tiddlers look"
	});
//--
//-- Paramifiers
//--

function getParameters()
{
	var p = null;
	if(window.location.hash) {
		p = decodeURIComponent(window.location.hash.substr(1));
		if(config.browser.firefoxDate != null && config.browser.firefoxDate[1] < "20051111")
			p = convertUTF8ToUnicode(p);
	}
	return p;
}

function invokeParamifier(params,handler)
{
	if(!params || params.length == undefined || params.length <= 1)
		return;
	var i;
	for(i=1; i<params.length; i++) {
		var p = config.paramifiers[params[i].name];
		if(p && p[handler] instanceof Function)
			p[handler](params[i].value);
		else {
			var h = config.optionHandlers[params[i].name.substr(0,3)];
			if(h && h.set instanceof Function)
				h.set(params[i].name,params[i].value);
		}
	}
}

config.paramifiers = {};

config.paramifiers.start = {
	oninit: function(v) {
		safeMode = v.toLowerCase() == "safe";
	}
};

config.paramifiers.open = {
	onstart: function(v) {
		if(!readOnly || store.tiddlerExists(v) || store.isShadowTiddler(v))
			story.displayTiddler("bottom",v,null,false,null);
	}
};

config.paramifiers.story = {
	onstart: function(v) {
		var list = store.getTiddlerText(v,"").parseParams("open",null,false);
		invokeParamifier(list,"onstart");
	}
};

config.paramifiers.search = {
	onstart: function(v) {
		story.search(v,false,false);
	}
};

config.paramifiers.searchRegExp = {
	onstart: function(v) {
		story.prototype.search(v,false,true);
	}
};

config.paramifiers.tag = {
	onstart: function(v) {
		story.displayTiddlers(null,store.filterTiddlers("[tag["+v+"]]"),null,false,null);
	}
};

config.paramifiers.newTiddler = {
	onstart: function(v) {
		var args = v.parseParams("anon", null, null)[0];
		var title = args.title ? args.title[0] : v;
		var customFields = args.fields ? args.fields[0] : null;
		if(!readOnly) {
			story.displayTiddler(null,title,DEFAULT_EDIT_TEMPLATE,false,null,customFields);
			story.focusTiddler(title,"text");
			var i,tags = args.tag || [];
			for(i=0;i<tags.length;i++) {
				story.setTiddlerTag(title,tags[i],+1);
			}
		}
	}
};

config.paramifiers.newJournal = {
	onstart: function(v) {
		if(!readOnly) {
			var now = new Date();
			var title = now.formatString(v.trim());
			story.displayTiddler(null,title,DEFAULT_EDIT_TEMPLATE);
			story.focusTiddler(title,"text");
		}
	}
};

config.paramifiers.readOnly = {
	onconfig: function(v) {
		var p = v.toLowerCase();
		readOnly = p == "yes" ? true : (p == "no" ? false : readOnly);
	}
};

config.paramifiers.theme = {
	onconfig: function(v) {
		story.switchTheme(v);
	}
};

config.paramifiers.upgrade = {
	onstart: function(v) {
		upgradeFrom(v);
	}
};

config.paramifiers.recent= {
	onstart: function(v) {
		var titles=[];
		var i,tiddlers=store.getTiddlers("modified","excludeLists").reverse();
		for(i=0; i<v && i<tiddlers.length; i++)
			titles.push(tiddlers[i].title);
		story.displayTiddlers(null,titles);
	}
};

config.paramifiers.filter = {
	onstart: function(v) {
		story.displayTiddlers(null,store.filterTiddlers(v),null,false);
	}
};

//--
//-- Formatter helpers
//--

function Formatter(formatters)
{
	var n;
	this.formatters = [];
	var pattern = [];
	for(n=0; n<formatters.length; n++) {
		pattern.push("(" + formatters[n].match + ")");
		this.formatters.push(formatters[n]);
	}
	this.formatterRegExp = new RegExp(pattern.join("|"),"mg");
}

config.formatterHelpers = {

	createElementAndWikify: function(w)
	{
		w.subWikifyTerm(createTiddlyElement(w.output,this.element),this.termRegExp);
	},

	inlineCssHelper: function(w)
	{
		var styles = [];
		config.textPrimitives.cssLookaheadRegExp.lastIndex = w.nextMatch;
		var lookaheadMatch = config.textPrimitives.cssLookaheadRegExp.exec(w.source);
		while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {
			var s,v;
			if(lookaheadMatch[1]) {
				s = lookaheadMatch[1].unDash();
				v = lookaheadMatch[2];
			} else {
				s = lookaheadMatch[3].unDash();
				v = lookaheadMatch[4];
			}
			if(s=="bgcolor")
				s = "backgroundColor";
			if(s=="float")
				s = "cssFloat";
			styles.push({style: s, value: v});
			w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
			config.textPrimitives.cssLookaheadRegExp.lastIndex = w.nextMatch;
			lookaheadMatch = config.textPrimitives.cssLookaheadRegExp.exec(w.source);
		}
		return styles;
	},

	applyCssHelper: function(e,styles)
	{
		var t;
		for(t=0; t< styles.length; t++) {
			try {
				e.style[styles[t].style] = styles[t].value;
			} catch (ex) {
			}
		}
	},

	enclosedTextHelper: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var text = lookaheadMatch[1];
			if(config.browser.isIE)
				text = text.replace(/\n/g,"\r");
			createTiddlyElement(w.output,this.element,null,null,text);
			w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
		}
	},

	isExternalLink: function(link)
	{
		if(store.tiddlerExists(link) || store.isShadowTiddler(link)) {
			return false;
		}
		var urlRegExp = new RegExp(config.textPrimitives.urlPattern,"mg");
		if(urlRegExp.exec(link)) {
			return true;
		}
		if(link.indexOf(".")!=-1 || link.indexOf("\\")!=-1 || link.indexOf("/")!=-1 || link.indexOf("#")!=-1) {
			return true;
		}
		return false;
	}

};

//--
//-- Standard formatters
//--

config.formatters = [
{
	name: "table",
	match: "^\\|(?:[^\\n]*)\\|(?:[fhck]?)$",
	lookaheadRegExp: /^\|([^\n]*)\|([fhck]?)$/mg,
	rowTermRegExp: /(\|(?:[fhck]?)$\n?)/mg,
	cellRegExp: /(?:\|([^\n\|]*)\|)|(\|[fhck]?$\n?)/mg,
	cellTermRegExp: /((?:\x20*)\|)/mg,
	rowTypes: {"c":"caption", "h":"thead", "":"tbody", "f":"tfoot"},
	handler: function(w)
	{
		var table = createTiddlyElement(w.output,"table",null,"twtable");
		var prevColumns = [];
		var currRowType = null;
		var rowContainer;
		var rowCount = 0;
		var onmouseover = function() {jQuery(this).addClass("hoverRow");};
		var onmouseout = function() {jQuery(this).removeClass("hoverRow");};
		w.nextMatch = w.matchStart;
		this.lookaheadRegExp.lastIndex = w.nextMatch;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {
			var nextRowType = lookaheadMatch[2];
			if(nextRowType == "k") {
				table.className = lookaheadMatch[1];
				w.nextMatch += lookaheadMatch[0].length+1;
			} else {
				if(nextRowType != currRowType) {
					rowContainer = createTiddlyElement(table,this.rowTypes[nextRowType]);
					currRowType = nextRowType;
				}
				if(currRowType == "c") {
					// Caption
					w.nextMatch++;
					if(rowContainer != table.firstChild)
						table.insertBefore(rowContainer,table.firstChild);
					rowContainer.setAttribute("align",rowCount == 0?"top":"bottom");
					w.subWikifyTerm(rowContainer,this.rowTermRegExp);
				} else {
					var theRow = createTiddlyElement(rowContainer,"tr",null,rowCount%2?"oddRow":"evenRow");
					theRow.onmouseover = onmouseover;
					theRow.onmouseout = onmouseout;
					this.rowHandler(w,theRow,prevColumns);
					rowCount++;
				}
			}
			this.lookaheadRegExp.lastIndex = w.nextMatch;
			lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		}
	},
	rowHandler: function(w,e,prevColumns)
	{
		var col = 0;
		var colSpanCount = 1;
		var prevCell = null;
		this.cellRegExp.lastIndex = w.nextMatch;
		var cellMatch = this.cellRegExp.exec(w.source);
		while(cellMatch && cellMatch.index == w.nextMatch) {
			if(cellMatch[1] == "~") {
				// Rowspan
				var last = prevColumns[col];
				if(last) {
					last.rowSpanCount++;
					last.element.setAttribute("rowspan",last.rowSpanCount);
					last.element.setAttribute("rowSpan",last.rowSpanCount); // Needed for IE
					last.element.valign = "center";
					if(colSpanCount > 1) {
						last.element.setAttribute("colspan",colSpanCount);
						last.element.setAttribute("colSpan",colSpanCount); // Needed for IE
						colSpanCount = 1;
					}
				}
				w.nextMatch = this.cellRegExp.lastIndex-1;
			} else if(cellMatch[1] == ">") {
				// Colspan
				colSpanCount++;
				w.nextMatch = this.cellRegExp.lastIndex-1;
			} else if(cellMatch[2]) {
				// End of row
				if(prevCell && colSpanCount > 1) {
					prevCell.setAttribute("colspan",colSpanCount);
					prevCell.setAttribute("colSpan",colSpanCount); // Needed for IE
				}
				w.nextMatch = this.cellRegExp.lastIndex;
				break;
			} else {
				// Cell
				w.nextMatch++;
				var styles = config.formatterHelpers.inlineCssHelper(w);
				var spaceLeft = false;
				var chr = w.source.substr(w.nextMatch,1);
				while(chr == " ") {
					spaceLeft = true;
					w.nextMatch++;
					chr = w.source.substr(w.nextMatch,1);
				}
				var cell;
				if(chr == "!") {
					cell = createTiddlyElement(e,"th");
					w.nextMatch++;
				} else {
					cell = createTiddlyElement(e,"td");
				}
				prevCell = cell;
				prevColumns[col] = {rowSpanCount:1,element:cell};
				if(colSpanCount > 1) {
					cell.setAttribute("colspan",colSpanCount);
					cell.setAttribute("colSpan",colSpanCount); // Needed for IE
					colSpanCount = 1;
				}
				config.formatterHelpers.applyCssHelper(cell,styles);
				w.subWikifyTerm(cell,this.cellTermRegExp);
				if(w.matchText.substr(w.matchText.length-2,1) == " ") // spaceRight
					cell.align = spaceLeft ? "center" : "left";
				else if(spaceLeft)
					cell.align = "right";
				w.nextMatch--;
			}
			col++;
			this.cellRegExp.lastIndex = w.nextMatch;
			cellMatch = this.cellRegExp.exec(w.source);
		}
	}
},

{
	name: "heading",
	match: "^!{1,6}",
	termRegExp: /(\n)/mg,
	handler: function(w)
	{
		w.subWikifyTerm(createTiddlyElement(w.output,"h" + w.matchLength),this.termRegExp);
	}
},

{
	name: "list",
	match: "^(?:[\\*#;:]+)",
	lookaheadRegExp: /^(?:(?:(\*)|(#)|(;)|(:))+)/mg,
	termRegExp: /(\n)/mg,
	handler: function(w)
	{
		var stack = [w.output];
		var currLevel = 0, currType = null;
		var listLevel, listType, itemType, baseType;
		w.nextMatch = w.matchStart;
		this.lookaheadRegExp.lastIndex = w.nextMatch;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {
			if(lookaheadMatch[1]) {
				listType = "ul";
				itemType = "li";
			} else if(lookaheadMatch[2]) {
				listType = "ol";
				itemType = "li";
			} else if(lookaheadMatch[3]) {
				listType = "dl";
				itemType = "dt";
			} else if(lookaheadMatch[4]) {
				listType = "dl";
				itemType = "dd";
			}
			if(!baseType)
				baseType = listType;
			listLevel = lookaheadMatch[0].length;
			w.nextMatch += lookaheadMatch[0].length;
			var t;
			if(listLevel > currLevel) {
				for(t=currLevel; t<listLevel; t++) {
					var target = (currLevel == 0) ? stack[stack.length-1] : stack[stack.length-1].lastChild;
					stack.push(createTiddlyElement(target,listType));
				}
			} else if(listType!=baseType && listLevel==1) {
				w.nextMatch -= lookaheadMatch[0].length;
				return;
			} else if(listLevel < currLevel) {
				for(t=currLevel; t>listLevel; t--)
					stack.pop();
			} else if(listLevel == currLevel && listType != currType) {
				stack.pop();
				stack.push(createTiddlyElement(stack[stack.length-1].lastChild,listType));
			}
			currLevel = listLevel;
			currType = listType;
			var e = createTiddlyElement(stack[stack.length-1],itemType);
			w.subWikifyTerm(e,this.termRegExp);
			this.lookaheadRegExp.lastIndex = w.nextMatch;
			lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		}
	}
},

{
	name: "quoteByBlock",
	match: "^<<<\\n",
	termRegExp: /(^<<<(\n|$))/mg,
	element: "blockquote",
	handler: config.formatterHelpers.createElementAndWikify
},

{
	name: "quoteByLine",
	match: "^>+",
	lookaheadRegExp: /^>+/mg,
	termRegExp: /(\n)/mg,
	element: "blockquote",
	handler: function(w)
	{
		var stack = [w.output];
		var currLevel = 0;
		var newLevel = w.matchLength;
		var t,matched;
		do {
			if(newLevel > currLevel) {
				for(t=currLevel; t<newLevel; t++)
					stack.push(createTiddlyElement(stack[stack.length-1],this.element));
			} else if(newLevel < currLevel) {
				for(t=currLevel; t>newLevel; t--)
					stack.pop();
			}
			currLevel = newLevel;
			w.subWikifyTerm(stack[stack.length-1],this.termRegExp);
			createTiddlyElement(stack[stack.length-1],"br");
			this.lookaheadRegExp.lastIndex = w.nextMatch;
			var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
			matched = lookaheadMatch && lookaheadMatch.index == w.nextMatch;
			if(matched) {
				newLevel = lookaheadMatch[0].length;
				w.nextMatch += lookaheadMatch[0].length;
			}
		} while(matched);
	}
},

{
	name: "rule",
	match: "^----+$\\n?|<hr ?/?>\\n?",
	handler: function(w)
	{
		createTiddlyElement(w.output,"hr");
	}
},

{
	name: "monospacedByLine",
	match: "^(?:/\\*\\{\\{\\{\\*/|\\{\\{\\{|//\\{\\{\\{|<!--\\{\\{\\{-->)\\n",
	element: "pre",
	handler: function(w)
	{
		switch(w.matchText) {
		case "/*{{{*/\n": // CSS
			this.lookaheadRegExp = /\/\*\{\{\{\*\/\n*((?:^[^\n]*\n)+?)(\n*^\f*\/\*\}\}\}\*\/$\n?)/mg;
			break;
		case "{{{\n": // monospaced block
			this.lookaheadRegExp = /^\{\{\{\n((?:^[^\n]*\n)+?)(^\f*\}\}\}$\n?)/mg;
			break;
		case "//{{{\n": // plugin
			this.lookaheadRegExp = /^\/\/\{\{\{\n\n*((?:^[^\n]*\n)+?)(\n*^\f*\/\/\}\}\}$\n?)/mg;
			break;
		case "<!--{{{-->\n": //template
			this.lookaheadRegExp = /<!--\{\{\{-->\n*((?:^[^\n]*\n)+?)(\n*^\f*<!--\}\}\}-->$\n?)/mg;
			break;
		default:
			break;
		}
		config.formatterHelpers.enclosedTextHelper.call(this,w);
	}
},

{
	name: "wikifyComment",
	match: "^(?:/\\*\\*\\*|<!---)\\n",
	handler: function(w)
	{
		var termRegExp = (w.matchText == "/***\n") ? (/(^\*\*\*\/\n)/mg) : (/(^--->\n)/mg);
		w.subWikifyTerm(w.output,termRegExp);
	}
},

{
	name: "macro",
	match: "<<",
	lookaheadRegExp: /<<([^>\s]+)(?:\s*)((?:[^>]|(?:>(?!>)))*)>>/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart && lookaheadMatch[1]) {
			w.nextMatch = this.lookaheadRegExp.lastIndex;
			invokeMacro(w.output,lookaheadMatch[1],lookaheadMatch[2],w,w.tiddler);
		}
	}
},

{
	name: "prettyLink",
	match: "\\[\\[",
	lookaheadRegExp: /\[\[(.*?)(?:\|(~)?(.*?))?\]\]/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var e;
			var text = lookaheadMatch[1];
			if(lookaheadMatch[3]) {
				// Pretty bracketted link
				var link = lookaheadMatch[3];
				e = (!lookaheadMatch[2] && config.formatterHelpers.isExternalLink(link)) ?
						createExternalLink(w.output,link) : createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);
			} else {
				// Simple bracketted link
				e = createTiddlyLink(w.output,text,false,null,w.isStatic,w.tiddler);
			}
			createTiddlyText(e,text);
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
},

{
	name: "wikiLink",
	match: config.textPrimitives.unWikiLink+"?"+config.textPrimitives.wikiLink,
	handler: function(w)
	{
		if(w.matchText.substr(0,1) == config.textPrimitives.unWikiLink) {
			w.outputText(w.output,w.matchStart+1,w.nextMatch);
			return;
		}
		if(w.matchStart > 0) {
			var preRegExp = new RegExp(config.textPrimitives.anyLetterStrict,"mg");
			preRegExp.lastIndex = w.matchStart-1;
			var preMatch = preRegExp.exec(w.source);
			if(preMatch.index == w.matchStart-1) {
				w.outputText(w.output,w.matchStart,w.nextMatch);
				return;
			}
		}
		if(w.autoLinkWikiWords || store.isShadowTiddler(w.matchText)) {
			var link = createTiddlyLink(w.output,w.matchText,false,null,w.isStatic,w.tiddler);
			w.outputText(link,w.matchStart,w.nextMatch);
		} else {
			w.outputText(w.output,w.matchStart,w.nextMatch);
		}
	}
},

{
	name: "urlLink",
	match: config.textPrimitives.urlPattern,
	handler: function(w)
	{
		w.outputText(createExternalLink(w.output,w.matchText),w.matchStart,w.nextMatch);
	}
},

{
	name: "image",
	match: "\\[[<>]?[Ii][Mm][Gg]\\[",
	lookaheadRegExp: /\[([<]?)(>?)[Ii][Mm][Gg]\[(?:([^\|\]]+)\|)?([^\[\]\|]+)\](?:\[([^\]]*)\])?\]/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var e = w.output;
			if(lookaheadMatch[5]) {
				var link = lookaheadMatch[5];
				e = config.formatterHelpers.isExternalLink(link) ? createExternalLink(w.output,link) : createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);
				jQuery(e).addClass("imageLink");
			}
			var img = createTiddlyElement(e,"img");
			if(lookaheadMatch[1])
				img.align = "left";
			else if(lookaheadMatch[2])
				img.align = "right";
			if(lookaheadMatch[3]) {
				img.title = lookaheadMatch[3];
				img.setAttribute("alt",lookaheadMatch[3]);
			}
			img.src = lookaheadMatch[4];
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
},

{
	name: "html",
	match: "<[Hh][Tt][Mm][Ll]>",
	lookaheadRegExp: /<[Hh][Tt][Mm][Ll]>((?:.|\n)*?)<\/[Hh][Tt][Mm][Ll]>/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			createTiddlyElement(w.output,"span").innerHTML = lookaheadMatch[1];
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
},

{
	name: "commentByBlock",
	match: "/%",
	lookaheadRegExp: /\/%((?:.|\n)*?)%\//mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart)
			w.nextMatch = this.lookaheadRegExp.lastIndex;
	}
},

{
	name: "characterFormat",
	match: "''|//|__|\\^\\^|~~|--(?!\\s|$)|\\{\\{\\{",
	handler: function(w)
	{
		switch(w.matchText) {
		case "''":
			w.subWikifyTerm(w.output.appendChild(document.createElement("strong")),/('')/mg);
			break;
		case "//":
			w.subWikifyTerm(createTiddlyElement(w.output,"em"),/(\/\/)/mg);
			break;
		case "__":
			w.subWikifyTerm(createTiddlyElement(w.output,"u"),/(__)/mg);
			break;
		case "^^":
			w.subWikifyTerm(createTiddlyElement(w.output,"sup"),/(\^\^)/mg);
			break;
		case "~~":
			w.subWikifyTerm(createTiddlyElement(w.output,"sub"),/(~~)/mg);
			break;
		case "--":
			w.subWikifyTerm(createTiddlyElement(w.output,"strike"),/(--)/mg);
			break;
		case "{{{":
			var lookaheadRegExp = /\{\{\{((?:.|\n)*?)\}\}\}/mg;
			lookaheadRegExp.lastIndex = w.matchStart;
			var lookaheadMatch = lookaheadRegExp.exec(w.source);
			if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
				createTiddlyElement(w.output,"code",null,null,lookaheadMatch[1]);
				w.nextMatch = lookaheadRegExp.lastIndex;
			}
			break;
		}
	}
},

{
	name: "customFormat",
	match: "@@|\\{\\{",
	handler: function(w)
	{
		switch(w.matchText) {
		case "@@":
			var e = createTiddlyElement(w.output,"span");
			var styles = config.formatterHelpers.inlineCssHelper(w);
			if(styles.length == 0)
				e.className = "marked";
			else
				config.formatterHelpers.applyCssHelper(e,styles);
			w.subWikifyTerm(e,/(@@)/mg);
			break;
		case "{{":
			var lookaheadRegExp = /\{\{[\s]*([\w]+[\s\w]*)[\s]*\{(\n?)/mg;
			lookaheadRegExp.lastIndex = w.matchStart;
			var lookaheadMatch = lookaheadRegExp.exec(w.source);
			if(lookaheadMatch) {
				w.nextMatch = lookaheadRegExp.lastIndex;
				e = createTiddlyElement(w.output,lookaheadMatch[2] == "\n" ? "div" : "span",null,lookaheadMatch[1]);
				w.subWikifyTerm(e,/(\}\}\})/mg);
			}
			break;
		}
	}
},

{
	name: "mdash",
	match: "--",
	handler: function(w)
	{
		createTiddlyElement(w.output,"span").innerHTML = "&mdash;";
	}
},

{
	name: "lineBreak",
	match: "\\n|<br ?/?>",
	handler: function(w)
	{
		createTiddlyElement(w.output,"br");
	}
},

{
	name: "rawText",
	match: "\"{3}|<nowiki>",
	lookaheadRegExp: /(?:\"{3}|<nowiki>)((?:.|\n)*?)(?:\"{3}|<\/nowiki>)/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			createTiddlyElement(w.output,"span",null,null,lookaheadMatch[1]);
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
},

{
	name: "htmlEntitiesEncoding",
	match: "(?:(?:&#?[a-zA-Z0-9]{2,8};|.)(?:&#?(?:x0*(?:3[0-6][0-9a-fA-F]|1D[c-fC-F][0-9a-fA-F]|20[d-fD-F][0-9a-fA-F]|FE2[0-9a-fA-F])|0*(?:76[89]|7[7-9][0-9]|8[0-7][0-9]|761[6-9]|76[2-7][0-9]|84[0-3][0-9]|844[0-7]|6505[6-9]|6506[0-9]|6507[0-1]));)+|&#?[a-zA-Z0-9]{2,8};)",
	handler: function(w)
	{
		createTiddlyElement(w.output,"span").innerHTML = w.matchText;
	}
}

];

//--
//-- Wikifier
//--

function getParser(tiddler,format)
{
	if(tiddler) {
		if(!format)
			format = tiddler.fields["wikiformat"];
		var i;
		if(format) {
			for(i in config.parsers) {
				if(format == config.parsers[i].format)
					return config.parsers[i];
			}
		} else {
			for(i in config.parsers) {
				if(tiddler.isTagged(config.parsers[i].formatTag))
					return config.parsers[i];
			}
		}
	}
	return formatter;
}

function Wikifier(source,formatter,highlightRegExp,tiddler)
{
	this.source = source;
	this.output = null;
	this.formatter = formatter;
	this.nextMatch = 0;
	this.autoLinkWikiWords = tiddler && tiddler.autoLinkWikiWords() == false ? false : true;
	this.highlightRegExp = highlightRegExp;
	this.highlightMatch = null;
	this.isStatic = false;
	if(highlightRegExp) {
		highlightRegExp.lastIndex = 0;
		this.highlightMatch = highlightRegExp.exec(source);
	}
	this.tiddler = tiddler;
}

Wikifier.prototype.wikifyPlain = function()
{
	var e = createTiddlyElement(document.body,"div");
	e.style.display = "none";
	this.subWikify(e);
	var text = jQuery(e).text();
	jQuery(e).remove();
	return text;
};

Wikifier.prototype.subWikify = function(output,terminator)
{
	try {
		if(terminator)
			this.subWikifyTerm(output,new RegExp("(" + terminator + ")","mg"));
		else
			this.subWikifyUnterm(output);
	} catch(ex) {
		showException(ex);
	}
};

Wikifier.prototype.subWikifyUnterm = function(output)
{
	var oldOutput = this.output;
	this.output = output;
	this.formatter.formatterRegExp.lastIndex = this.nextMatch;
	var formatterMatch = this.formatter.formatterRegExp.exec(this.source);
	while(formatterMatch) {
		// Output any text before the match
		if(formatterMatch.index > this.nextMatch)
			this.outputText(this.output,this.nextMatch,formatterMatch.index);
		// Set the match parameters for the handler
		this.matchStart = formatterMatch.index;
		this.matchLength = formatterMatch[0].length;
		this.matchText = formatterMatch[0];
		this.nextMatch = this.formatter.formatterRegExp.lastIndex;
		var t;
		for(t=1; t<formatterMatch.length; t++) {
			if(formatterMatch[t]) {
				this.formatter.formatters[t-1].handler(this);
				this.formatter.formatterRegExp.lastIndex = this.nextMatch;
				break;
			}
		}
		formatterMatch = this.formatter.formatterRegExp.exec(this.source);
	}
	if(this.nextMatch < this.source.length) {
		this.outputText(this.output,this.nextMatch,this.source.length);
		this.nextMatch = this.source.length;
	}
	this.output = oldOutput;
};

Wikifier.prototype.subWikifyTerm = function(output,terminatorRegExp)
{
	var oldOutput = this.output;
	this.output = output;
	terminatorRegExp.lastIndex = this.nextMatch;
	var terminatorMatch = terminatorRegExp.exec(this.source);
	this.formatter.formatterRegExp.lastIndex = this.nextMatch;
	var formatterMatch = this.formatter.formatterRegExp.exec(terminatorMatch ? this.source.substr(0,terminatorMatch.index) : this.source);
	while(terminatorMatch || formatterMatch) {
		if(terminatorMatch && (!formatterMatch || terminatorMatch.index <= formatterMatch.index)) {
			if(terminatorMatch.index > this.nextMatch)
				this.outputText(this.output,this.nextMatch,terminatorMatch.index);
			this.matchText = terminatorMatch[1];
			this.matchLength = terminatorMatch[1].length;
			this.matchStart = terminatorMatch.index;
			this.nextMatch = this.matchStart + this.matchLength;
			this.output = oldOutput;
			return;
		}
		if(formatterMatch.index > this.nextMatch)
			this.outputText(this.output,this.nextMatch,formatterMatch.index);
		this.matchStart = formatterMatch.index;
		this.matchLength = formatterMatch[0].length;
		this.matchText = formatterMatch[0];
		this.nextMatch = this.formatter.formatterRegExp.lastIndex;
		var t;
		for(t=1; t<formatterMatch.length; t++) {
			if(formatterMatch[t]) {
				this.formatter.formatters[t-1].handler(this);
				this.formatter.formatterRegExp.lastIndex = this.nextMatch;
				break;
			}
		}
		terminatorRegExp.lastIndex = this.nextMatch;
		terminatorMatch = terminatorRegExp.exec(this.source);
		formatterMatch = this.formatter.formatterRegExp.exec(terminatorMatch ? this.source.substr(0,terminatorMatch.index) : this.source);
	}
	if(this.nextMatch < this.source.length) {
		this.outputText(this.output,this.nextMatch,this.source.length);
		this.nextMatch = this.source.length;
	}
	this.output = oldOutput;
};

Wikifier.prototype.outputText = function(place,startPos,endPos)
{
	while(this.highlightMatch && (this.highlightRegExp.lastIndex > startPos) && (this.highlightMatch.index < endPos) && (startPos < endPos)) {
		if(this.highlightMatch.index > startPos) {
			createTiddlyText(place,this.source.substring(startPos,this.highlightMatch.index));
			startPos = this.highlightMatch.index;
		}
		var highlightEnd = Math.min(this.highlightRegExp.lastIndex,endPos);
		createTiddlyElement(place,"span",null,"highlight",this.source.substring(startPos,highlightEnd));
		startPos = highlightEnd;
		if(startPos >= this.highlightRegExp.lastIndex)
			this.highlightMatch = this.highlightRegExp.exec(this.source);
	}
	if(startPos < endPos) {
		createTiddlyText(place,this.source.substring(startPos,endPos));
	}
};

function wikify(source,output,highlightRegExp,tiddler)
{
	if(source) {
		var wikifier = new Wikifier(source,getParser(tiddler),highlightRegExp,tiddler);
		var t0 = new Date();
		wikifier.subWikify(output);
		if(tiddler && config.options.chkDisplayInstrumentation)
			displayMessage("wikify:" +tiddler.title+ " in " + (new Date()-t0) + " ms");
	}
}

function wikifyStatic(source,highlightRegExp,tiddler,format)
{
	var e = createTiddlyElement(document.body,"pre");
	e.style.display = "none";
	var html = "";
	if(source && source != "") {
		if(!tiddler)
			tiddler = new Tiddler("temp");
		var wikifier = new Wikifier(source,getParser(tiddler,format),highlightRegExp,tiddler);
		wikifier.isStatic = true;
		wikifier.subWikify(e);
		html = e.innerHTML;
		jQuery(e).remove();
	}
	return html;
}

function wikifyPlainText(text,limit,tiddler)
{
	if(limit > 0)
		text = text.substr(0,limit);
	var wikifier = new Wikifier(text,formatter,null,tiddler);
	return wikifier.wikifyPlain();
}

function highlightify(source,output,highlightRegExp,tiddler)
{
	if(source) {
		var wikifier = new Wikifier(source,formatter,highlightRegExp,tiddler);
		wikifier.outputText(output,0,source.length);
	}
}

//--
//-- Macro definitions
//--

function invokeMacro(place,macro,params,wikifier,tiddler)
{
	try {
		var m = config.macros[macro];
		if(m && m.handler) {
			var tiddlerElem = story.findContainingTiddler(place);
			window.tiddler = tiddlerElem ? store.getTiddler(tiddlerElem.getAttribute("tiddler")) : null;
			window.place = place;
			var allowEval = true;
			if(config.evaluateMacroParameters=="system") {
				if(!tiddler || tiddler.tags.indexOf("systemAllowEval") == -1) {
					allowEval = false;
				}
			}
			m.handler(place,macro,m.noPreParse?null:params.readMacroParams(!allowEval),wikifier,params,tiddler);
		} else {
			createTiddlyError(place,config.messages.macroError.format([macro]),config.messages.macroErrorDetails.format([macro,config.messages.missingMacro]));
		}
	} catch(ex) {
		createTiddlyError(place,config.messages.macroError.format([macro]),config.messages.macroErrorDetails.format([macro,ex.toString()]));
	}
}

config.macros.version.handler = function(place)
{
	jQuery("<span/>").text(formatVersion()).appendTo(place);
};

config.macros.today.handler = function(place,macroName,params)
{
	var now = new Date();
	var text = params[0] ? now.formatString(params[0].trim()) : now.toLocaleString();
	jQuery("<span/>").text(text).appendTo(place);
};

config.macros.list.template = "<<view title link>>";
config.macros.list.handler = function(place,macroName,params,wikifier,paramString)
{
	var list = document.createElement("ul");
	jQuery(list).attr({ refresh: "macro", macroName: macroName }).data("params", paramString);
	place.appendChild(list);
	this.refresh(list);
};

config.macros.list.refresh = function(list) {
	var paramString = jQuery(list).data("params");
	var params = paramString.readMacroParams();
	var args = paramString.parseParams("anon", null, null)[0];
	var type = args.anon ? args.anon[0] : "all";
	jQuery(list).empty().addClass("list list-" + type);
	var template = args.template ? store.getTiddlerText(args.template[0]) : false;
	if(!template) {
		template = config.macros.list.template;
	}
	if(this[type].prompt)
		createTiddlyElement(list,"li",null,"listTitle",this[type].prompt);
	var results;
	if(this[type].handler)
		results = this[type].handler(params);
	var t;
	for(t = 0; t < results.length; t++) {
		var li = document.createElement("li");
		list.appendChild(li);
		var tiddler = results[t];
		if(typeof(tiddler) == 'string') { // deal with missing etc..
				tiddler = store.getTiddler(tiddler) || new Tiddler(tiddler);
		}
		wikify(template, li, null, tiddler);
	}
	if(results.length === 0 && args.emptyMessage) {
		jQuery(list).addClass("emptyList");
		jQuery("<li />").text(args.emptyMessage[0]).appendTo(list);
	}
};

config.macros.list.all.handler = function(params)
{
	return store.reverseLookup("tags","excludeLists",false,"title");
};

config.macros.list.missing.handler = function(params)
{
	return store.getMissingLinks();
};

config.macros.list.orphans.handler = function(params)
{
	return store.getOrphans();
};

config.macros.list.shadowed.handler = function(params)
{
	return store.getShadowed();
};

config.macros.list.touched.handler = function(params)
{
	return store.getTouched();
};

config.macros.list.filter.handler = function(params)
{
	var filter = params[1];
	var results = [];
	if(filter) {
		var tiddlers = store.filterTiddlers(filter);
		var t;
		for(t=0; t<tiddlers.length; t++)
			results.push(tiddlers[t].title);
	}
	return results;
};

config.macros.allTags.handler = function(place,macroName,params)
{
	var tags = store.getTags(params[0]);
	var ul = createTiddlyElement(place,"ul");
	if(tags.length == 0)
		createTiddlyElement(ul,"li",null,"listTitle",this.noTags);
	var t;
	for(t=0; t<tags.length; t++) {
		var title = tags[t][0];
		var info = getTiddlyLinkInfo(title);
		var li = createTiddlyElement(ul,"li");
		var btn = createTiddlyButton(li,title + " (" + tags[t][1] + ")",this.tooltip.format([title]),onClickTag,info.classes);
		btn.setAttribute("tag",title);
		btn.setAttribute("refresh","link");
		btn.setAttribute("tiddlyLink",title);
		if(params[1]) {
			btn.setAttribute("sortby",params[1]);
		}
	}
};

var macro = config.macros.timeline;
merge(macro, {
	handler: function(place,macroName,params, wikifier, paramString, tiddler) {
		var container = jQuery("<div />").attr("params", paramString).
			attr("macroName", macroName).appendTo(place)[0];
		macro.refresh(container);
	},
	refresh: function(container) {
		jQuery(container).attr("refresh", "macro").empty();
		var paramString = jQuery(container).attr("params");
		var args = paramString.parseParams("anon", null, null)[0];
		var params = args.anon || [];

		var field = params[0] || "modified";
		var prefix = field.charAt(0);
		var no_prefix_field = prefix === "-" || prefix === "+" ? field.substr(1, field.length) : field;
		var dateFormat = params[2] || this.dateFormat;
		var groupTemplate = macro.groupTemplate.format(no_prefix_field, dateFormat);
		groupTemplate = args.groupTemplate ? store.getTiddlerText(args.groupTemplate[0]) || groupTemplate :
			groupTemplate;

		var itemTemplate = macro.itemTemplate;
		itemTemplate = args.template ? store.getTiddlerText(args.template[0]) || itemTemplate :
			itemTemplate;

		var tiddlers = args.filter ? store.sortTiddlers(store.filterTiddlers(args.filter[0]), field) :
			store.reverseLookup("tags", "excludeLists", false, field);
		var lastGroup = "", ul;
		var last = params[1] ? tiddlers.length-Math.min(tiddlers.length,parseInt(params[1],10)) : 0;
		var t;
		for(t=tiddlers.length-1; t>=last; t--) {
			var tiddler = tiddlers[t];
			var theGroup = wikifyPlainText(groupTemplate,0,tiddler);
			if(typeof(ul) == "undefined" || theGroup != lastGroup) {
				ul = document.createElement("ul");
				jQuery(ul).addClass("timeline");
				container.appendChild(ul);
				createTiddlyElement(ul,"li",null,"listTitle",theGroup);
				lastGroup = theGroup;
			}
			var item = createTiddlyElement(ul,"li",null,"listLink");
			wikify(itemTemplate,item,null,tiddler);
		}
	},
	groupTemplate: "<<view %0 date '%1'>>", 
	itemTemplate: "<<view title link>>"
});

config.macros.tiddler.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var allowEval = true;
	var stack = config.macros.tiddler.tiddlerStack;
	if(stack.length > 0 && config.evaluateMacroParameters == "system") {
		// included tiddler and "system" evaluation required, so check tiddler tagged appropriately
		var title = stack[stack.length-1];
		var pos = title.indexOf(config.textPrimitives.sectionSeparator);
		if(pos != -1) {
			title = title.substr(0,pos); // get the base tiddler title
		}
		var t = store.getTiddler(title);
		if(!t || t.tags.indexOf("systemAllowEval") == -1) {
			allowEval = false;
		}
	}
	params = paramString.parseParams("name",null,allowEval,false,true);
	var names = params[0]["name"];
	var tiddlerName = names[0];
	var className = names[1] || null;
	var args = params[0]["with"];
	var wrapper = createTiddlyElement(place,"span",null,className,null,{
		refresh: "content", tiddler: tiddlerName
	});
	if(args!==undefined)
		wrapper.setAttribute("args","[["+args.join("]] [[")+"]]");
	this.transclude(wrapper,tiddlerName,args);
};

config.macros.tiddler.transclude = function(wrapper,tiddlerName,args)
{
	var text = store.getTiddlerText(tiddlerName);
	if(!text)
		return;
	var stack = config.macros.tiddler.tiddlerStack;
	if(stack.indexOf(tiddlerName) !== -1)
		return;
	stack.push(tiddlerName);
	try {
		if(typeof args == "string")
			args = args.readBracketedList();
		var n = args ? Math.min(args.length,9) : 0;
		var i;
		for(i=0; i<n; i++) {
			var placeholderRE = new RegExp("\\$" + (i + 1),"mg");
			text = text.replace(placeholderRE,args[i]);
		}
		config.macros.tiddler.renderText(wrapper,text,tiddlerName);
	} finally {
		stack.pop();
	}
};

config.macros.tiddler.renderText = function(place,text,tiddlerName)
{
	wikify(text,place,null,store.getTiddler(tiddlerName));
};

config.macros.tiddler.tiddlerStack = [];

config.macros.tag.handler = function(place,macroName,params)
{
	var btn = createTagButton(place,params[0],null,params[1],params[2]);
	if(params[3]) {
		btn.setAttribute('sortby',params[3]);
	}
};

config.macros.tags.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	params = paramString.parseParams("anon",null,true,false,false);
	var ul = createTiddlyElement(place,"ul");
	var title = getParam(params,"anon","");
	if(title && store.tiddlerExists(title))
		tiddler = store.getTiddler(title);
	var sep = getParam(params,"sep"," ");
	var lingo = config.views.wikified.tag;
	var label = null;
	var t;
	for(t=0; t<tiddler.tags.length; t++) {
		var tag = store.getTiddler(tiddler.tags[t]);
		if(!tag || !tag.tags.contains("excludeLists")) {
			if(!label)
				label = createTiddlyElement(ul,"li",null,"listTitle",lingo.labelTags.format([tiddler.title]));
			createTagButton(createTiddlyElement(ul,"li"),tiddler.tags[t],tiddler.title);
			if(t<tiddler.tags.length-1)
				createTiddlyText(ul,sep);
		}
	}
	if(!label)
		createTiddlyElement(ul,"li",null,"listTitle",lingo.labelNoTags.format([tiddler.title]));
};

config.macros.tagging.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	params = paramString.parseParams("anon",null,true,false,false);
	var ul = createTiddlyElement(place,"ul");
	var title = getParam(params,"anon","");
	if(title == "" && tiddler instanceof Tiddler)
		title = tiddler.title;
	var sep = getParam(params,"sep"," ");
	ul.setAttribute("title",this.tooltip.format([title]));
	var sortby = getParam(params,"sortBy",false);
	var tagged = store.getTaggedTiddlers(title,sortby);
	var prompt = tagged.length == 0 ? this.labelNotTag : this.label;
	createTiddlyElement(ul,"li",null,"listTitle",prompt.format([title,tagged.length]));
	var t;
	for(t=0; t<tagged.length; t++) {
		createTiddlyLink(createTiddlyElement(ul,"li"),tagged[t].title,true);
		if(t<tagged.length-1)
			createTiddlyText(ul,sep);
	}
};

config.macros.closeAll.handler = function(place)
{
	createTiddlyButton(place,this.label,this.prompt,this.onClick);
};

config.macros.closeAll.onClick = function(e)
{
	story.closeAllTiddlers();
	return false;
};

config.macros.permaview.handler = function(place)
{
	createTiddlyButton(place,this.label,this.prompt,this.onClick);
};

config.macros.permaview.onClick = function(e)
{
	story.permaView();
	return false;
};

config.macros.saveChanges.handler = function(place,macroName,params)
{
	if(!readOnly)
		createTiddlyButton(place,params[0] || this.label,params[1] || this.prompt,this.onClick,null,null,this.accessKey);
};

config.macros.saveChanges.onClick = function(e)
{
	saveChanges();
	return false;
};

config.macros.slider.onClickSlider = function(ev)
{
	var n = this.nextSibling;
	var cookie = n.getAttribute("cookie");
	var isOpen = n.style.display != "none";
	if(config.options.chkAnimate && anim && typeof Slider == "function")
		anim.startAnimating(new Slider(n,!isOpen,null,"none"));
	else
		n.style.display = isOpen ? "none" : "block";
	config.options[cookie] = !isOpen;
	saveOption(cookie);
	return false;
};

config.macros.slider.createSlider = function(place,cookie,title,tooltip)
{
	var c = cookie || "";
	createTiddlyButton(place,title,tooltip,this.onClickSlider);
	var panel = createTiddlyElement(null,"div",null,"sliderPanel");
	panel.setAttribute("cookie",c);
	panel.style.display = config.options[c] ? "block" : "none";
	place.appendChild(panel);
	return panel;
};

config.macros.slider.handler = function(place,macroName,params)
{
	var panel = this.createSlider(place,params[0],params[2],params[3]);
	var text = store.getTiddlerText(params[1]);
	panel.setAttribute("refresh","content");
	panel.setAttribute("tiddler",params[1]);
	if(text)
		wikify(text,panel,null,store.getTiddler(params[1]));
};

// <<gradient [[tiddler name]] vert|horiz rgb rgb rgb rgb... >>
config.macros.gradient.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var panel = wikifier ? createTiddlyElement(place,"div",null,"gradient") : place;
	panel.style.position = "relative";
	panel.style.overflow = "hidden";
	panel.style.zIndex = "0";
	if(wikifier) {
		var styles = config.formatterHelpers.inlineCssHelper(wikifier);
		config.formatterHelpers.applyCssHelper(panel,styles);
	}
	params = paramString.parseParams("color");
	var locolors = [], hicolors = [];
	var t;
	for(t=2; t<params.length; t++) {
		var c = params[t].value;
		if(params[t].name == "snap") {
			hicolors[hicolors.length-1] = c;
		} else {
			locolors.push(c);
			hicolors.push(c);
		}
	}
	drawGradient(panel,params[1].value != "vert",locolors,hicolors);
	if(wikifier)
		wikifier.subWikify(panel,">>");
	if(document.all) {
		panel.style.height = "100%";
		panel.style.width = "100%";
	}
};

config.macros.message.handler = function(place,macroName,params)
{
	if(params[0]) {
		var names = params[0].split(".");
		var lookupMessage = function(root,nameIndex) {
				if(root[names[nameIndex]]) {
					if(nameIndex < names.length-1)
						return (lookupMessage(root[names[nameIndex]],nameIndex+1));
					else
						return root[names[nameIndex]];
				} else
					return null;
			};
		var m = lookupMessage(config,0);
		if(m == null)
			m = lookupMessage(window,0);
		createTiddlyText(place,m.toString().format(params.splice(1)));
	}
};


config.macros.view.depth = 0;
config.macros.view.values = [];
config.macros.view.views = {
	text: function(value,place,params,wikifier,paramString,tiddler) {
		highlightify(value,place,highlightHack,tiddler);
	},
	link: function(value,place,params,wikifier,paramString,tiddler) {
		createTiddlyLink(place,value,true);
	},
	wikified: function(value,place,params,wikifier,paramString,tiddler) {
		if(config.macros.view.depth>50)
			return;
		if(config.macros.view.depth>0) {
			if (value==config.macros.view.values[config.macros.view.depth-1]) {
				return;
			}
		}
		config.macros.view.values[config.macros.view.depth] = value;
		config.macros.view.depth++;
		if(params[2])
			value=params[2].unescapeLineBreaks().format([value]);
		wikify(value,place,highlightHack,tiddler);
		config.macros.view.depth--;
		config.macros.view.values[config.macros.view.depth] = null;
	},
	date: function(value,place,params,wikifier,paramString,tiddler) {
		value = Date.convertFromYYYYMMDDHHMM(value);
		createTiddlyText(place,value.formatString(params[2] || config.views.wikified.dateFormat));
	}
};

config.macros.view.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	if((tiddler instanceof Tiddler) && params[0]) {
		var value = store.getValue(tiddler,params[0]);
		if(value) {
			var type = params[1] || config.macros.view.defaultView;
			var handler = config.macros.view.views[type];
			if(handler)
				handler(value,place,params,wikifier,paramString,tiddler);
		}
	}
};

config.macros.edit.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var field = params[0];
	var rows = params[1] || 0;
	var defVal = params[2] || '';
	if((tiddler instanceof Tiddler) && field) {
		story.setDirty(tiddler.title,true);
		var e,v;
		if(field != "text" && !rows) {
			e = createTiddlyElement(null,"input",null,null,null,{
				type: "text", edit: field, size: "40", autocomplete: "off"
			});
			e.value = store.getValue(tiddler,field) || defVal;
			place.appendChild(e);
		} else {
			var wrapper1 = createTiddlyElement(null,"fieldset",null,"fieldsetFix");
			var wrapper2 = createTiddlyElement(wrapper1,"div");
			e = createTiddlyElement(wrapper2,"textarea");
			e.value = v = store.getValue(tiddler,field) || defVal;
			rows = rows || 10;
			var lines = v.match(/\n/mg);
			var maxLines = Math.max(parseInt(config.options.txtMaxEditRows,10),5);
			if(lines != null && lines.length > rows)
				rows = lines.length + 5;
			rows = Math.min(rows,maxLines);
			e.setAttribute("rows",rows);
			e.setAttribute("edit",field);
			place.appendChild(wrapper1);
		}
		if(tiddler.isReadOnly()) {
			e.setAttribute("readOnly","readOnly");
			jQuery(e).addClass("readOnly");
		}
		return e;
	}
};

config.macros.tagChooser.onClick = function(ev)
{
	var e = ev || window.event;
	var lingo = config.views.editor.tagChooser;
	var popup = Popup.create(this);
	var tags = store.getTags(this.getAttribute("tags"));
	if(tags.length == 0)
		jQuery("<li/>").text(lingo.popupNone).appendTo(popup);
	var t;
	for(t=0; t<tags.length; t++) {
		var tag = createTiddlyButton(createTiddlyElement(popup,"li"),tags[t][0],lingo.tagTooltip.format([tags[t][0]]),config.macros.tagChooser.onTagClick);
		tag.setAttribute("tag",tags[t][0]);
		tag.setAttribute("tiddler",this.getAttribute("tiddler"));
	}
	Popup.show();
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	return false;
};

config.macros.tagChooser.onTagClick = function(ev)
{
	var e = ev || window.event;
	if(e.metaKey || e.ctrlKey) stopEvent(e); //# keep popup open on CTRL-click
	var tag = this.getAttribute("tag");
	var title = this.getAttribute("tiddler");
	if(!readOnly)
		story.setTiddlerTag(title,tag,0);
	return false;
};

config.macros.tagChooser.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	if(tiddler instanceof Tiddler) {
		var lingo = config.views.editor.tagChooser;
		var btn = createTiddlyButton(place,lingo.text,lingo.tooltip,this.onClick);
		btn.setAttribute("tiddler",tiddler.title);
		btn.setAttribute("tags",params[0]);
	}
};

config.macros.refreshDisplay.handler = function(place)
{
	createTiddlyButton(place,this.label,this.prompt,this.onClick);
};

config.macros.refreshDisplay.onClick = function(e)
{
	refreshAll();
	return false;
};

config.macros.annotations.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var title = tiddler ? tiddler.title : null;
	var a = title ? config.annotations[title] : null;
	if(!tiddler || !title || !a)
		return;
	var text = a.format([title]);
	wikify(text,createTiddlyElement(place,"div",null,"annotation"),null,tiddler);
};
//--
//-- NewTiddler and NewJournal macros
//--

config.macros.newTiddler.createNewTiddlerButton = function(place,title,params,label,prompt,accessKey,newFocus,isJournal)
{
	var tags = [];
	var t;
	for(t=1; t<params.length; t++) {
		if((params[t].name == "anon" && t != 1) || (params[t].name == "tag"))
			tags.push(params[t].value);
	}
	label = getParam(params,"label",label);
	prompt = getParam(params,"prompt",prompt);
	accessKey = getParam(params,"accessKey",accessKey);
	newFocus = getParam(params,"focus",newFocus);
	var customFields = getParam(params,"fields","");
	if(!customFields && !store.isShadowTiddler(title))
		customFields = String.encodeHashMap(config.defaultCustomFields);
	var btn = createTiddlyButton(place,label,prompt,this.onClickNewTiddler,null,null,accessKey);
	btn.setAttribute("newTitle",title);
	btn.setAttribute("isJournal",isJournal ? "true" : "false");
	if(tags.length > 0)
		btn.setAttribute("params",tags.join("|"));
	btn.setAttribute("newFocus",newFocus);
	btn.setAttribute("newTemplate",getParam(params,"template",DEFAULT_EDIT_TEMPLATE));
	if(customFields !== "")
		btn.setAttribute("customFields",customFields);
	var text = getParam(params,"text");
	if(text !== undefined)
		btn.setAttribute("newText",text);
	return btn;
};

config.macros.newTiddler.onClickNewTiddler = function()
{
	var title = this.getAttribute("newTitle");
	if(this.getAttribute("isJournal") == "true") {
		title = new Date().formatString(title.trim());
	}
	var params = this.getAttribute("params");
	var tags = params ? params.split("|") : [];
	var focus = this.getAttribute("newFocus");
	var template = this.getAttribute("newTemplate");
	var customFields = this.getAttribute("customFields");
	if(!customFields && !store.isShadowTiddler(title))
		customFields = String.encodeHashMap(config.defaultCustomFields);
	story.displayTiddler(null,title,template,false,null,null);
	var tiddlerElem = story.getTiddler(title);
	if(customFields)
		story.addCustomFields(tiddlerElem,customFields);
	var text = this.getAttribute("newText");
	if(typeof text == "string" && story.getTiddlerField(title,"text"))
		story.getTiddlerField(title,"text").value = text.format([title]);
	var t;
	for(t=0;t<tags.length;t++)
		story.setTiddlerTag(title,tags[t],+1);
	story.focusTiddler(title,focus);
	return false;
};

config.macros.newTiddler.handler = function(place,macroName,params,wikifier,paramString)
{
	if(!readOnly) {
		params = paramString.parseParams("anon",null,true,false,false);
		var title = params[1] && params[1].name == "anon" ? params[1].value : this.title;
		title = getParam(params,"title",title);
		this.createNewTiddlerButton(place,title,params,this.label,this.prompt,this.accessKey,"title",false);
	}
};

config.macros.newJournal.handler = function(place,macroName,params,wikifier,paramString)
{
	if(!readOnly) {
		params = paramString.parseParams("anon",null,true,false,false);
		var title = params[1] && params[1].name == "anon" ? params[1].value : config.macros.timeline.dateFormat;
		title = getParam(params,"title",title);
		config.macros.newTiddler.createNewTiddlerButton(place,title,params,this.label,this.prompt,this.accessKey,"text",true);
	}
};

//--
//-- Search macro
//--

config.macros.search.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	params = paramString.parseParams("anon",null,false,false,false);
	createTiddlyButton(place,this.label,this.prompt,this.onClick,"searchButton");
	var txt = createTiddlyElement(null,"input",null,"txtOptionInput searchField");
	txt.value = getParam(params,"anon","");
	if(config.browser.isSafari) {
		txt.setAttribute("type","search");
		txt.setAttribute("results","5");
	} else {
		txt.setAttribute("type","text");
	}
	place.appendChild(txt);
	txt.onkeyup = this.onKeyPress;
	txt.onfocus = this.onFocus;
	txt.setAttribute("size",this.sizeTextbox);
	txt.setAttribute("accessKey",getParam(params,"accesskey",this.accessKey));
	txt.setAttribute("autocomplete","off");
	txt.setAttribute("lastSearchText","");
	txt.setAttribute("placeholder",getParam(params,"placeholder",this.placeholder));
};

// Global because there's only ever one outstanding incremental search timer
config.macros.search.timeout = null;

config.macros.search.doSearch = function(txt)
{
	if(txt.value.length > 0) {
		story.search(txt.value,config.options.chkCaseSensitiveSearch,config.options.chkRegExpSearch);
		txt.setAttribute("lastSearchText",txt.value);
	}
};

config.macros.search.onClick = function(e)
{
	config.macros.search.doSearch(this.nextSibling);
	return false;
};

config.macros.search.onKeyPress = function(ev)
{
	var me = config.macros.search;
	var e = ev || window.event;
	switch(e.keyCode) {
		case 9: // Tab
			return;
		case 13: // Ctrl-Enter
		case 10: // Ctrl-Enter on IE PC
			me.doSearch(this);
			break;
		case 27: // Escape
			this.value = "";
			clearMessage();
			break;
	}
	if(config.options.chkIncrementalSearch) {
		if(this.value.length > 2) {
			if(this.value != this.getAttribute("lastSearchText")) {
				if(me.timeout) {
					clearTimeout(me.timeout);
				}
				var txt = this;
				me.timeout = setTimeout(function() {me.doSearch(txt);},500);
			}
		} else {
			if(me.timeout) {
				clearTimeout(me.timeout);
			}
		}
	}
};

config.macros.search.onFocus = function(e)
{
	this.select();
};

//--
//-- Tabs macro
//--

config.macros.tabs.handler = function(place,macroName,params)
{
	var cookie = params[0];
	var numTabs = (params.length-1)/3;
	var wrapper = createTiddlyElement(null,"div",null,"tabsetWrapper " + cookie);
	var tabset = createTiddlyElement(wrapper,"div",null,"tabset");
	tabset.setAttribute("cookie",cookie);
	var validTab = false;
	var t;
	for(t=0; t<numTabs; t++) {
		var label = params[t*3+1];
		var prompt = params[t*3+2];
		var content = params[t*3+3];
		var tab = createTiddlyButton(tabset,label,prompt,this.onClickTab,"tab tabUnselected");
		createTiddlyElement(tab,"span",null,null," ",{style:"font-size:0pt;line-height:0px"});
		tab.setAttribute("tab",label);
		tab.setAttribute("content",content);
		tab.title = prompt;
		if(config.options[cookie] == label)
			validTab = true;
	}
	if(!validTab)
		config.options[cookie] = params[1];
	place.appendChild(wrapper);
	this.switchTab(tabset,config.options[cookie]);
};

config.macros.tabs.onClickTab = function(e)
{
	config.macros.tabs.switchTab(this.parentNode,this.getAttribute("tab"));
	return false;
};

config.macros.tabs.switchTab = function(tabset,tab)
{
	var cookie = tabset.getAttribute("cookie");
	var theTab = null;
	var nodes = tabset.childNodes;
	var t;
	for(t=0; t<nodes.length; t++) {
		if(nodes[t].getAttribute && nodes[t].getAttribute("tab") == tab) {
			theTab = nodes[t];
			theTab.className = "tab tabSelected";
		} else {
			nodes[t].className = "tab tabUnselected";
		}
	}
	if(theTab) {
		if(tabset.nextSibling && tabset.nextSibling.className == "tabContents")
			jQuery(tabset.nextSibling).remove();
		var tabContent = createTiddlyElement(null,"div",null,"tabContents");
		tabset.parentNode.insertBefore(tabContent,tabset.nextSibling);
		var contentTitle = theTab.getAttribute("content");
		wikify(store.getTiddlerText(contentTitle),tabContent,null,store.getTiddler(contentTitle));
		if(cookie) {
			config.options[cookie] = tab;
			saveOption(cookie);
		}
	}
};

//--
//-- Tiddler toolbar
//--

// Create a toolbar command button
config.macros.toolbar.createCommand = function(place,commandName,tiddler,className)
{
	if(typeof commandName != "string") {
		var c = null;
		var t;
		for(t in config.commands) {
			if(config.commands[t] == commandName)
				c = t;
		}
		commandName = c;
	}
	if((tiddler instanceof Tiddler) && (typeof commandName == "string")) {
		var command = config.commands[commandName];
		if(command.isEnabled ? command.isEnabled(tiddler) : this.isCommandEnabled(command,tiddler)) {
			var text = command.getText ? command.getText(tiddler) : this.getCommandText(command,tiddler);
			var tooltip = command.getTooltip ? command.getTooltip(tiddler) : this.getCommandTooltip(command,tiddler);
			var cmd = command.type == "popup" ? this.onClickPopup : this.onClickCommand;
			var btn = createTiddlyButton(null,text,tooltip,cmd);
			btn.setAttribute("commandName",commandName);
			btn.setAttribute("tiddler",tiddler.title);
			jQuery(btn).addClass("command_" + commandName);
			if(className)
				jQuery(btn).addClass(className);
			place.appendChild(btn);
		}
	}
};

config.macros.toolbar.isCommandEnabled = function(command,tiddler)
{
	var title = tiddler.title;
	var ro = tiddler.isReadOnly();
	var shadow = store.isShadowTiddler(title) && !store.tiddlerExists(title);
	return (!ro || (ro && !command.hideReadOnly)) && !(shadow && command.hideShadow);
};

config.macros.toolbar.getCommandText = function(command,tiddler)
{
	return (tiddler.isReadOnly() && command.readOnlyText) || command.text;
};

config.macros.toolbar.getCommandTooltip = function(command,tiddler)
{
	return (tiddler.isReadOnly() && command.readOnlyTooltip) || command.tooltip;
};

config.macros.toolbar.onClickCommand = function(ev)
{
	var e = ev || window.event;
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	var command = config.commands[this.getAttribute("commandName")];
	return command.handler(e,this,this.getAttribute("tiddler"));
};

config.macros.toolbar.onClickPopup = function(ev)
{
	var e = ev || window.event;
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	var popup = Popup.create(this);
	var command = config.commands[this.getAttribute("commandName")];
	var title = this.getAttribute("tiddler");
	popup.setAttribute("tiddler",title);
	command.handlePopup(popup,title);
	Popup.show();
	return false;
};

// Invoke the first command encountered from a given place that is tagged with a specified class
config.macros.toolbar.invokeCommand = function(place,className,event)
{
	var children = place.getElementsByTagName("a");
	var t;
	for(t=0; t<children.length; t++) {
		var c = children[t];
		if(jQuery(c).hasClass(className) && c.getAttribute && c.getAttribute("commandName")) {
			if(c.onclick instanceof Function)
				c.onclick.call(c,event);
			break;
		}
	}
};

config.macros.toolbar.onClickMore = function(ev)
{
	var e = this.nextSibling;
	e.style.display = "inline";
	this.style.display = "none";
	return false;
};

config.macros.toolbar.onClickLess = function(ev)
{
	var e = this.parentNode;
	var m = e.previousSibling;
	e.style.display = "none";
	m.style.display = "inline";
	return false;
};

config.macros.toolbar.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var t;
	for(t=0; t<params.length; t++) {
		var btn;
		var c = params[t];
		switch(c) {
		case "!":
			createTiddlyText(place,this.separator);
			break;
		case "*":
			createTiddlyElement(place,"br");
			break;
		case "<":
			btn = createTiddlyButton(place,this.lessLabel,this.lessPrompt,config.macros.toolbar.onClickLess);
			jQuery(btn).addClass("lessCommand");
			break;
		case ">":
			btn = createTiddlyButton(place,this.moreLabel,this.morePrompt,config.macros.toolbar.onClickMore);
			jQuery(btn).addClass("moreCommand");
			var e = createTiddlyElement(place,"span",null,"moreCommand");
			e.style.display = "none";
			place = e;
			break;
		default:
			var className = "";
			switch(c.substr(0,1)) {
			case "+":
				className = "defaultCommand";
				c = c.substr(1);
				break;
			case "-":
				className = "cancelCommand";
				c = c.substr(1);
				break;
			}
			if(config.commands[c]) {
				this.createCommand(place,c,tiddler,className);
			} else {
				this.customCommand(place,c,wikifier,tiddler);
			}
			break;
		}
	}
};

// Overrideable function to extend toolbar handler
config.macros.toolbar.customCommand = function(place,command,wikifier,tiddler)
{
};

//--
//-- Menu and toolbar commands
//--

config.commands.closeTiddler.handler = function(event,src,title)
{
	if(story.isDirty(title) && !readOnly) {
		if(!confirm(config.commands.cancelTiddler.warning.format([title])))
			return false;
	}
	story.setDirty(title,false);
	story.closeTiddler(title,true);
	return false;
};

config.commands.closeOthers.handler = function(event,src,title)
{
	story.closeAllTiddlers(title);
	return false;
};

config.commands.editTiddler.handler = function(event,src,title)
{
	clearMessage();
	var tiddlerElem = story.getTiddler(title);
	var fields = tiddlerElem.getAttribute("tiddlyFields");
	story.displayTiddler(null,title,DEFAULT_EDIT_TEMPLATE,false,null,fields);
	var e = story.getTiddlerField(title,config.options.txtEditorFocus||"text");
	if(e) {
		setCaretPosition(e,0);
	}
	return false;
};

config.commands.saveTiddler.handler = function(event,src,title)
{
	var newTitle = story.saveTiddler(title,event.shiftKey);
	if(newTitle)
		story.displayTiddler(null,newTitle);
	return false;
};

config.commands.cancelTiddler.handler = function(event,src,title)
{
	if(story.hasChanges(title) && !readOnly) {
		if(!confirm(this.warning.format([title])))
			return false;
	}
	story.setDirty(title,false);
	story.displayTiddler(null,title);
	return false;
};

config.commands.deleteTiddler.handler = function(event,src,title)
{
	var deleteIt = true;
	if(config.options.chkConfirmDelete)
		deleteIt = confirm(this.warning.format([title]));
	if(deleteIt) {
		store.removeTiddler(title);
		story.closeTiddler(title,true);
		autoSaveChanges();
	}
	return false;
};

config.commands.permalink.handler = function(event,src,title)
{
	var t = encodeURIComponent(String.encodeTiddlyLink(title));
	if(window.location.hash != t)
		window.location.hash = t;
	return false;
};

config.commands.references.handlePopup = function(popup,title)
{
	var references = store.getReferringTiddlers(title);
	var c = false;
	var r;
	for(r=0; r<references.length; r++) {
		if(references[r].title != title && !references[r].isTagged("excludeLists")) {
			createTiddlyLink(createTiddlyElement(popup,"li"),references[r].title,true);
			c = true;
		}
	}
	if(!c)
		createTiddlyElement(popup,"li",null,"disabled",this.popupNone);
};

config.commands.jump.handlePopup = function(popup,title)
{
	story.forEachTiddler(function(title,element) {
		createTiddlyLink(createTiddlyElement(popup,"li"),title,true,null,false,null,true);
		});
};

config.commands.fields.handlePopup = function(popup,title)
{
	var tiddler = store.fetchTiddler(title);
	if(!tiddler)
		return;
	var items = [];
	store.forEachField(tiddler,function(tiddler,fieldName,value){items.push({field:fieldName,value:value});},true);
	items.sort(function(a,b) {return a.field < b.field ? -1 : (a.field == b.field ? 0 : +1);});
	if(items.length > 0)
		ListView.create(popup,items,this.listViewTemplate);
	else
		createTiddlyElement(popup,"div",null,null,this.emptyText);
};

//--
//-- Tiddler() object
//--

function Tiddler(title)
{
	this.title = title;
	this.text = "";
	this.creator = null;
	this.modifier = null;
	this.created = new Date();
	this.modified = this.created;
	this.links = [];
	this.linksUpdated = false;
	this.tags = [];
	this.fields = {};
	return this;
}

Tiddler.prototype.getLinks = function()
{
	if(this.linksUpdated==false)
		this.changed();
	return this.links;
};

// Returns the fields that are inherited in string field:"value" field2:"value2" format
Tiddler.prototype.getInheritedFields = function()
{
	var f = {};
	var i;
	for(i in this.fields) {
		if(i=="server.host" || i=="server.workspace" || i=="wikiformat"|| i=="server.type") {
			f[i] = this.fields[i];
		}
	}
	return String.encodeHashMap(f);
};

// Increment the changeCount of a tiddler
Tiddler.prototype.incChangeCount = function()
{
	var c = this.fields['changecount'];
	c = c ? parseInt(c,10) : 0;
	this.fields['changecount'] = String(c+1);
};

// Clear the changeCount of a tiddler
Tiddler.prototype.clearChangeCount = function()
{
	if(this.fields['changecount']) {
		delete this.fields['changecount'];
	}
};

Tiddler.prototype.doNotSave = function()
{
	return this.fields['doNotSave'];
};

// Returns true if the tiddler has been updated since the tiddler was created or downloaded
Tiddler.prototype.isTouched = function()
{
	var changecount = this.fields.changecount || 0;
	return changecount > 0;
};

// Change the text and other attributes of a tiddler
Tiddler.prototype.set = function(title,text,modifier,modified,tags,created,fields,creator)
{
	this.assign(title,text,modifier,modified,tags,created,fields,creator);
	this.changed();
	return this;
};

// Change the text and other attributes of a tiddler without triggered a tiddler.changed() call
Tiddler.prototype.assign = function(title,text,modifier,modified,tags,created,fields,creator)
{
	if(title != undefined)
		this.title = title;
	if(text != undefined)
		this.text = text;
	if(modifier != undefined)
		this.modifier = modifier;
	if(modified != undefined)
		this.modified = modified;
	if(creator != undefined)
		this.creator = creator;
	if(created != undefined)
		this.created = created;
	if(fields != undefined)
		this.fields = fields;
	if(tags != undefined)
		this.tags = (typeof tags == "string") ? tags.readBracketedList() : tags;
	else if(this.tags == undefined)
		this.tags = [];
	return this;
};

// Get the tags for a tiddler as a string (space delimited, using [[brackets]] for tags containing spaces)
Tiddler.prototype.getTags = function()
{
	return String.encodeTiddlyLinkList(this.tags);
};

// Test if a tiddler carries a tag
Tiddler.prototype.isTagged = function(tag)
{
	return this.tags.indexOf(tag) != -1;
};

// Static method to convert "\n" to newlines, "\s" to "\"
Tiddler.unescapeLineBreaks = function(text)
{
	return text ? text.unescapeLineBreaks() : "";
};

// Convert newlines to "\n", "\" to "\s"
Tiddler.prototype.escapeLineBreaks = function()
{
	return this.text.escapeLineBreaks();
};

// Updates the secondary information (like links[] array) after a change to a tiddler
Tiddler.prototype.changed = function()
{
	this.links = [];
	var text = this.text;
	// remove 'quoted' text before scanning tiddler source
	text = text.replace(/\/%((?:.|\n)*?)%\//g,"").
		replace(/\{{3}((?:.|\n)*?)\}{3}/g,"").
		replace(/"""((?:.|\n)*?)"""/g,"").
		replace(/<nowiki\>((?:.|\n)*?)<\/nowiki\>/g,"").
		replace(/<html\>((?:.|\n)*?)<\/html\>/g,"").
		replace(/<script((?:.|\n)*?)<\/script\>/g,"");
	var t = this.autoLinkWikiWords() ? 0 : 1;
	var tiddlerLinkRegExp = t==0 ? config.textPrimitives.tiddlerAnyLinkRegExp : config.textPrimitives.tiddlerForcedLinkRegExp;
	tiddlerLinkRegExp.lastIndex = 0;
	var formatMatch = tiddlerLinkRegExp.exec(text);
	while(formatMatch) {
		var lastIndex = tiddlerLinkRegExp.lastIndex;
		if(t==0 && formatMatch[1] && formatMatch[1] != this.title) {
			// wikiWordLink
			if(formatMatch.index > 0) {
				var preRegExp = new RegExp(config.textPrimitives.unWikiLink+"|"+config.textPrimitives.anyLetter,"mg");
				preRegExp.lastIndex = formatMatch.index-1;
				var preMatch = preRegExp.exec(text);
				if(preMatch.index != formatMatch.index-1)
					this.links.pushUnique(formatMatch[1]);
			} else {
				this.links.pushUnique(formatMatch[1]);
			}
		}
		else if(formatMatch[2-t] && !config.formatterHelpers.isExternalLink(formatMatch[3-t])) // titledBrackettedLink
			this.links.pushUnique(formatMatch[3-t]);
		else if(formatMatch[4-t] && formatMatch[4-t] != this.title) // brackettedLink
			this.links.pushUnique(formatMatch[4-t]);
		tiddlerLinkRegExp.lastIndex = lastIndex;
		formatMatch = tiddlerLinkRegExp.exec(text);
	}
	this.linksUpdated = true;
};

Tiddler.prototype.getSubtitle = function()
{
	var modifier = this.modifier;
	if(!modifier)
		modifier = config.messages.subtitleUnknown || "";
	var modified = this.modified;
	if(modified)
		modified = modified.toLocaleString();
	else
		modified = config.messages.subtitleUnknown || "";
	var f = config.messages.tiddlerLinkTooltip || "%0 - %1, %2";
	return f.format([this.title,modifier,modified]);
};

Tiddler.prototype.isReadOnly = function()
{
	return readOnly;
};

Tiddler.prototype.autoLinkWikiWords = function()
{
	return !(this.isTagged("systemConfig") || this.isTagged("excludeMissing"));
};

Tiddler.prototype.getServerType = function()
{
	var serverType = null;
	if(this.fields['server.type'])
		serverType = this.fields['server.type'];
	if(!serverType)
		serverType = this.fields['wikiformat'];
	if(serverType && !config.adaptors[serverType])
		serverType = null;
	return serverType;
};

Tiddler.prototype.getAdaptor = function()
{
	var serverType = this.getServerType();
	return serverType ? new config.adaptors[serverType]() : null;
};

//--
//-- TiddlyWiki instance contains TiddlerS
//--

function TiddlyWiki(params)
{
	var tiddlers = {}; // Hashmap by name of tiddlers
	if(params && params.config) {
		this.config = config;
	}
	this.tiddlersUpdated = false;
	this.namedNotifications = []; // Array of {name:,notify:} of notification functions
	this.notificationLevel = 0;
	this.slices = {}; // map tiddlerName->(map sliceName->sliceValue). Lazy.
	this.clear = function() {
		tiddlers = {};
		this.setDirty(false);
	};
	this.fetchTiddler = function(title) {
		var t = tiddlers[title];
		return t instanceof Tiddler ? t : null;
	};
	this.deleteTiddler = function(title) {
		delete this.slices[title];
		delete tiddlers[title];
	};
	this.addTiddler = function(tiddler) {
		delete this.slices[tiddler.title];
		tiddlers[tiddler.title] = tiddler;
	};
	this.forEachTiddler = function(callback) {
		var t;
		for(t in tiddlers) {
			var tiddler = tiddlers[t];
			if(tiddler instanceof Tiddler)
				callback.call(this,t,tiddler);
		}
	};
}

TiddlyWiki.prototype.setDirty = function(dirty)
{
	this.dirty = dirty;
};

TiddlyWiki.prototype.isDirty = function()
{
	return this.dirty;
};

TiddlyWiki.prototype.tiddlerExists = function(title)
{
	var t = this.fetchTiddler(title);
	return t != undefined;
};

TiddlyWiki.prototype.isShadowTiddler = function(title)
{
	return config.shadowTiddlers[title] === undefined ? false : true;
};

TiddlyWiki.prototype.createTiddler = function(title)
{
	var tiddler = this.fetchTiddler(title);
	if(!tiddler) {
		tiddler = new Tiddler(title);
		this.addTiddler(tiddler);
		this.setDirty(true);
	}
	return tiddler;
};

TiddlyWiki.prototype.getTiddler = function(title)
{
	var t = this.fetchTiddler(title);
	if(t != undefined)
		return t;
	else
		return null;
};

TiddlyWiki.prototype.getShadowTiddlerText = function(title)
{
	if(typeof config.shadowTiddlers[title] == "string")
		return config.shadowTiddlers[title];
	else
		return "";
};

// Retrieve tiddler contents
TiddlyWiki.prototype.getTiddlerText = function(title,defaultText)
{
	if(!title)
		return defaultText;
	var pos = title.indexOf(config.textPrimitives.sectionSeparator);
	var section = null;
	if(pos != -1) {
		section = title.substr(pos + config.textPrimitives.sectionSeparator.length);
		title = title.substr(0,pos);
	}
	pos = title.indexOf(config.textPrimitives.sliceSeparator);
	if(pos != -1) {
		var slice = this.getTiddlerSlice(title.substr(0,pos),title.substr(pos + config.textPrimitives.sliceSeparator.length));
		if(slice)
			return slice;
	}
	var tiddler = this.fetchTiddler(title);
	var text = tiddler ? tiddler.text : null;
	if(!tiddler && this.isShadowTiddler(title)) {
		text = this.getShadowTiddlerText(title);
	}
	if(text) {
		if(!section)
			return text;
		var re = new RegExp("(^!{1,6}[ \t]*" + section.escapeRegExp() + "[ \t]*\n)","mg");
		re.lastIndex = 0;
		var match = re.exec(text);
		if(match) {
			var t = text.substr(match.index+match[1].length);
			var re2 = /^!/mg;
			re2.lastIndex = 0;
			match = re2.exec(t); //# search for the next heading
			if(match)
				t = t.substr(0,match.index-1);//# don't include final \n
			return t;
		}
		return defaultText;
	}
	if(defaultText != undefined)
		return defaultText;
	return null;
};

TiddlyWiki.prototype.getRecursiveTiddlerText = function(title,defaultText,depth)
{
	var bracketRegExp = new RegExp("(?:\\[\\[([^\\]]+)\\]\\])","mg");
	var text = this.getTiddlerText(title,null);
	if(text == null)
		return defaultText;
	var textOut = [];
	var match,lastPos = 0;
	do {
		match = bracketRegExp.exec(text);
		if(match) {
			textOut.push(text.substr(lastPos,match.index-lastPos));
			if(match[1]) {
				if(depth <= 0)
					textOut.push(match[1]);
				else
					textOut.push(this.getRecursiveTiddlerText(match[1],"",depth-1));
			}
			lastPos = match.index + match[0].length;
		} else {
			textOut.push(text.substr(lastPos));
		}
	} while(match);
	return textOut.join("");
};

//TiddlyWiki.prototype.slicesRE = /(?:^([\'\/]{0,2})~?([\.\w]+)\:\1[\t\x20]*([^\n]+)[\t\x20]*$)|(?:^\|([\'\/]{0,2})~?([\.\w]+)\:?\4\|[\t\x20]*([^\n]+)[\t\x20]*\|$)/gm;
TiddlyWiki.prototype.slicesRE = /(?:^([\'\/]{0,2})~?([\.\w]+)\:\1[\t\x20]*([^\n]*)[\t\x20]*$)|(?:^\|([\'\/]{0,2})~?([\.\w]+)\:?\4\|[\t\x20]*([^\|\n]*)[\t\x20]*\|$)/gm;
// @internal
TiddlyWiki.prototype.calcAllSlices = function(title)
{
	var slices = {};
	var text = this.getTiddlerText(title,"");
	this.slicesRE.lastIndex = 0;
	var m = this.slicesRE.exec(text);
	while(m) {
		if(m[2])
			slices[m[2]] = m[3];
		else
			slices[m[5]] = m[6];
		m = this.slicesRE.exec(text);
	}
	return slices;
};

// Returns the slice of text of the given name
TiddlyWiki.prototype.getTiddlerSlice = function(title,sliceName)
{
	var slices = this.slices[title];
	if(!slices) {
		slices = this.calcAllSlices(title);
		this.slices[title] = slices;
	}
	return slices[sliceName];
};

// Build an hashmap of the specified named slices of a tiddler
TiddlyWiki.prototype.getTiddlerSlices = function(title,sliceNames)
{
	var t,r = {};
	for(t=0; t<sliceNames.length; t++) {
		var slice = this.getTiddlerSlice(title,sliceNames[t]);
		if(slice)
			r[sliceNames[t]] = slice;
	}
	return r;
};

TiddlyWiki.prototype.suspendNotifications = function()
{
	this.notificationLevel--;
};

TiddlyWiki.prototype.resumeNotifications = function()
{
	this.notificationLevel++;
};

// Invoke the notification handlers for a particular tiddler
TiddlyWiki.prototype.notify = function(title,doBlanket)
{
	if(!this.notificationLevel) {
	    var t;
		for(t=0; t<this.namedNotifications.length; t++) {
			var n = this.namedNotifications[t];
			if((n.name == null && doBlanket) || (n.name == title))
				n.notify(title);
		}
	}
};

// Invoke the notification handlers for all tiddlers
TiddlyWiki.prototype.notifyAll = function()
{
	if(!this.notificationLevel) {
	    var t;
		for(t=0; t<this.namedNotifications.length; t++) {
			var n = this.namedNotifications[t];
			if(n.name)
				n.notify(n.name);
		}
	}
};

// Add a notification handler to a tiddler
TiddlyWiki.prototype.addNotification = function(title,fn)
{
	var i;
	for(i=0; i<this.namedNotifications.length; i++) {
		if((this.namedNotifications[i].name == title) && (this.namedNotifications[i].notify == fn))
			return this;
	}
	this.namedNotifications.push({name: title, notify: fn});
	return this;
};

TiddlyWiki.prototype.removeTiddler = function(title)
{
	var tiddler = this.fetchTiddler(title);
	if(tiddler) {
		this.deleteTiddler(title);
		this.notify(title,true);
		this.setDirty(true);
	}
};

// Reset the sync status of a freshly synced tiddler
TiddlyWiki.prototype.resetTiddler = function(title)
{
	var tiddler = this.fetchTiddler(title);
	if(tiddler) {
		tiddler.clearChangeCount();
		this.notify(title,true);
		this.setDirty(true);
	}
};

TiddlyWiki.prototype.setTiddlerTag = function(title,status,tag)
{
	var tiddler = this.fetchTiddler(title);
	if(tiddler) {
		var t = tiddler.tags.indexOf(tag);
		if(t != -1)
			tiddler.tags.splice(t,1);
		if(status)
			tiddler.tags.push(tag);
		tiddler.changed();
		tiddler.incChangeCount();
		this.notify(title,true);
		this.setDirty(true);
	}
};

TiddlyWiki.prototype.addTiddlerFields = function(title,fields)
{
	var tiddler = this.fetchTiddler(title);
	if(!tiddler)
		return;
	merge(tiddler.fields,fields);
	tiddler.changed();
	tiddler.incChangeCount();
	this.notify(title,true);
	this.setDirty(true);
};

// Store tiddler in TiddlyWiki instance
TiddlyWiki.prototype.saveTiddler = function(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created,creator)
{
	var tiddler;
	if(title instanceof Tiddler) {
		tiddler = title;
		title = tiddler.title;
		newTitle = title;
	} else {
		tiddler = this.fetchTiddler(title);
		if(tiddler) {
			created = created || tiddler.created; // Preserve created date
			creator = creator || tiddler.creator;
			this.deleteTiddler(title);
		} else {
			created = created || modified;
			tiddler = new Tiddler();
		}
		fields = merge(merge({},fields),config.defaultCustomFields,true);
		tiddler.set(newTitle,newBody,modifier,modified,tags,created,fields,creator);
	}
	this.addTiddler(tiddler);
	if(clearChangeCount)
		tiddler.clearChangeCount();
	else
		tiddler.incChangeCount();
	if(title != newTitle)
		this.notify(title,true);
	this.notify(newTitle,true);
	this.setDirty(true);
	return tiddler;
};

TiddlyWiki.prototype.incChangeCount = function(title)
{
	var tiddler = this.fetchTiddler(title);
	if(tiddler)
		tiddler.incChangeCount();
};

TiddlyWiki.prototype.getLoader = function()
{
	if(!this.loader)
		this.loader = new TW21Loader();
	return this.loader;
};

TiddlyWiki.prototype.getSaver = function()
{
	if(!this.saver)
		this.saver = new TW21Saver();
	return this.saver;
};

// Return all tiddlers formatted as an HTML string
TiddlyWiki.prototype.allTiddlersAsHtml = function()
{
	return this.getSaver().externalize(store);
};

// Load contents of a TiddlyWiki from an HTML DIV
TiddlyWiki.prototype.loadFromDiv = function(src,idPrefix,noUpdate)
{
	this.idPrefix = idPrefix;
	var storeElem = (typeof src == "string") ? document.getElementById(src) : src;
	if(!storeElem)
		return;
	var tiddlers = this.getLoader().loadTiddlers(this,storeElem.childNodes);
	this.setDirty(false);
	if(!noUpdate) {
		var i;
		for(i = 0;i<tiddlers.length; i++)
			tiddlers[i].changed();
	}
	jQuery(document).trigger("loadTiddlers");
};

// Load contents of a TiddlyWiki from a string
// Returns null if there's an error
TiddlyWiki.prototype.importTiddlyWiki = function(text)
{
	var posDiv = locateStoreArea(text);
	if(!posDiv)
		return null;
	var content = "<" + "html><" + "body>" + text.substring(posDiv[0],posDiv[1] + endSaveArea.length) + "<" + "/body><" + "/html>";
	// Create the iframe
	var iframe = document.createElement("iframe");
	iframe.style.display = "none";
	document.body.appendChild(iframe);
	var doc = iframe.document;
	if(iframe.contentDocument)
		doc = iframe.contentDocument; // For NS6
	else if(iframe.contentWindow)
		doc = iframe.contentWindow.document; // For IE5.5 and IE6
	// Put the content in the iframe
	doc.open();
	doc.writeln(content);
	doc.close();
	// Load the content into a TiddlyWiki() object
	var storeArea = doc.getElementById("storeArea");
	this.loadFromDiv(storeArea,"store");
	// Get rid of the iframe
	iframe.parentNode.removeChild(iframe);
	return this;
};

TiddlyWiki.prototype.updateTiddlers = function()
{
	this.tiddlersUpdated = true;
	this.forEachTiddler(function(title,tiddler) {
		tiddler.changed();
	});
};

// Return an array of tiddlers matching a search regular expression
TiddlyWiki.prototype.search = function(searchRegExp,sortField,excludeTag,match)
{
	var candidates = this.reverseLookup("tags",excludeTag,!!match);
	var t,results = [];
	for(t=0; t<candidates.length; t++) {
		if((candidates[t].title.search(searchRegExp) != -1) || (candidates[t].text.search(searchRegExp) != -1))
			results.push(candidates[t]);
	}
	if(!sortField)
		sortField = "title";
	results.sort(function(a,b) {return a[sortField] < b[sortField] ? -1 : (a[sortField] == b[sortField] ? 0 : +1);});
	return results;
};

// Returns a list of all tags in use
//   excludeTag - if present, excludes tags that are themselves tagged with excludeTag
// Returns an array of arrays where [tag][0] is the name of the tag and [tag][1] is the number of occurances
TiddlyWiki.prototype.getTags = function(excludeTag)
{
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
	    var g,c;
		for(g=0; g<tiddler.tags.length; g++) {
			var tag = tiddler.tags[g];
			var n = true;
			for(c=0; c<results.length; c++) {
				if(results[c][0] == tag) {
					n = false;
					results[c][1]++;
				}
			}
			if(n && excludeTag) {
				var t = this.fetchTiddler(tag);
				if(t && t.isTagged(excludeTag))
					n = false;
			}
			if(n)
				results.push([tag,1]);
		}
	});
	results.sort(function(a,b) {return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : (a[0].toLowerCase() == b[0].toLowerCase() ? 0 : +1);});
	return results;
};

// Return an array of the tiddlers that are tagged with a given tag
TiddlyWiki.prototype.getTaggedTiddlers = function(tag,sortField)
{
	return this.reverseLookup("tags",tag,true,sortField);
};

TiddlyWiki.prototype.getValueTiddlers = function(field,value,sortField)
{
	return this.reverseLookup(field,value,true,sortField);
};

// Return an array of the tiddlers that link to a given tiddler
TiddlyWiki.prototype.getReferringTiddlers = function(title,unusedParameter,sortField)
{
	if(!this.tiddlersUpdated)
		this.updateTiddlers();
	return this.reverseLookup("links",title,true,sortField);
};

// Return an array of the tiddlers that do or do not have a specified entry in the specified storage array (ie, "links" or "tags")
// lookupMatch == true to match tiddlers, false to exclude tiddlers
TiddlyWiki.prototype.reverseLookup = function(lookupField,lookupValue,lookupMatch,sortField)
{
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
		var f = !lookupMatch;
		var values;
		if(["links", "tags"].contains(lookupField)) {
			values = tiddler[lookupField];
		} else {
			var accessor = TiddlyWiki.standardFieldAccess[lookupField];
			if(accessor) {
				values = [ accessor.get(tiddler) ];
			} else {
				values = tiddler.fields[lookupField] ? [tiddler.fields[lookupField]] : [];
			}
		}
		var lookup;
		for(lookup=0; lookup<values.length; lookup++) {
			if(values[lookup] == lookupValue)
				f = lookupMatch;
		}
		if(f)
			results.push(tiddler);
	});
	if(!sortField)
		sortField = "title";
	return this.sortTiddlers(results,sortField);
};

// Return the tiddlers as a sorted array
TiddlyWiki.prototype.getTiddlers = function(field,excludeTag)
{
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
		if(excludeTag == undefined || !tiddler.isTagged(excludeTag))
			results.push(tiddler);
	});
	if(field)
		results.sort(function(a,b) {return a[field] < b[field] ? -1 : (a[field] == b[field] ? 0 : +1);});
	return results;
};

// Return array of names of tiddlers that are referred to but not defined
TiddlyWiki.prototype.getMissingLinks = function()
{
	if(!this.tiddlersUpdated)
		this.updateTiddlers();
	var results = [];
	this.forEachTiddler(function (title,tiddler) {
		if(tiddler.isTagged("excludeMissing") || tiddler.isTagged("systemConfig"))
			return;
		var n;
		for(n=0; n<tiddler.links.length;n++) {
			var link = tiddler.links[n];
			if(this.getTiddlerText(link,null) == null && !this.isShadowTiddler(link) && !config.macros[link])
				results.pushUnique(link);
		}
	});
	results.sort();
	return results;
};

// Return an array of names of tiddlers that are defined but not referred to
TiddlyWiki.prototype.getOrphans = function()
{
	var results = [];
	this.forEachTiddler(function (title,tiddler) {
		if(this.getReferringTiddlers(title).length == 0 && !tiddler.isTagged("excludeLists"))
			results.push(title);
	});
	results.sort();
	return results;
};

// Return an array of names of all the shadow tiddlers
TiddlyWiki.prototype.getShadowed = function()
{
	var t,results = [];
	for(t in config.shadowTiddlers) {
		if(this.isShadowTiddler(t))
			results.push(t);
	}
	results.sort();
	return results;
};

// Return an array of tiddlers that have been touched since they were downloaded or created
TiddlyWiki.prototype.getTouched = function()
{
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
		if(tiddler.isTouched())
			results.push(tiddler);
		});
	results.sort();
	return results;
};

// Resolves a Tiddler reference or tiddler title into a Tiddler object, or null if it doesn't exist
TiddlyWiki.prototype.resolveTiddler = function(tiddler)
{
	var t = (typeof tiddler == "string") ? this.getTiddler(tiddler) : tiddler;
	return t instanceof Tiddler ? t : null;
};

// Sort a list of tiddlers
TiddlyWiki.prototype.sortTiddlers = function(tiddlers,field)
{
	var asc = +1;
	switch(field.substr(0,1)) {
	case "-":
		asc = -1;
		field = field.substr(1);
		break;
	case "+":
		field = field.substr(1);
		break;
	}
	if(TiddlyWiki.standardFieldAccess[field]) {
		if(field=="title") {
			tiddlers.sort(function(a,b) {return a[field].toLowerCase() < b[field].toLowerCase() ? -asc : (a[field].toLowerCase() == b[field].toLowerCase() ? 0 : asc);});
		} else {
			tiddlers.sort(function(a,b) {return a[field] < b[field] ? -asc : (a[field] == b[field] ? 0 : asc);});
		}
	} else {
		tiddlers.sort(function(a,b) {return a.fields[field] < b.fields[field] ? -asc : (a.fields[field] == b.fields[field] ? 0 : +asc);});
	}
	return tiddlers;
};

//--
//-- Filter a list of tiddlers
//--

config.filters = {
	tiddler: function(results,match) {
		var title = match[1]||match[4];
		var tiddler = this.fetchTiddler(title);
		if(tiddler) {
			results.pushUnique(tiddler);
		} else if(this.isShadowTiddler(title)) {
			tiddler = new Tiddler();
			tiddler.set(title,this.getTiddlerText(title));
			results.pushUnique(tiddler);
		} else {
			results.pushUnique(new Tiddler(title));
		}
		return results;
	},
	tag: function(results,match) {
		var m,matched = this.getTaggedTiddlers(match[3]);
		for(m=0; m<matched.length; m++) {
			results.pushUnique(matched[m]);
		}
		return results;
	},
	sort: function(results,match) {
		return this.sortTiddlers(results,match[3]);
	},
	limit: function(results,match) {
		return results.slice(0,parseInt(match[3],10));
	},
	field: function(results,match) {
		var m,matched = this.getValueTiddlers(match[2],match[3]);
		for (m = 0; m < matched.length; m++) {
			results.pushUnique(matched[m]);
		}
		return results;
	}
};

// Filter a list of tiddlers
TiddlyWiki.prototype.filterTiddlers = function(filter)
{
	var re = /([^\s\[\]]+)|(?:\[([ \w\.\-]+)\[([^\]]+)\]\])|(?:\[\[([^\]]+)\]\])/mg;

	var results = [];
	if(filter) {
		var match = re.exec(filter);
		while(match) {
			var handler = (match[1]||match[4])?'tiddler':config.filters[match[2]]?match[2]:'field';
			results = config.filters[handler].call(this,results,match);
			match = re.exec(filter);
		}
	}
	return results;
};
// Returns true if path is a valid field name (path),
// i.e. a sequence of identifiers, separated by "."
TiddlyWiki.isValidFieldName = function(name)
{
	var match = /[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*/.exec(name);
	return match && (match[0] == name);
};

// Throws an exception when name is not a valid field name.
TiddlyWiki.checkFieldName = function(name)
{
	if(!TiddlyWiki.isValidFieldName(name))
		throw config.messages.invalidFieldName.format([name]);
};

function StringFieldAccess(n,readOnly)
{
	this.set = readOnly ?
			function(t,v) {if(v != t[n]) throw config.messages.fieldCannotBeChanged.format([n]);} :
			function(t,v) {if(v != t[n]) {t[n] = v; return true;}};
	this.get = function(t) {return t[n];};
}

function DateFieldAccess(n)
{
	this.set = function(t,v) {
		var d = v instanceof Date ? v : Date.convertFromYYYYMMDDHHMM(v);
		if(d != t[n]) {
			t[n] = d; return true;
		}
	};
	this.get = function(t) {return t[n].convertToYYYYMMDDHHMM();};
}

function LinksFieldAccess(n)
{
	this.set = function(t,v) {
		var s = (typeof v == "string") ? v.readBracketedList() : v;
		if(s.toString() != t[n].toString()) {
			t[n] = s; return true;
		}
	};
	this.get = function(t) {return String.encodeTiddlyLinkList(t[n]);};
}

TiddlyWiki.standardFieldAccess = {
	// The set functions return true when setting the data has changed the value.
	"title":    new StringFieldAccess("title",true),
	// Handle the "tiddler" field name as the title
	"tiddler":  new StringFieldAccess("title",true),
	"text":     new StringFieldAccess("text"),
	"modifier": new StringFieldAccess("modifier"),
	"modified": new DateFieldAccess("modified"),
	"creator":  new StringFieldAccess("creator"),
	"created":  new DateFieldAccess("created"),
	"tags":     new LinksFieldAccess("tags")
};

TiddlyWiki.isStandardField = function(name)
{
	return TiddlyWiki.standardFieldAccess[name] != undefined;
};

// Sets the value of the given field of the tiddler to the value.
// Setting an ExtendedField's value to null or undefined removes the field.
// Setting a namespace to undefined removes all fields of that namespace.
// The fieldName is case-insensitive.
// All values will be converted to a string value.
TiddlyWiki.prototype.setValue = function(tiddler,fieldName,value)
{
	TiddlyWiki.checkFieldName(fieldName);
	var t = this.resolveTiddler(tiddler);
	if(!t)
		return;
	fieldName = fieldName.toLowerCase();
	var isRemove = (value === undefined) || (value === null);
	var accessor = TiddlyWiki.standardFieldAccess[fieldName];
	if(accessor) {
		if(isRemove)
			// don't remove StandardFields
			return;
		var h = TiddlyWiki.standardFieldAccess[fieldName];
		if(!h.set(t,value))
			return;
	} else {
		var oldValue = t.fields[fieldName];
		if(isRemove) {
			if(oldValue !== undefined) {
				// deletes a single field
				delete t.fields[fieldName];
			} else {
				// no concrete value is defined for the fieldName
				// so we guess this is a namespace path.
				// delete all fields in a namespace
				var re = new RegExp("^"+fieldName+"\\.");
				var dirty = false;
				var n;
				for(n in t.fields) {
					if(n.match(re)) {
						delete t.fields[n];
						dirty = true;
					}
				}
				if(!dirty)
					return;
			}
		} else {
			// the "normal" set case. value is defined (not null/undefined)
			// For convenience provide a nicer conversion Date->String
			value = value instanceof Date ? value.convertToYYYYMMDDHHMMSSMMM() : String(value);
			if(oldValue == value)
				return;
			t.fields[fieldName] = value;
		}
	}
	// When we are here the tiddler/store really was changed.
	this.notify(t.title,true);
	if(!fieldName.match(/^temp\./))
		this.setDirty(true);
};

// Returns the value of the given field of the tiddler.
// The fieldName is case-insensitive.
// Will only return String values (or undefined).
TiddlyWiki.prototype.getValue = function(tiddler,fieldName)
{
	var t = this.resolveTiddler(tiddler);
	if(!t)
		return undefined;
	if(fieldName.indexOf(config.textPrimitives.sectionSeparator) === 0 || fieldName.indexOf(config.textPrimitives.sliceSeparator) === 0) {
		var sliceType = fieldName.substr(0, 2);
		var sliceName = fieldName.substring(2);
		return store.getTiddlerText("%0%1%2".format(t.title,sliceType,sliceName));
	} else {
		fieldName = fieldName.toLowerCase();
		var accessor = TiddlyWiki.standardFieldAccess[fieldName];
		if(accessor) {
			return accessor.get(t);
		}
	}
	return t.fields[fieldName];
};

// Calls the callback function for every field in the tiddler.
// When callback function returns a non-false value the iteration stops
// and that value is returned.
// The order of the fields is not defined.
// @param callback a function(tiddler,fieldName,value).
TiddlyWiki.prototype.forEachField = function(tiddler,callback,onlyExtendedFields)
{
	var t = this.resolveTiddler(tiddler);
	if(!t)
		return undefined;
	var n,result;
	for(n in t.fields) {
		result = callback(t,n,t.fields[n]);
		if(result)
			return result;
		}
	if(onlyExtendedFields)
		return undefined;
	for(n in TiddlyWiki.standardFieldAccess) {
		if(n != "tiddler") {
			// even though the "title" field can also be referenced through the name "tiddler"
			// we only visit this field once.
			result = callback(t,n,TiddlyWiki.standardFieldAccess[n].get(t));
			if(result)
				return result;
		}
	}
	return undefined;
};

//--
//-- Story functions
//--

function Story(containerId,idPrefix)
{
	this.container = containerId;
	this.idPrefix = idPrefix;
	this.highlightRegExp = null;
	this.tiddlerId = function(title) {
		title = title.replace(/_/g, "__").replace(/ /g, "_");
		var id = this.idPrefix + title;
		return id==this.container ? this.idPrefix + "_" + title : id;
	};
	this.containerId = function() {
		return this.container;
	};
}

Story.prototype.getTiddler = function(title)
{
	return document.getElementById(this.tiddlerId(title));
};

Story.prototype.getContainer = function()
{
	return document.getElementById(this.containerId());
};

Story.prototype.forEachTiddler = function(fn)
{
	var place = this.getContainer();
	if(!place)
		return;
	var e = place.firstChild;
	while(e) {
		var n = e.nextSibling;
		var title = e.getAttribute("tiddler");
		if(title) {
			fn.call(this,title,e);
		}
		e = n;
	}
};

Story.prototype.displayDefaultTiddlers = function()
{
	this.displayTiddlers(null,store.filterTiddlers(store.getTiddlerText("DefaultTiddlers")),null,null,null,String.encodeHashMap(config.defaultCustomFields));
};

Story.prototype.displayTiddlers = function(srcElement,titles,template,animate,unused,customFields,toggle)
{
	var t;
	for(t = titles.length-1;t>=0;t--)
		this.displayTiddler(srcElement,titles[t],template,animate,unused,customFields);
};

Story.prototype.displayTiddler = function(srcElement,tiddler,template,animate,unused,customFields,toggle,animationSrc)
{
	var title = (tiddler instanceof Tiddler) ? tiddler.title : tiddler;
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem) {
		if(toggle) {
			if(tiddlerElem.getAttribute("dirty") != "true")
				this.closeTiddler(title,true);
		} else {
			this.refreshTiddler(title,template,false,customFields);
		}
	} else {
		var place = this.getContainer();
		var before = this.positionTiddler(srcElement);
		tiddlerElem = this.createTiddler(place,before,title,template,customFields);
	}
	if(animationSrc && typeof animationSrc !== "string") {
		srcElement = animationSrc;
	}
	if(srcElement && typeof srcElement !== "string") {
		if(config.options.chkAnimate && (animate == undefined || animate == true) && anim && typeof Zoomer == "function" && typeof Scroller == "function")
			anim.startAnimating(new Zoomer(title,srcElement,tiddlerElem),new Scroller(tiddlerElem));
		else
			window.scrollTo(0,ensureVisible(tiddlerElem));
	}
	return tiddlerElem;
};

Story.prototype.positionTiddler = function(srcElement)
{
	var place = this.getContainer();
	var before = null;
	if(typeof srcElement == "string") {
		switch(srcElement) {
		case "top":
			before = place.firstChild;
			break;
		case "bottom":
			before = null;
			break;
		}
	} else {
		var after = this.findContainingTiddler(srcElement);
		if(after == null) {
			before = place.firstChild;
		} else if(after.nextSibling) {
			before = after.nextSibling;
			if(before.nodeType != 1)
				before = null;
		}
	}
	return before;
};

Story.prototype.createTiddler = function(place,before,title,template,customFields)
{
	var tiddlerElem = createTiddlyElement(null,"div",this.tiddlerId(title),"tiddler");
	tiddlerElem.setAttribute("refresh","tiddler");
	if(customFields)
		tiddlerElem.setAttribute("tiddlyFields",customFields);
	place.insertBefore(tiddlerElem,before);
	var defaultText = null;
	if(!store.tiddlerExists(title) && !store.isShadowTiddler(title))
		defaultText = this.loadMissingTiddler(title,customFields);
	this.refreshTiddler(title,template,false,customFields,defaultText);
	return tiddlerElem;
};

Story.prototype.loadMissingTiddler = function(title,fields,callback)
{
	var getTiddlerCallback = function(context)
	{
		if(context.status) {
			var t = context.tiddler;
			if(!t.created)
				t.created = new Date();
			if(!t.modified)
				t.modified = t.created;
			var dirty = store.isDirty();
			context.tiddler = store.saveTiddler(t.title,t.title,t.text,t.modifier,t.modified,t.tags,t.fields,true,t.created,t.creator);
			if(window.location.protocol != "file:")
				store.setDirty(dirty);
			autoSaveChanges();
		} else {
			story.refreshTiddler(context.title,null,true);
		}
		context.adaptor.close();
		if(callback) {
			callback(context);
		}
	};
	var tiddler = new Tiddler(title);
	tiddler.fields = typeof fields == "string" ? fields.decodeHashMap() : fields||{};
	var context = {serverType:tiddler.getServerType()};
	if(!context.serverType)
		return "";
	context.host = tiddler.fields['server.host'];
	context.workspace = tiddler.fields['server.workspace'];
	var adaptor = new config.adaptors[context.serverType]();
	adaptor.getTiddler(title,context,null,getTiddlerCallback);
	return config.messages.loadingMissingTiddler.format([title,context.serverType,context.host,context.workspace]);
};

Story.prototype.chooseTemplateForTiddler = function(title,template)
{
	if(!template)
		template = DEFAULT_VIEW_TEMPLATE;
	if(template == DEFAULT_VIEW_TEMPLATE || template == DEFAULT_EDIT_TEMPLATE)
		template = config.tiddlerTemplates[template];
	return template;
};

Story.prototype.getTemplateForTiddler = function(title,template,tiddler)
{
	return store.getRecursiveTiddlerText(template,null,10);
};

Story.prototype.refreshTiddler = function(title,template,force,customFields,defaultText)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem) {
		if(tiddlerElem.getAttribute("dirty") == "true" && !force)
			return tiddlerElem;
		template = this.chooseTemplateForTiddler(title,template);
		var currTemplate = tiddlerElem.getAttribute("template");
		if((template != currTemplate) || force) {
			var tiddler = store.getTiddler(title);
			if(!tiddler) {
				tiddler = new Tiddler();
				if(store.isShadowTiddler(title)) {
					var tags = [];
					tiddler.set(title,store.getTiddlerText(title),config.views.wikified.shadowModifier,version.date,tags,version.date);
				} else {
					var text = template=="EditTemplate" ?
								config.views.editor.defaultText.format([title]) :
								config.views.wikified.defaultText.format([title]);
					text = defaultText || text;
					var fields = customFields ? customFields.decodeHashMap() : null;
					tiddler.set(title,text,config.views.wikified.defaultModifier,version.date,[],version.date,fields);
				}
			}
			tiddlerElem.setAttribute("tags",tiddler.tags.join(" "));
			tiddlerElem.setAttribute("tiddler",title);
			tiddlerElem.setAttribute("template",template);
			tiddlerElem.onmouseover = this.onTiddlerMouseOver;
			tiddlerElem.onmouseout = this.onTiddlerMouseOut;
			tiddlerElem.ondblclick = this.onTiddlerDblClick;
			tiddlerElem[window.event?"onkeydown":"onkeypress"] = this.onTiddlerKeyPress;
			tiddlerElem.innerHTML = this.getTemplateForTiddler(title,template,tiddler);
			applyHtmlMacros(tiddlerElem,tiddler);
			if(store.getTaggedTiddlers(title).length > 0)
				jQuery(tiddlerElem).addClass("isTag");
			else
				jQuery(tiddlerElem).removeClass("isTag");
			if(store.tiddlerExists(title)) {
				jQuery(tiddlerElem).removeClass("shadow");
				jQuery(tiddlerElem).removeClass("missing");
			} else {
				jQuery(tiddlerElem).addClass(store.isShadowTiddler(title) ? "shadow" : "missing");
			}
			if(customFields)
				this.addCustomFields(tiddlerElem,customFields);
		}
	}
	return tiddlerElem;
};

Story.prototype.addCustomFields = function(place,customFields)
{
	var fields = customFields.decodeHashMap();
	var w = createTiddlyElement(place,"div",null,"customFields");
	w.style.display = "none";
	var t;
	for(t in fields) {
		var e = document.createElement("input");
		e.setAttribute("type","text");
		e.setAttribute("value",fields[t]);
		w.appendChild(e);
		e.setAttribute("edit",t);
	}
};

Story.prototype.refreshAllTiddlers = function(force)
{
	var e = this.getContainer().firstChild;
	while(e) {
		var template = e.getAttribute("template");
		if(template && e.getAttribute("dirty") != "true") {
			this.refreshTiddler(e.getAttribute("tiddler"),force ? null : template,true);
		}
		e = e.nextSibling;
	}
};

Story.prototype.onTiddlerMouseOver = function(e)
{
	jQuery(this).addClass("selected");
};

Story.prototype.onTiddlerMouseOut = function(e)
{
	jQuery(this).removeClass("selected");
};

Story.prototype.onTiddlerDblClick = function(ev)
{
	var e = ev || window.event;
	var target = resolveTarget(e);
	if(target && target.nodeName.toLowerCase() != "input" && target.nodeName.toLowerCase() != "textarea") {
		if(document.selection && document.selection.empty)
			document.selection.empty();
		config.macros.toolbar.invokeCommand(this,"defaultCommand",e);
		e.cancelBubble = true;
		if(e.stopPropagation) e.stopPropagation();
		return true;
	}
	return false;
};

Story.prototype.onTiddlerKeyPress = function(ev)
{
	var e = ev || window.event;
	clearMessage();
	var consume = false;
	var title = this.getAttribute("tiddler");
	var target = resolveTarget(e);
	switch(e.keyCode) {
	case 9: // Tab
		var ed = story.getTiddlerField(title,"text");
		if(target.tagName.toLowerCase() == "input" && ed.value==config.views.editor.defaultText.format([title])) {
			// moving from input field and editor still contains default text, so select it
			ed.focus();
			ed.select();
			consume = true;
		}
		if(config.options.chkInsertTabs && target.tagName.toLowerCase() == "textarea") {
			replaceSelection(target,String.fromCharCode(9));
			consume = true;
		}
		if(config.isOpera) {
			target.onblur = function() {
				this.focus();
				this.onblur = null;
			};
		}
		break;
	case 13: // Ctrl-Enter
	case 10: // Ctrl-Enter on IE PC
	case 77: // Ctrl-Enter is "M" on some platforms
		if(e.ctrlKey) {
			blurElement(this);
			config.macros.toolbar.invokeCommand(this,"defaultCommand",e);
			consume = true;
		}
		break;
	case 27: // Escape
		blurElement(this);
		config.macros.toolbar.invokeCommand(this,"cancelCommand",e);
		consume = true;
		break;
	}
	e.cancelBubble = consume;
	if(consume) {
		if(e.stopPropagation) e.stopPropagation(); // Stop Propagation
		e.returnValue = true; // Cancel The Event in IE
		if(e.preventDefault ) e.preventDefault(); // Cancel The Event in Moz
	}
	return !consume;
};

Story.prototype.getTiddlerField = function(title,field)
{
	var tiddlerElem = this.getTiddler(title);
	var e = null;
	if(tiddlerElem) {
		var t,children = tiddlerElem.getElementsByTagName("*");
		for(t=0; t<children.length; t++) {
			var c = children[t];
			if(c.tagName.toLowerCase() == "input" || c.tagName.toLowerCase() == "textarea") {
				if(!e)
					e = c;
				if(c.getAttribute("edit") == field)
					e = c;
			}
		}
	}
	return e;
};

Story.prototype.focusTiddler = function(title,field)
{
	var e = this.getTiddlerField(title,field);
	if(e) {
		e.focus();
		e.select();
	}
};

Story.prototype.blurTiddler = function(title)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem && tiddlerElem.focus && tiddlerElem.blur) {
		tiddlerElem.focus();
		tiddlerElem.blur();
	}
};

Story.prototype.setTiddlerField = function(title,tag,mode,field)
{
	var c = this.getTiddlerField(title,field);
	var tags = c.value.readBracketedList();
	tags.setItem(tag,mode);
	c.value = String.encodeTiddlyLinkList(tags);
};

Story.prototype.setTiddlerTag = function(title,tag,mode)
{
	this.setTiddlerField(title,tag,mode,"tags");
};

Story.prototype.closeTiddler = function(title,animate,unused)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem) {
		clearMessage();
		this.scrubTiddler(tiddlerElem);
		if(config.options.chkAnimate && animate && anim && typeof Slider == "function")
			anim.startAnimating(new Slider(tiddlerElem,false,null,"all"));
		else {
			jQuery(tiddlerElem).remove();
		}
	}
};

Story.prototype.scrubTiddler = function(tiddlerElem)
{
	tiddlerElem.id = null;
};

Story.prototype.setDirty = function(title,dirty)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem)
		tiddlerElem.setAttribute("dirty",dirty ? "true" : "false");
};

Story.prototype.isDirty = function(title)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem)
		return tiddlerElem.getAttribute("dirty") == "true";
	return null;
};

Story.prototype.areAnyDirty = function()
{
	var r = false;
	this.forEachTiddler(function(title,element) {
		if(this.isDirty(title))
			r = true;
	});
	return r;
};

Story.prototype.closeAllTiddlers = function(exclude)
{
	clearMessage();
	this.forEachTiddler(function(title,element) {
		if((title != exclude) && element.getAttribute("dirty") != "true")
			this.closeTiddler(title);
	});
	window.scrollTo(0,ensureVisible(this.container));
};

Story.prototype.isEmpty = function()
{
	var place = this.getContainer();
	return place && place.firstChild == null;
};

Story.prototype.search = function(text,useCaseSensitive,useRegExp)
{
	this.closeAllTiddlers();
	highlightHack = new RegExp(useRegExp ? text : text.escapeRegExp(),useCaseSensitive ? "mg" : "img");
	var matches = store.search(highlightHack,"title","excludeSearch");
	this.displayTiddlers(null,matches);
	highlightHack = null;
	var q = useRegExp ? "/" : "'";
	if(matches.length > 0)
		displayMessage(config.macros.search.successMsg.format([matches.length.toString(),q + text + q]));
	else
		displayMessage(config.macros.search.failureMsg.format([q + text + q]));
};

Story.prototype.findContainingTiddler = function(e)
{
	while(e && !jQuery(e).hasClass("tiddler")) {
		e = jQuery(e).hasClass("popup") && Popup.stack[0] ? Popup.stack[0].root : e.parentNode;
	}
	return e;
};

Story.prototype.gatherSaveFields = function(e,fields)
{
	if(e && e.getAttribute) {
		var f = e.getAttribute("edit");
		if(f)
			fields[f] = e.value.replace(/\r/mg,"");
		if(e.hasChildNodes()) {
			var t,c = e.childNodes;
			for(t=0; t<c.length; t++)
				this.gatherSaveFields(c[t],fields);
		}
	}
};

Story.prototype.hasChanges = function(title)
{
	var e = this.getTiddler(title);
	if(e) {
		var fields = {};
		this.gatherSaveFields(e,fields);
		if(store.fetchTiddler(title)) {
		    var n;
			for(n in fields) {
				if(store.getValue(title,n) != fields[n]) //# tiddler changed
					return true;
			}
		} else {
			if(store.isShadowTiddler(title) && store.getShadowTiddlerText(title) == fields.text) { //# not checking for title or tags
				return false;
			} else { //# changed shadow or new tiddler
				return true;
			}
		}
	}
	return false;
};

Story.prototype.saveTiddler = function(title,minorUpdate)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem) {
		var fields = {};
		this.gatherSaveFields(tiddlerElem,fields);
		var newTitle = fields.title || title;
		if(!store.tiddlerExists(newTitle)) {
			newTitle = newTitle.trim();
			var creator = config.options.txtUserName;
		}
		if(store.tiddlerExists(newTitle) && newTitle != title) {
			if(!confirm(config.messages.overwriteWarning.format([newTitle.toString()])))
				return null;
				title = newTitle;
		}
		if(newTitle != title)
			this.closeTiddler(newTitle,false);
		tiddlerElem.id = this.tiddlerId(newTitle);
		tiddlerElem.setAttribute("tiddler",newTitle);
		tiddlerElem.setAttribute("template",DEFAULT_VIEW_TEMPLATE);
		tiddlerElem.setAttribute("dirty","false");
		if(config.options.chkForceMinorUpdate)
			minorUpdate = !minorUpdate;
		if(!store.tiddlerExists(newTitle))
			minorUpdate = false;
		var newDate = new Date();
		if(store.tiddlerExists(title)) {
			var t = store.fetchTiddler(title);
			var extendedFields = t.fields;
			creator = t.creator;
		} else {
			extendedFields = merge({},config.defaultCustomFields);
		}
		var n;
		for(n in fields) {
			if(!TiddlyWiki.isStandardField(n))
				extendedFields[n] = fields[n];
		}
		var tiddler = store.saveTiddler(title,newTitle,fields.text,minorUpdate ? undefined : config.options.txtUserName,minorUpdate ? undefined : newDate,fields.tags,extendedFields,null,null,creator);
		autoSaveChanges(null,[tiddler]);
		return newTitle;
	}
	return null;
};

Story.prototype.permaView = function()
{
	var links = [];
	this.forEachTiddler(function(title,element) {
		links.push(String.encodeTiddlyLink(title));
	});
	var t = encodeURIComponent(links.join(" "));
	if(t == "")
		t = "#";
	if(window.location.hash != t)
		window.location.hash = t;
};

Story.prototype.switchTheme = function(theme)
{
	if(safeMode)
		return;

	var isAvailable = function(title) {
		var s = title ? title.indexOf(config.textPrimitives.sectionSeparator) : -1;
		if(s!=-1)
			title = title.substr(0,s);
		return store.tiddlerExists(title) || store.isShadowTiddler(title);
	};

	var getSlice = function(theme,slice) {
		var r;
		if(readOnly)
			r = store.getTiddlerSlice(theme,slice+"ReadOnly") || store.getTiddlerSlice(theme,"Web"+slice);
		r = r || store.getTiddlerSlice(theme,slice);
		if(r && r.indexOf(config.textPrimitives.sectionSeparator)==0)
			r = theme + r;
		return isAvailable(r) ? r : slice;
	};

	var replaceNotification = function(i,name,theme,slice) {
		var newName = getSlice(theme,slice);
		if(name!=newName && store.namedNotifications[i].name==name) {
			store.namedNotifications[i].name = newName;
			return newName;
		}
		return name;
	};

	var pt = config.refresherData.pageTemplate;
	var vi = DEFAULT_VIEW_TEMPLATE;
	var vt = config.tiddlerTemplates[vi];
	var ei = DEFAULT_EDIT_TEMPLATE;
	var et = config.tiddlerTemplates[ei];

	var i;
	for(i=0; i<config.notifyTiddlers.length; i++) {
		var name = config.notifyTiddlers[i].name;
		switch(name) {
		case "PageTemplate":
			config.refresherData.pageTemplate = replaceNotification(i,config.refresherData.pageTemplate,theme,name);
			break;
		case "StyleSheet":
			removeStyleSheet(config.refresherData.styleSheet);
			config.refresherData.styleSheet = replaceNotification(i,config.refresherData.styleSheet,theme,name);
			break;
		case "ColorPalette":
			config.refresherData.colorPalette = replaceNotification(i,config.refresherData.colorPalette,theme,name);
			break;
		default:
			break;
		}
	}
	config.tiddlerTemplates[vi] = getSlice(theme,"ViewTemplate");
	config.tiddlerTemplates[ei] = getSlice(theme,"EditTemplate");
	if(!startingUp) {
		if(config.refresherData.pageTemplate!=pt || config.tiddlerTemplates[vi]!=vt || config.tiddlerTemplates[ei]!=et) {
			refreshAll();
			this.refreshAllTiddlers(true);
		} else {
			setStylesheet(store.getRecursiveTiddlerText(config.refresherData.styleSheet,"",10),config.refreshers.styleSheet);
		}
		config.options.txtTheme = theme;
		saveOption("txtTheme");
	}
};

//--
//-- Manager UI for groups of tiddlers
//--

config.macros.plugins.handler = function(place,macroName,params,wikifier,paramString)
{
	var wizard = new Wizard();
	wizard.createWizard(place,this.wizardTitle);
	wizard.addStep(this.step1Title,this.step1Html);
	var markList = wizard.getElement("markList");
	var listWrapper = document.createElement("div");
	markList.parentNode.insertBefore(listWrapper,markList);
	listWrapper.setAttribute("refresh","macro");
	listWrapper.setAttribute("macroName","plugins");
	listWrapper.setAttribute("params",paramString);
	this.refresh(listWrapper,paramString);
};

config.macros.plugins.refresh = function(listWrapper,params)
{
	var me = config.macros.plugins;
	var wizard = new Wizard(listWrapper);
	var selectedRows = [];
	ListView.forEachSelector(listWrapper,function(e,rowName) {
			if(e.checked)
				selectedRows.push(e.getAttribute("rowName"));
		});
	jQuery(listWrapper).empty();
	params = params.parseParams("anon");
	var plugins = installedPlugins.slice(0);
	var t,tiddler,p;
	var configTiddlers = store.getTaggedTiddlers("systemConfig");
	for(t=0; t<configTiddlers.length; t++) {
		tiddler = configTiddlers[t];
		if(plugins.findByField("title",tiddler.title) == null) {
			p = getPluginInfo(tiddler);
			p.executed = false;
			p.log.splice(0,0,this.skippedText);
			plugins.push(p);
		}
	}
	for(t=0; t<plugins.length; t++) {
		p = plugins[t];
		p.size = p.tiddler.text ? p.tiddler.text.length : 0;
		p.forced = p.tiddler.isTagged("systemConfigForce");
		p.disabled = p.tiddler.isTagged("systemConfigDisable");
		p.Selected = selectedRows.indexOf(plugins[t].title) != -1;
	}
	if(plugins.length == 0) {
		createTiddlyElement(listWrapper,"em",null,null,this.noPluginText);
		wizard.setButtons([]);
	} else {
		var template = readOnly ? this.listViewTemplateReadOnly : this.listViewTemplate;
		var listView = ListView.create(listWrapper,plugins,template,this.onSelectCommand);
		wizard.setValue("listView",listView);
		if(!readOnly) {
			wizard.setButtons([
				{caption: me.removeLabel, tooltip: me.removePrompt, onClick: me.doRemoveTag},
				{caption: me.deleteLabel, tooltip: me.deletePrompt, onClick: me.doDelete}
			]);
		}
	}
};

config.macros.plugins.doRemoveTag = function(e)
{
	var wizard = new Wizard(this);
	var listView = wizard.getValue("listView");
	var rowNames = ListView.getSelectedRows(listView);
	if(rowNames.length == 0) {
		alert(config.messages.nothingSelected);
	} else {
		var t;
		for(t=0; t<rowNames.length; t++) {
			store.setTiddlerTag(rowNames[t],false,"systemConfig");
		}
		autoSaveChanges();
	}
};

config.macros.plugins.doDelete = function(e)
{
	var wizard = new Wizard(this);
	var listView = wizard.getValue("listView");
	var rowNames = ListView.getSelectedRows(listView);
	if(rowNames.length == 0) {
		alert(config.messages.nothingSelected);
	} else {
		if(confirm(config.macros.plugins.confirmDeleteText.format([rowNames.join(", ")]))) {
			var t;
			for(t=0; t<rowNames.length; t++) {
				store.removeTiddler(rowNames[t]);
				story.closeTiddler(rowNames[t],true);
			}
		}
		autoSaveChanges();
	}
};

//--
//-- Message area
//--

function getMessageDiv()
{
	var msgArea = document.getElementById("messageArea");
	if(!msgArea)
		return null;
	if(!msgArea.hasChildNodes())
		createTiddlyButton(createTiddlyElement(msgArea,"div",null,"messageToolbar"),
			config.messages.messageClose.text,
			config.messages.messageClose.tooltip,
			clearMessage);
	msgArea.style.display = "block";
	return createTiddlyElement(msgArea,"div");
}

function displayMessage(text,linkText)
{
	var e = getMessageDiv();
	if(!e) {
		alert(text);
		return;
	}
	if(linkText) {
		var link = createTiddlyElement(e,"a",null,null,text);
		link.href = linkText;
		link.target = "_blank";
	} else {
		e.appendChild(document.createTextNode(text));
	}
}

function clearMessage()
{
	var msgArea = document.getElementById("messageArea");
	if(msgArea) {
		jQuery(msgArea).empty();
		msgArea.style.display = "none";
	}
	return false;
}

//--
//-- Refresh mechanism
//--

config.notifyTiddlers = [
	{name: "SystemSettings", notify: onSystemSettingsChange},
	{name: "StyleSheetLayout", notify: refreshStyles},
	{name: "StyleSheetColors", notify: refreshStyles},
	{name: "StyleSheet", notify: refreshStyles},
	{name: "StyleSheetPrint", notify: refreshStyles},
	{name: "PageTemplate", notify: refreshPageTemplate},
	{name: "SiteTitle", notify: refreshPageTitle},
	{name: "SiteSubtitle", notify: refreshPageTitle},
	{name: "WindowTitle", notify: refreshPageTitle},
	{name: "ColorPalette", notify: refreshColorPalette},
	{name: null, notify: refreshDisplay}
];

config.refreshers = {
	link: function(e,changeList)
		{
		var title = e.getAttribute("tiddlyLink");
		refreshTiddlyLink(e,title);
		return true;
		},

	tiddler: function(e,changeList)
		{
		var title = e.getAttribute("tiddler");
		var template = e.getAttribute("template");
		if(changeList && (changeList.indexOf && changeList.indexOf(title) != -1) && !story.isDirty(title))
			story.refreshTiddler(title,template,true);
		else
			refreshElements(e,changeList);
		return true;
		},

	content: function(e,changeList)
		{
		var title = e.getAttribute("tiddler");
		var force = e.getAttribute("force");
		var args = e.getAttribute("args");
		if(force != null || changeList == null || (changeList.indexOf && changeList.indexOf(title) != -1)) {
			jQuery(e).empty();
			config.macros.tiddler.transclude(e,title,args);
			return true;
		} else
			return false;
		},

	macro: function(e,changeList)
		{
		var macro = e.getAttribute("macroName");
		var params = e.getAttribute("params");
		if(macro)
			macro = config.macros[macro];
		if(macro && macro.refresh)
			macro.refresh(e,params);
		return true;
		}
};

config.refresherData = {
	styleSheet: "StyleSheet",
	defaultStyleSheet: "StyleSheet",
	pageTemplate: "PageTemplate",
	defaultPageTemplate: "PageTemplate",
	colorPalette: "ColorPalette",
	defaultColorPalette: "ColorPalette"
};

function refreshElements(root,changeList)
{
	var c,nodes = root.childNodes;
	for(c=0; c<nodes.length; c++) {
		var e = nodes[c], type = null;
		if(e.getAttribute && (e.tagName ? e.tagName != "IFRAME" : true))
			type = e.getAttribute("refresh");
		var refresher = config.refreshers[type];
		var refreshed = false;
		if(refresher != undefined)
			refreshed = refresher(e,changeList);
		if(e.hasChildNodes() && !refreshed)
			refreshElements(e,changeList);
	}
}

function applyHtmlMacros(root,tiddler)
{
	var e = root.firstChild;
	while(e) {
		var nextChild = e.nextSibling;
		if(e.getAttribute) {
			var macro = e.getAttribute("macro");
			if(macro) {
				e.removeAttribute("macro");
				var params = "";
				var p = macro.indexOf(" ");
				if(p != -1) {
					params = macro.substr(p+1);
					macro = macro.substr(0,p);
				}
				invokeMacro(e,macro,params,null,tiddler);
			}
		}
		if(e.hasChildNodes())
			applyHtmlMacros(e,tiddler);
		e = nextChild;
	}
}

function refreshPageTemplate(title)
{
	var stash = jQuery("<div/>").appendTo("body").hide()[0];
	var display = story.getContainer();
	var nodes,t;
	if(display) {
		nodes = display.childNodes;
		for(t=nodes.length-1; t>=0; t--)
			stash.appendChild(nodes[t]);
	}
	var wrapper = document.getElementById("contentWrapper");

	var isAvailable = function(title) {
		var s = title ? title.indexOf(config.textPrimitives.sectionSeparator) : -1;
		if(s!=-1)
			title = title.substr(0,s);
		return store.tiddlerExists(title) || store.isShadowTiddler(title);
	};
	if(!title || !isAvailable(title))
		title = config.refresherData.pageTemplate;
	if(!isAvailable(title))
		title = config.refresherData.defaultPageTemplate; //# this one is always avaialable
	wrapper.innerHTML = store.getRecursiveTiddlerText(title,null,10);
	applyHtmlMacros(wrapper);
	refreshElements(wrapper);
	display = story.getContainer();
	jQuery(display).empty();
	if(!display)
		display = createTiddlyElement(wrapper,"div",story.containerId());
	nodes = stash.childNodes;
	for(t=nodes.length-1; t>=0; t--)
		display.appendChild(nodes[t]);
	jQuery(stash).remove();
}

function refreshDisplay(hint)
{
	if(typeof hint == "string")
		hint = [hint];
	var e = document.getElementById("contentWrapper");
	refreshElements(e,hint);
	if(backstage.isPanelVisible()) {
		e = document.getElementById("backstage");
		refreshElements(e,hint);
	}
}

function refreshPageTitle()
{
	document.title = getPageTitle();
}

function getPageTitle()
{
	return wikifyPlainText(store.getTiddlerText("WindowTitle",""),null,tiddler);
}

function refreshStyles(title,doc)
{
	setStylesheet(title == null ? "" : store.getRecursiveTiddlerText(title,"",10),title,doc || document);
}

function refreshColorPalette(title)
{
	if(!startingUp)
		refreshAll();
}

function refreshAll()
{
	refreshPageTemplate();
	refreshDisplay();
	refreshStyles("StyleSheetLayout");
	refreshStyles("StyleSheetColors");
	refreshStyles(config.refresherData.styleSheet);
	refreshStyles("StyleSheetPrint");
}

//--
//-- Option handling
//--

config.optionHandlers = {
	'txt': {
		get: function(name) {return encodeCookie(config.options[name].toString());},
		set: function(name,value) {config.options[name] = decodeCookie(value);}
	},
	'chk': {
		get: function(name) {return config.options[name] ? 'true' : 'false';},
		set: function(name,value) {config.options[name] = value == 'true';}
	}
};

function setOption(name,value)
{
	var optType = name.substr(0,3);
	if(config.optionHandlers[optType] && config.optionHandlers[optType].set)
		config.optionHandlers[optType].set(name,value);
}

// Gets the value of an option as a string. Most code should just read from config.options.* directly
function getOption(name)
{
	var optType = name.substr(0,3);
	return config.optionHandlers[optType] && config.optionHandlers[optType].get ? config.optionHandlers[optType].get(name) : null;
}

function loadOptions()
{
	if(safeMode)
		return;
	loadCookies();
	loadSystemSettings();
}
// @Deprecated; retained for backwards compatibility
var loadOptionsCookie = loadOptions;

function getCookies()
{
	var cookieList = document.cookie.split(';');
	var i,cookies = {};
	for(i=0; i<cookieList.length; i++) {
		var p = cookieList[i].indexOf('=');
		if(p != -1) {
			var name = cookieList[i].substr(0,p).trim();
			var value = cookieList[i].substr(p+1).trim();
			cookies[name] = value;
		}
	}
	return cookies;
}

function loadCookies()
{
	var i,cookies = getCookies();
	if(cookies['TiddlyWiki']) {
		cookies = cookies['TiddlyWiki'].decodeHashMap();
	}
	for(i in cookies) {
		if(config.optionsSource[i] != 'setting') {
			setOption(i,cookies[i]);
		}
	}
}

function loadSystemSettings()
{
	var key,settings = store.calcAllSlices('SystemSettings');
	config.optionsSource = {};
	for(key in settings) {
		setOption(key,settings[key]);
		config.optionsSource[key] = 'setting';
	}
}

function onSystemSettingsChange()
{
	if(!startingUp) {
		loadSystemSettings();
	}
}

function saveOption(name)
{
	if(safeMode)
		return;
	if(name.match(/[()\s]/g, '_')) {
		alert(config.messages.invalidCookie.format([name]));
		return;
	}
	saveCookie(name);
	if(config.optionsSource[name] == 'setting') {
		saveSystemSetting(name,true);
	}
}
// @Deprecated; retained for backwards compatibility
var saveOptionCookie = saveOption;

function removeCookie(name)
{
	document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 UTC; path=/;';
}

function saveCookie(name)
{
	var key,cookies = {};
	for(key in config.options) {
		var value = getOption(key);
		value = value == null ? 'false' : value;
		cookies[key] = value;
	}
	document.cookie = 'TiddlyWiki=' + String.encodeHashMap(cookies) + '; expires=Fri, 1 Jan 2038 12:00:00 UTC; path=/';
	cookies = getCookies();
	var c;
	for(c in cookies) {
		var optType = c.substr(0,3);
		if(config.optionHandlers[optType])
			removeCookie(c);
	}
}

var systemSettingSave;
function commitSystemSettings(storeWasDirty)
{
	if(systemSettingSave) {
		window.clearTimeout(systemSettingSave);
	}
	systemSettingSave = window.setTimeout(function() {
		var tiddler = store.getTiddler('SystemSettings');
		autoSaveChanges(null,[tiddler]);
	}, 1000);
}

function saveSystemSetting(name,saveFile)
{
	var title = 'SystemSettings';
	var slice = store.getTiddlerSlice(title,name);
	if(readOnly || slice === getOption(name)) {
		return; //# don't save if read-only or the option hasn't changed
	}
	var slices = store.calcAllSlices(title);
	var key;
	for(key in config.optionsSource) {
		var value = getOption(key) || '';
		if(slices[key] !== value) {
			slices[key] = value;
		}
	}
	var text = [];
	for(key in slices) {
		text.push('%0: %1'.format([key,slices[key]]));
	}
	text = text.sort().join('\n');
	var storeWasDirty = store.isDirty();
	var tiddler = store.getTiddler(title);
	if(tiddler) {
		tiddler.text = text;
		tiddler = store.saveTiddler(tiddler);
	} else {
		tiddler = store.saveTiddler(title,title,text,'System',new Date(),['excludeLists'],config.defaultCustomFields);
	}
	if(saveFile) {
		commitSystemSettings(storeWasDirty);
	}
}

function encodeCookie(s)
{
	return escape(convertUnicodeToHtmlEntities(s));
}

function decodeCookie(s)
{
	s = unescape(s);
	var re = /&#[0-9]{1,5};/g;
	return s.replace(re,function($0) {return String.fromCharCode(eval($0.replace(/[&#;]/g,'')));});
}

config.macros.option.genericCreate = function(place,type,opt,className,desc)
{
	var typeInfo = config.macros.option.types[type];
	var c = document.createElement(typeInfo.elementType);
	if(typeInfo.typeValue)
		c.setAttribute('type',typeInfo.typeValue);
	c[typeInfo.eventName] = typeInfo.onChange;
	c.setAttribute('option',opt);
	c.className = className || typeInfo.className;
	if(config.optionsDesc[opt])
		c.setAttribute('title',config.optionsDesc[opt]);
	place.appendChild(c);
	if(desc != 'no')
		createTiddlyText(place,config.optionsDesc[opt] || opt);
	c[typeInfo.valueField] = config.options[opt];
	return c;
};

config.macros.option.genericOnChange = function(e)
{
	var opt = this.getAttribute('option');
	if(opt) {
		var optType = opt.substr(0,3);
		var handler = config.macros.option.types[optType];
		if(handler.elementType && handler.valueField)
			config.macros.option.propagateOption(opt,handler.valueField,this[handler.valueField],handler.elementType,this);
	}
	return true;
};

config.macros.option.types = {
	'txt': {
		elementType: 'input',
		valueField: 'value',
		eventName: 'onchange',
		className: 'txtOptionInput',
		create: config.macros.option.genericCreate,
		onChange: config.macros.option.genericOnChange
	},
	'chk': {
		elementType: 'input',
		valueField: 'checked',
		eventName: 'onclick',
		className: 'chkOptionInput',
		typeValue: 'checkbox',
		create: config.macros.option.genericCreate,
		onChange: config.macros.option.genericOnChange
	}
};

config.macros.option.propagateOption = function(opt,valueField,value,elementType,elem)
{
	config.options[opt] = value;
	saveOption(opt);
	var t,nodes = document.getElementsByTagName(elementType);
	for(t=0; t<nodes.length; t++) {
		var optNode = nodes[t].getAttribute('option');
		if(opt == optNode && nodes[t]!=elem)
			nodes[t][valueField] = value;
	}
};

config.macros.option.handler = function(place,macroName,params,wikifier,paramString)
{
	params = paramString.parseParams('anon',null,true,false,false);
	var opt = (params[1] && params[1].name == 'anon') ? params[1].value : getParam(params,'name',null);
	var className = (params[2] && params[2].name == 'anon') ? params[2].value : getParam(params,'class',null);
	var desc = getParam(params,'desc','no');
	var type = opt.substr(0,3);
	var h = config.macros.option.types[type];
	if(h && h.create)
		h.create(place,type,opt,className,desc);
};

config.macros.options.handler = function(place,macroName,params,wikifier,paramString)
{
	params = paramString.parseParams('anon',null,true,false,false);
	var showUnknown = getParam(params,'showUnknown','no');
	var wizard = new Wizard();
	wizard.createWizard(place,this.wizardTitle);
	wizard.addStep(this.step1Title,this.step1Html);
	var markList = wizard.getElement('markList');
	var chkUnknown = wizard.getElement('chkUnknown');
	chkUnknown.checked = showUnknown == 'yes';
	chkUnknown.onchange = this.onChangeUnknown;
	var listWrapper = document.createElement('div');
	markList.parentNode.insertBefore(listWrapper,markList);
	wizard.setValue('listWrapper',listWrapper);
	this.refreshOptions(listWrapper,showUnknown == 'yes');
};

config.macros.options.refreshOptions = function(listWrapper,showUnknown)
{
	var n,opts = [];
	for(n in config.options) {
		var opt = {};
		opt.option = '';
		opt.name = n;
		opt.lowlight = !config.optionsDesc[n];
		opt.description = opt.lowlight ? this.unknownDescription : config.optionsDesc[n];
		if(!opt.lowlight || showUnknown)
			opts.push(opt);
	}
	opts.sort(function(a,b) {return a.name.substr(3) < b.name.substr(3) ? -1 : (a.name.substr(3) == b.name.substr(3) ? 0 : +1);});
	ListView.create(listWrapper,opts,this.listViewTemplate);
	for(n=0; n<opts.length; n++) {
		var type = opts[n].name.substr(0,3);
		var h = config.macros.option.types[type];
		if(h && h.create) {
			h.create(opts[n].colElements['option'],type,opts[n].name,null,'no');
		}
	}
};

config.macros.options.onChangeUnknown = function(e)
{
	var wizard = new Wizard(this);
	var listWrapper = wizard.getValue('listWrapper');
	jQuery(listWrapper).empty();
	config.macros.options.refreshOptions(listWrapper,this.checked);
	return false;
};

// If there are unsaved changes, force the user to confirm before exitting
function confirmExit()
{
	hadConfirmExit = true;
	if((store && store.isDirty && store.isDirty()) || (story && story.areAnyDirty && story.areAnyDirty()))
		return config.messages.confirmExit;
}

// Give the user a chance to save changes before exitting
function checkUnsavedChanges()
{
	if(store && store.isDirty && store.isDirty() && window.hadConfirmExit === false) {
		if(confirm(config.messages.unsavedChangesWarning))
			saveChanges();
	}
}

function saveChanges() {
	// expects to be implemented elsewhere
}

function autoSaveChanges(onlyIfDirty,tiddlers)
{
	if(config.options.chkAutoSave)
		saveChanges(onlyIfDirty,tiddlers);
}
//--
//-- Filesystem utilities
//--
function convertUTF8ToUnicode(u)
{
	return config.browser.isOpera || !window.netscape ? manualConvertUTF8ToUnicode(u) : mozConvertUTF8ToUnicode(u);
}

function manualConvertUTF8ToUnicode(utf)
{
	var uni = utf;
	var src = 0;
	var dst = 0;
	var b1, b2, b3;
	var c;
	while(src < utf.length) {
		b1 = utf.charCodeAt(src++);
		if(b1 < 0x80) {
			dst++;
		} else if(b1 < 0xE0) {
			b2 = utf.charCodeAt(src++);
			c = String.fromCharCode(((b1 & 0x1F) << 6) | (b2 & 0x3F));
			uni = uni.substring(0,dst++).concat(c,utf.substr(src));
		} else {
			b2 = utf.charCodeAt(src++);
			b3 = utf.charCodeAt(src++);
			c = String.fromCharCode(((b1 & 0xF) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F));
			uni = uni.substring(0,dst++).concat(c,utf.substr(src));
		}
	}
	return uni;
}

function mozConvertUTF8ToUnicode(u)
{
	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
		converter.charset = "UTF-8";
	} catch(ex) {
		return manualConvertUTF8ToUnicode(u);
	} // fallback
	var s = converter.ConvertToUnicode(u);
	var fin = converter.Finish();
	return fin.length > 0 ? s+fin : s;
}

function convertUnicodeToFileFormat(s)
{
	return config.browser.isOpera || !window.netscape ? (config.browser.isIE ? convertUnicodeToHtmlEntities(s) : s) : mozConvertUnicodeToUTF8(s);
}

function convertUnicodeToHtmlEntities(s)
{
	var re = /[^\u0000-\u007F]/g;
	return s.replace(re,function($0) {return "&#" + $0.charCodeAt(0).toString() + ";";});
}

function convertUnicodeToUTF8(s)
{
// return convertUnicodeToFileFormat to allow plugin migration
	return convertUnicodeToFileFormat(s);
}

function manualConvertUnicodeToUTF8(s)
{
	return unescape(encodeURIComponent(s));
}

function mozConvertUnicodeToUTF8(s)
{
	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
		converter.charset = "UTF-8";
	} catch(ex) {
		return manualConvertUnicodeToUTF8(s);
	} // fallback
	var u = converter.ConvertFromUnicode(s);
	var fin = converter.Finish();
	return fin.length > 0 ? u + fin : u;
}

function convertUriToUTF8(uri,charSet)
{
	if(window.netscape == undefined || charSet == undefined || charSet == "")
		return uri;
	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		var converter = Components.classes["@mozilla.org/intl/utf8converterservice;1"].getService(Components.interfaces.nsIUTF8ConverterService);
	} catch(ex) {
		return uri;
	}
	return converter.convertURISpecToUTF8(uri,charSet);
}
//--
//-- Server adaptor base class
//--

function AdaptorBase()
{
	this.host = null;
	this.store = null;
	return this;
}

AdaptorBase.prototype.close = function()
{
	return true;
};

AdaptorBase.prototype.fullHostName = function(host)
{
	if(!host)
		return '';
	host = host.trim();
	if(!host.match(/:\/\//))
		host = 'http://' + host;
	if(host.substr(host.length-1) == '/')
		host = host.substr(0,host.length-1);
	return host;
};

AdaptorBase.minHostName = function(host)
{
	return host;
};

AdaptorBase.prototype.setContext = function(context,userParams,callback)
{
	if(!context) context = {};
	context.userParams = userParams;
	if(callback) context.callback = callback;
	context.adaptor = this;
	if(!context.host)
		context.host = this.host;
	context.host = this.fullHostName(context.host);
	if(!context.workspace)
		context.workspace = this.workspace;
	return context;
};

// Open the specified host
AdaptorBase.prototype.openHost = function(host,context,userParams,callback)
{
	this.host = host;
	context = this.setContext(context,userParams,callback);
	context.status = true;
	if(callback)
		window.setTimeout(function() {context.callback(context,userParams);},10);
	return true;
};

// Open the specified workspace
AdaptorBase.prototype.openWorkspace = function(workspace,context,userParams,callback)
{
	this.workspace = workspace;
	context = this.setContext(context,userParams,callback);
	context.status = true;
	if(callback)
		window.setTimeout(function() {callback(context,userParams);},10);
	return true;
};

//--
//-- HTTP request code
//--

function ajaxReq(args)
{
	if(window.Components && window.netscape && window.netscape.security && document.location.protocol.indexOf("http") == -1)
		window.netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	return jQuery.ajax(args);
}

function httpReq(type,url,callback,params,headers,data,contentType,username,password,allowCache)
{
	var httpSuccess = function(xhr) {
		try {
			// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
			return (!xhr.status && location.protocol === "file:") ||
				(xhr.status >= 200 && xhr.status < 300) ||
				xhr.status === 304 || xhr.status === 1223;
		} catch(e) {}
		return false;
	};

	var options = {
		type:type,
		url:url,
		processData:false,
		data:data,
		cache:!!allowCache,
		beforeSend: function(xhr) {
			var i;
			for(i in headers)
				xhr.setRequestHeader(i,headers[i]);
			xhr.setRequestHeader("X-Requested-With", "TiddlyWiki " + formatVersion());
		}
	};

	if(callback) {
		options.complete = function(xhr,textStatus) {
			if(httpSuccess(xhr))
				callback(true,params,xhr.responseText,url,xhr);
			else
				callback(false,params,null,url,xhr);
		};
	}
	if(contentType)
		options.contentType = contentType;
	if(username)
		options.username = username;
	if(password)
		options.password = password;
	if(window.Components && window.netscape && window.netscape.security && document.location.protocol.indexOf("http") == -1)
		window.netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	return jQuery.ajax(options);
}
//--
//-- TiddlyWiki-specific utility functions
//--

// Returns TiddlyWiki version string
function formatVersion(v)
{
	v = v || version;
	return v.major + "." + v.minor + "." + v.revision +
		(v.alpha ? " (alpha " + v.alpha + ")" : "") +
		(v.beta ? " (beta " + v.beta + ")" : "");
}

function compareVersions(v1,v2)
{
	var x1,x2,i,a = ["major","minor","revision"];
	for(i = 0; i<a.length; i++) {
		x1 = v1[a[i]] || 0;
		x2 = v2[a[i]] || 0;
		if(x1<x2)
			return 1;
		if(x1>x2)
			return -1;
	}
	x1 = v1.beta || 9999;
	x2 = v2.beta || 9999;
	if(x1<x2)
		return 1;
	return x1 > x2 ? -1 : 0;
}

function merge(dst,src,preserveExisting)
{
	var i;
	for(i in src) {
		if(!preserveExisting || dst[i] === undefined)
			dst[i] = src[i];
	}
	return dst;
}

// Resolve the target object of an event
function resolveTarget(e)
{
	var obj;
	if(e.target)
		obj = e.target;
	else if(e.srcElement)
		obj = e.srcElement;
	if(obj.nodeType == 3) // defeat Safari bug
		obj = obj.parentNode;
	return obj;
}

// Returns a string containing the description of an exception, optionally prepended by a message
function exceptionText(e,message)
{
	var s = e.description || e.toString();
	return message ? "%0:\n%1".format([message,s]) : s;
}

// Displays an alert of an exception description with optional message
function showException(e,message)
{
	alert(exceptionText(e,message));
}

function alertAndThrow(m)
{
	alert(m);
	throw(m);
}

function glyph(name)
{
	var g = config.glyphs;
	var b = g.currBrowser;
	if(b == null) {
		b = 0;
		while(b < g.browsers.length-1 && !g.browsers[b]())
			b++;
		g.currBrowser = b;
	}
	if(!g.codes[name])
		return "";
	return g.codes[name][b];
}

function createTiddlyText(parent,text)
{
	return parent.appendChild(document.createTextNode(text));
}

function createTiddlyCheckbox(parent,caption,checked,onChange)
{
	var cb = document.createElement("input");
	cb.setAttribute("type","checkbox");
	cb.onclick = onChange;
	parent.appendChild(cb);
	cb.checked = checked;
	cb.className = "chkOptionInput";
	if(caption)
		wikify(caption,parent);
	return cb;
}

function createTiddlyElement(parent,element,id,className,text,attribs)
{
	var n,e = document.createElement(element);
	if(className != null)
		e.className = className;
	if(id != null)
		e.setAttribute("id",id);
	if(text != null)
		e.appendChild(document.createTextNode(text));
	if(attribs) {
		for(n in attribs) {
			e.setAttribute(n,attribs[n]);
		}
	}
	if(parent != null)
		parent.appendChild(e);
	return e;
}

function createTiddlyButton(parent,text,tooltip,action,className,id,accessKey,attribs)
{
	var i,btn = document.createElement("a");
	btn.setAttribute("href","javascript:;");
	if(action) {
		btn.onclick = action;
	}
	if(tooltip)
		btn.setAttribute("title",tooltip);
	if(text)
		btn.appendChild(document.createTextNode(text));
	btn.className = className || "button";
	if(id)
		btn.id = id;
	if(attribs) {
		for(i in attribs) {
			btn.setAttribute(i,attribs[i]);
		}
	}
	if(parent)
		parent.appendChild(btn);
	if(accessKey)
		btn.setAttribute("accessKey",accessKey);
	return btn;
}

function createExternalLink(place,url,label)
{
	var link = document.createElement("a");
	link.className = "externalLink";
	link.href = url;
	var f = config.messages.externalLinkTooltip;
	link.title = f ? f.format([url]) : url;
	if(config.options.chkOpenInNewWindow)
		link.target = "_blank";
	place.appendChild(link);
	if(label)
		createTiddlyText(link, label);
	return link;
}

function getTiddlyLinkInfo(title,currClasses)
{
	var classes = currClasses ? currClasses.split(" ") : [];
	classes.pushUnique("tiddlyLink");
	var tiddler = store.fetchTiddler(title);
	var subTitle;
	if(tiddler) {
		subTitle = tiddler.getSubtitle();
		classes.pushUnique("tiddlyLinkExisting");
		classes.remove("tiddlyLinkNonExisting");
		classes.remove("shadow");
	} else {
	    var f;
		classes.remove("tiddlyLinkExisting");
		classes.pushUnique("tiddlyLinkNonExisting");
		if(store.isShadowTiddler(title)) {
			f = config.messages.shadowedTiddlerToolTip;
			classes.pushUnique("shadow");
		} else {
			f = config.messages.undefinedTiddlerToolTip;
			classes.remove("shadow");
		}
		subTitle = f ? f.format([title]) : "";
	}
	if(typeof config.annotations[title]=="string")
		subTitle = config.annotations[title];
	return {classes: classes.join(" "),subTitle: subTitle};
}

// Event handler for clicking on a tiddly link
function onClickTiddlerLink(ev)
{
	var e = ev || window.event;
	var target = resolveTarget(e);
	var link = target;
	var title = null;
	var fields = null;
	var noToggle = null;
	do {
		title = link.getAttribute("tiddlyLink");
		fields = link.getAttribute("tiddlyFields");
		noToggle = link.getAttribute("noToggle");
		link = link.parentNode;
	} while(title == null && link != null);
	if(!store.isShadowTiddler(title)) {
		var f = fields ? fields.decodeHashMap() : {};
		fields = String.encodeHashMap(merge(f,config.defaultCustomFields,true));
	}
	if(title) {
		var toggling = e.metaKey || e.ctrlKey;
		if(config.options.chkToggleLinks)
			toggling = !toggling;
		if(noToggle)
			toggling = false;
		if(store.getTiddler(title))
			fields = null;
		story.displayTiddler(target,title,null,true,null,fields,toggling);
	}
	clearMessage();
	return false;
}

function createTiddlyLink(place,title,includeText,className,isStatic,linkedFromTiddler,noToggle)
{
	var title = jQuery.trim(title);
	var text = includeText ? title : null;
	var i = getTiddlyLinkInfo(title,className);
	var btn = isStatic ? createExternalLink(place,store.getTiddlerText("SiteUrl",null) + "#" + title) : createTiddlyButton(place,text,i.subTitle,onClickTiddlerLink,i.classes);
	if(isStatic)
		btn.className += ' ' + className;
	btn.setAttribute("refresh","link");
	btn.setAttribute("tiddlyLink",title);
	if(noToggle)
		btn.setAttribute("noToggle","true");
	if(linkedFromTiddler) {
		var fields = linkedFromTiddler.getInheritedFields();
		if(fields)
			btn.setAttribute("tiddlyFields",fields);
	}
	return btn;
}

function refreshTiddlyLink(e,title)
{
	var i = getTiddlyLinkInfo(title,e.className);
	e.className = i.classes;
	e.title = i.subTitle;
}

function createTiddlyDropDown(place,onchange,options,defaultValue)
{
	var sel = createTiddlyElement(place,"select");
	sel.onchange = onchange;
	var t;
	for(t=0; t<options.length; t++) {
		var e = createTiddlyElement(sel,"option",null,null,options[t].caption);
		e.value = options[t].name;
		if(options[t].name == defaultValue)
			e.selected = true;
	}
	return sel;
}

//--
//-- TiddlyWiki-specific popup utility functions
//--

// Event handler for 'open all' on a tiddler popup
function onClickTagOpenAll(ev)
{
	var tiddlers = store.getTaggedTiddlers(this.getAttribute("tag"));
	var sortby = this.getAttribute("sortby");
	if(sortby&&sortby.length) {
		store.sortTiddlers(tiddlers,sortby);
	}
	story.displayTiddlers(this,tiddlers);
	return false;
}

// Event handler for clicking on a tiddler tag
function onClickTag(ev)
{
	var e = ev || window.event;
	var popup = Popup.create(this);
	jQuery(popup).addClass("taggedTiddlerList");
	var tag = this.getAttribute("tag");
	var title = this.getAttribute("tiddler");
	if(popup && tag) {
		var tagged = tag.indexOf("[")==-1 ? store.getTaggedTiddlers(tag) : store.filterTiddlers(tag);
		var sortby = this.getAttribute("sortby");
		if(sortby&&sortby.length) {
			store.sortTiddlers(tagged,sortby);
		}
		var titles = [];
		var r;
		for(r=0;r<tagged.length;r++) {
			if(tagged[r].title != title)
				titles.push(tagged[r].title);
		}
		var lingo = config.views.wikified.tag;
		if(titles.length > 0) {
			var openAll = createTiddlyButton(createTiddlyElement(popup,"li"),lingo.openAllText.format([tag]),lingo.openAllTooltip,onClickTagOpenAll);
			openAll.setAttribute("tag",tag);
			openAll.setAttribute("sortby",sortby);
			createTiddlyElement(createTiddlyElement(popup,"li",null,"listBreak"),"div");
			for(r=0; r<titles.length; r++) {
				createTiddlyLink(createTiddlyElement(popup,"li"),titles[r],true);
			}
		} else {
			createTiddlyElement(popup,"li",null,"disabled",lingo.popupNone.format([tag]));
		}
		createTiddlyElement(createTiddlyElement(popup,"li",null,"listBreak"),"div");
		var h = createTiddlyLink(createTiddlyElement(popup,"li"),tag,false);
		createTiddlyText(h,lingo.openTag.format([tag]));
	}
	Popup.show();
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	return false;
}

// Create a button for a tag with a popup listing all the tiddlers that it tags
function createTagButton(place,tag,excludeTiddler,title,tooltip)
{
	var btn = createTiddlyButton(place,title||tag,(tooltip||config.views.wikified.tag.tooltip).format([tag]),onClickTag);
	btn.setAttribute("tag",tag);
	if(excludeTiddler)
		btn.setAttribute("tiddler",excludeTiddler);
	return btn;
}

function onClickTiddlyPopup(ev)
{
	var e = ev || window.event;
	var tiddler = this.tiddler;
	if(tiddler.text) {
		var popup = Popup.create(this,"div","popupTiddler");
		wikify(tiddler.text,popup,null,tiddler);
		Popup.show();
	}
	if(e) e.cancelBubble = true;
	if(e && e.stopPropagation) e.stopPropagation();
	return false;
}

function createTiddlyPopup(place,caption,tooltip,tiddler)
{
	if(tiddler.text) {
		createTiddlyLink(place,caption,true);
		var btn = createTiddlyButton(place,glyph("downArrow"),tooltip,onClickTiddlyPopup,"tiddlerPopupButton");
		btn.tiddler = tiddler;
	} else {
		createTiddlyText(place,caption);
	}
}

function onClickError(ev)
{
	var e = ev || window.event;
	var popup = Popup.create(this);
	var lines = this.getAttribute("errorText").split("\n");
	var t;
	for(t=0; t<lines.length; t++)
		createTiddlyElement(popup,"li",null,null,lines[t]);
	Popup.show();
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	return false;
}

function createTiddlyError(place,title,text)
{
	var btn = createTiddlyButton(place,title,null,onClickError,"errorButton");
	if(text) btn.setAttribute("errorText",text);
}
//-
//- Animation engine
//-

function Animator()
{
	this.running = 0; // Incremented at start of each animation, decremented afterwards. If zero, the interval timer is disabled
	this.timerID = 0; // ID of the timer used for animating
	this.animations = []; // List of animations in progress
	return this;
}

// Start animation engine
Animator.prototype.startAnimating = function() //# Variable number of arguments
{
	var t;
	for(t=0; t<arguments.length; t++)
		this.animations.push(arguments[t]);
	if(this.running == 0) {
		var me = this;
		this.timerID = window.setInterval(function() {me.doAnimate(me);},10);
	}
	this.running += arguments.length;
};

// Perform an animation engine tick, calling each of the known animation modules
Animator.prototype.doAnimate = function(me)
{
	var a = 0;
	while(a < me.animations.length) {
		var animation = me.animations[a];
		if(animation.tick()) {
			a++;
		} else {
			me.animations.splice(a,1);
			if(--me.running == 0)
				window.clearInterval(me.timerID);
		}
	}
};

Animator.slowInSlowOut = function(progress)
{
	return(1-((Math.cos(progress * Math.PI)+1)/2));
};

//--
//-- Morpher animation
//--

// Animate a set of properties of an element
function Morpher(element,duration,properties,callback)
{
	this.element = element;
	this.duration = duration;
	this.properties = properties;
	this.startTime = new Date();
	this.endTime = Number(this.startTime) + duration;
	this.callback = callback;
	this.tick();
	return this;
}

Morpher.prototype.assignStyle = function(element,style,value)
{
	switch(style) {
	case "-tw-vertScroll":
		window.scrollTo(findScrollX(),value);
		break;
	case "-tw-horizScroll":
		window.scrollTo(value,findScrollY());
		break;
	default:
		element.style[style] = value;
		break;
	}
};

Morpher.prototype.stop = function()
{
	var t;
	for(t=0; t<this.properties.length; t++) {
		var p = this.properties[t];
		if(p.atEnd !== undefined) {
			this.assignStyle(this.element,p.style,p.atEnd);
		}
	}
	if(this.callback)
		this.callback(this.element,this.properties);
};

Morpher.prototype.tick = function()
{
	var currTime = Number(new Date());
	var t,progress = Animator.slowInSlowOut(Math.min(1,(currTime-this.startTime)/this.duration));
	for(t=0; t<this.properties.length; t++) {
		var p = this.properties[t];
		if(p.start !== undefined && p.end !== undefined) {
			var template = p.template || "%0";
			switch(p.format) {
			case undefined:
			case "style":
				var v = p.start + (p.end-p.start) * progress;
				this.assignStyle(this.element,p.style,template.format([v]));
				break;
			case "color":
				break;
			}
		}
	}
	if(currTime >= this.endTime) {
		this.stop();
		return false;
	}
	return true;
};

//--
//-- Zoomer animation
//--

function Zoomer(text,startElement,targetElement,unused)
{
	var e = createTiddlyElement(document.body,"div",null,"zoomer");
	createTiddlyElement(e,"div",null,null,text);
	var winWidth = findWindowWidth();
	var winHeight = findWindowHeight();
	var p = [
		{style: 'left', start: findPosX(startElement), end: findPosX(targetElement), template: '%0px'},
		{style: 'top', start: findPosY(startElement), end: findPosY(targetElement), template: '%0px'},
		{style: 'width', start: Math.min(startElement.scrollWidth,winWidth), end: Math.min(targetElement.scrollWidth,winWidth), template: '%0px', atEnd: 'auto'},
		{style: 'height', start: Math.min(startElement.scrollHeight,winHeight), end: Math.min(targetElement.scrollHeight,winHeight), template: '%0px', atEnd: 'auto'},
		{style: 'fontSize', start: 8, end: 24, template: '%0pt'}
	];
	var c = function(element,properties) {jQuery(element).remove();};
	return new Morpher(e,config.animDuration,p,c);
}

//--
//-- Scroller animation
//--

function Scroller(targetElement)
{
	var p = [{style: '-tw-vertScroll', start: findScrollY(), end: ensureVisible(targetElement)}];
	return new Morpher(targetElement,config.animDuration,p);
}

//--
//-- Slider animation
//--

// deleteMode - "none", "all" [delete target element and it's children], [only] "children" [but not the target element]
function Slider(element,opening,unused,deleteMode)
{
	element.style.overflow = 'hidden';
	if(opening)
		element.style.height = '0px'; // Resolves a Firefox flashing bug
	element.style.display = 'block';
	var height = element.scrollHeight;
	var p = [];
	var c = null;
	if(opening) {
		p.push({style: 'height', start: 0, end: height, template: '%0px', atEnd: 'auto'});
		p.push({style: 'opacity', start: 0, end: 1, template: '%0'});
		p.push({style: 'filter', start: 0, end: 100, template: 'alpha(opacity:%0)'});
	} else {
		p.push({style: 'height', start: height, end: 0, template: '%0px'});
		p.push({style: 'display', atEnd: 'none'});
		p.push({style: 'opacity', start: 1, end: 0, template: '%0'});
		p.push({style: 'filter', start: 100, end: 0, template: 'alpha(opacity:%0)'});
		switch(deleteMode) {
		case "all":
			c = function(element,properties) {jQuery(element).remove();};
			break;
		case "children":
			c = function(element,properties) {jQuery(element).empty();};
			break;
		}
	}
	return new Morpher(element,config.animDuration,p,c);
}

//--
//-- Popup menu
//--

var Popup = {
	stack: [] // Array of objects with members root: and popup:
	};

Popup.create = function(root,elem,className)
{
	var stackPosition = this.find(root,"popup");
	Popup.remove(stackPosition+1);
	var popup = createTiddlyElement(document.body,elem || "ol","popup",className || "popup");
	popup.stackPosition = stackPosition;
	Popup.stack.push({root: root, popup: popup});
	return popup;
};

Popup.onDocumentClick = function(ev)
{
	var e = ev || window.event;
	if(e.eventPhase == undefined)
		Popup.remove();
	else if(e.eventPhase == Event.BUBBLING_PHASE || e.eventPhase == Event.AT_TARGET)
		Popup.remove();
	return true;
};

Popup.show = function(valign,halign,offset)
{
	var curr = Popup.stack[Popup.stack.length-1];
	this.place(curr.root,curr.popup,valign,halign,offset);
	jQuery(curr.root).addClass("highlight");
	if(config.options.chkAnimate && anim && typeof Scroller == "function")
		anim.startAnimating(new Scroller(curr.popup));
	else
		window.scrollTo(0,ensureVisible(curr.popup));
};

Popup.place = function(root,popup,valign,halign,offset)
{
	if(!offset)
		offset = {x:0,y:0};
	if(popup.stackPosition >= 0 && !valign && !halign) {
		offset.x = offset.x + root.offsetWidth;
	} else {
		offset.x = (halign == "right") ? offset.x + root.offsetWidth : offset.x;
		offset.y = (valign == "top") ? offset.y : offset.y + root.offsetHeight;
	}
	var rootLeft = findPosX(root);
	var rootTop = findPosY(root);
	var popupLeft = rootLeft + offset.x;
	var popupTop = rootTop + offset.y;
	var winWidth = findWindowWidth();
	if(popup.offsetWidth > winWidth*0.75)
		popup.style.width = winWidth*0.75 + "px";
	var popupWidth = popup.offsetWidth;
	var scrollWidth = winWidth - document.body.offsetWidth;
	if(popupLeft + popupWidth > winWidth - scrollWidth - 1) {
		if(halign == "right")
			popupLeft = popupLeft - root.offsetWidth - popupWidth;
		else
			popupLeft = winWidth - popupWidth - scrollWidth - 1;
	}
	popup.style.left = popupLeft + "px";
	popup.style.top = popupTop + "px";
	popup.style.display = "block";
};

Popup.find = function(e)
{
	var t,pos = -1;
	for(t=this.stack.length-1; t>=0; t--) {
		if(isDescendant(e,this.stack[t].popup))
			pos = t;
	}
	return pos;
};

Popup.remove = function(pos)
{
	if(!pos) pos = 0;
	if(Popup.stack.length > pos) {
		Popup.removeFrom(pos);
	}
};

Popup.removeFrom = function(from)
{
	var t;
	for(t=Popup.stack.length-1; t>=from; t--) {
		var p = Popup.stack[t];
		jQuery(p.root).removeClass("highlight");
		jQuery(p.popup).remove();
	}
	Popup.stack = Popup.stack.slice(0,from);
};

//--
//-- Wizard support
//--

function Wizard(elem)
{
	if(elem) {
		this.formElem = findRelated(elem,"wizard","className");
		this.bodyElem = findRelated(this.formElem.firstChild,"wizardBody","className","nextSibling");
		this.footElem = findRelated(this.formElem.firstChild,"wizardFooter","className","nextSibling");
	} else {
		this.formElem = null;
		this.bodyElem = null;
		this.footElem = null;
	}
}

Wizard.prototype.setValue = function(name,value)
{
	jQuery(this.formElem).data(name, value);
};

Wizard.prototype.getValue = function(name)
{
	return this.formElem ? jQuery(this.formElem).data(name) : null;
};

Wizard.prototype.createWizard = function(place,title)
{
	this.formElem = createTiddlyElement(place,"form",null,"wizard");
	createTiddlyElement(this.formElem,"h1",null,null,title);
	this.bodyElem = createTiddlyElement(this.formElem,"div",null,"wizardBody");
	this.footElem = createTiddlyElement(this.formElem,"div",null,"wizardFooter");
	return this.formElem;
};

Wizard.prototype.clear = function()
{
	jQuery(this.bodyElem).empty();
};

Wizard.prototype.setButtons = function(buttonInfo,status)
{
	jQuery(this.footElem).empty();
	var t;
	for(t=0; t<buttonInfo.length; t++) {
		createTiddlyButton(this.footElem,buttonInfo[t].caption,buttonInfo[t].tooltip,buttonInfo[t].onClick);
		insertSpacer(this.footElem);
		}
	if(typeof status == "string") {
		createTiddlyElement(this.footElem,"span",null,"status",status);
	}
};

Wizard.prototype.addStep = function(stepTitle,html)
{
	jQuery(this.bodyElem).empty();
	var w = createTiddlyElement(this.bodyElem,"div");
	createTiddlyElement(w,"h2",null,null,stepTitle);
	var step = createTiddlyElement(w,"div",null,"wizardStep");
	step.innerHTML = html;
	applyHtmlMacros(step,tiddler);
};

Wizard.prototype.getElement = function(name)
{
	return this.formElem.elements[name];
};

//--
//-- ListView gadget
//--

var ListView = {};

// Create a listview
ListView.create = function(place,listObject,listTemplate,callback,className)
{
	var table = createTiddlyElement(place,"table",null,className || "listView twtable");
	var thead = createTiddlyElement(table,"thead");
	var t,r = createTiddlyElement(thead,"tr");
	for(t=0; t<listTemplate.columns.length; t++) {
		var columnTemplate = listTemplate.columns[t];
		var c = createTiddlyElement(r,"th");
		var colType = ListView.columnTypes[columnTemplate.type];
		if(colType && colType.createHeader) {
			colType.createHeader(c,columnTemplate,t);
			if(columnTemplate.className)
				jQuery(c).addClass(columnTemplate.className);
		}
	}
	var rc,tbody = createTiddlyElement(table,"tbody");
	for(rc=0; rc<listObject.length; rc++) {
		var rowObject = listObject[rc];
		r = createTiddlyElement(tbody,"tr");
		for(c=0; c<listTemplate.rowClasses.length; c++) {
			if(rowObject[listTemplate.rowClasses[c].field])
				jQuery(r).addClass(listTemplate.rowClasses[c].className);
		}
		rowObject.rowElement = r;
		rowObject.colElements = {};
		var cc;
		for(cc=0; cc<listTemplate.columns.length; cc++) {
			c = createTiddlyElement(r,"td");
			columnTemplate = listTemplate.columns[cc];
			var field = columnTemplate.field;
			colType = ListView.columnTypes[columnTemplate.type];
			if(colType && colType.createItem) {
				colType.createItem(c,rowObject,field,columnTemplate,cc,rc);
				if(columnTemplate.className)
					jQuery(c).addClass(columnTemplate.className);
			}
			rowObject.colElements[field] = c;
		}
	}
	if(callback && listTemplate.actions)
		createTiddlyDropDown(place,ListView.getCommandHandler(callback),listTemplate.actions);
	if(callback && listTemplate.buttons) {
		for(t=0; t<listTemplate.buttons.length; t++) {
			var a = listTemplate.buttons[t];
			if(a && a.name != "")
				createTiddlyButton(place,a.caption,null,ListView.getCommandHandler(callback,a.name,a.allowEmptySelection));
		}
	}
	return table;
};

ListView.getCommandHandler = function(callback,name,allowEmptySelection)
{
	return function(e) {
		var view = findRelated(this,"TABLE",null,"previousSibling");
		var tiddlers = [];
		ListView.forEachSelector(view,function(e,rowName) {
					if(e.checked)
						tiddlers.push(rowName);
					});
		if(tiddlers.length == 0 && !allowEmptySelection) {
			alert(config.messages.nothingSelected);
		} else {
			if(this.nodeName.toLowerCase() == "select") {
				callback(view,this.value,tiddlers);
				this.selectedIndex = 0;
			} else {
				callback(view,name,tiddlers);
			}
		}
	};
};

// Invoke a callback for each selector checkbox in the listview
ListView.forEachSelector = function(view,callback)
{
	var checkboxes = view.getElementsByTagName("input");
	var t,hadOne = false;
	for(t=0; t<checkboxes.length; t++) {
		var cb = checkboxes[t];
		if(cb.getAttribute("type") == "checkbox") {
			var rn = cb.getAttribute("rowName");
			if(rn) {
				callback(cb,rn);
				hadOne = true;
			}
		}
	}
	return hadOne;
};

ListView.getSelectedRows = function(view)
{
	var rowNames = [];
	ListView.forEachSelector(view,function(e,rowName) {
				if(e.checked)
					rowNames.push(rowName);
				});
	return rowNames;
};

ListView.columnTypes = {};

ListView.columnTypes.String = {
	createHeader: function(place,columnTemplate,col)
		{
			createTiddlyText(place,columnTemplate.title);
		},
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined)
				createTiddlyText(place,v);
		}
};

ListView.columnTypes.WikiText = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined)
				wikify(v,place,null,null);
		}
};

ListView.columnTypes.Tiddler = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined && v.title)
				createTiddlyPopup(place,v.title,config.messages.listView.tiddlerTooltip,v);
		}
};

ListView.columnTypes.Size = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var msg = config.messages.sizeTemplates;
			var v = listObject[field];
			if(v != undefined) {
				var t = 0;
				while(t<msg.length-1 && v<msg[t].unit)
					t++;
				createTiddlyText(place,msg[t].template.format([Math.round(v/msg[t].unit)]));
			}
		}
};

ListView.columnTypes.Link = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			var c = columnTemplate.text;
			if(v != undefined)
				createExternalLink(place,v,c || v);
		}
};

ListView.columnTypes.Date = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined)
				createTiddlyText(place,v.formatString(columnTemplate.dateFormat));
		}
};

ListView.columnTypes.StringList = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined) {
				var t;
				for(t=0; t<v.length; t++) {
					createTiddlyText(place,v[t]);
					createTiddlyElement(place,"br");
				}
			}
		}
};

ListView.columnTypes.Selector = {
	createHeader: function(place,columnTemplate,col)
		{
			createTiddlyCheckbox(place,null,false,this.onHeaderChange);
		},
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var e = createTiddlyCheckbox(place,null,listObject[field],null);
			e.setAttribute("rowName",listObject[columnTemplate.rowName]);
		},
	onHeaderChange: function(e)
		{
			var state = this.checked;
			var view = findRelated(this,"TABLE");
			if(!view)
				return;
			ListView.forEachSelector(view,function(e,rowName) {
								e.checked = state;
							});
		}
};

ListView.columnTypes.Tags = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var tags = listObject[field];
			createTiddlyText(place,String.encodeTiddlyLinkList(tags));
		}
};

ListView.columnTypes.Boolean = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			if(listObject[field] == true)
				createTiddlyText(place,columnTemplate.trueText);
			if(listObject[field] == false)
				createTiddlyText(place,columnTemplate.falseText);
		}
};

ListView.columnTypes.TagCheckbox = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var e = createTiddlyCheckbox(place,null,listObject[field],this.onChange);
			e.setAttribute("tiddler",listObject.title);
			e.setAttribute("tag",columnTemplate.tag);
		},
	onChange : function(e)
		{
			var tag = this.getAttribute("tag");
			var tiddler = this.getAttribute("tiddler");
			store.setTiddlerTag(tiddler,this.checked,tag);
		}
};

ListView.columnTypes.TiddlerLink = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined) {
				var link = createTiddlyLink(place,listObject[columnTemplate.tiddlerLink],false,null);
				createTiddlyText(link,listObject[field]);
			}
		}
};

//--
//-- Augmented methods for the JavaScript Array() object
//--

// Add indexOf function if browser does not support it
if(!Array.indexOf) {
Array.prototype.indexOf = function(item,from)
{
	if(!from)
		from = 0;
	var i;
	for(i=from; i<this.length; i++) {
		if(this[i] === item)
			return i;
	}
	return -1;
};}

// Find an entry in a given field of the members of an array
Array.prototype.findByField = function(field,value)
{
	var t;
	for(t=0; t<this.length; t++) {
		if(this[t][field] === value)
			return t;
	}
	return null;
};

// Return whether an entry exists in an array
Array.prototype.contains = function(item)
{
	return this.indexOf(item) != -1;
};

// Adds, removes or toggles a particular value within an array
//  value - value to add
//  mode - +1 to add value, -1 to remove value, 0 to toggle it
Array.prototype.setItem = function(value,mode)
{
	var p = this.indexOf(value);
	if(mode == 0)
		mode = (p == -1) ? +1 : -1;
	if(mode == +1) {
		if(p == -1)
			this.push(value);
	} else if(mode == -1) {
		if(p != -1)
			this.splice(p,1);
	}
};

// Return whether one of a list of values exists in an array
Array.prototype.containsAny = function(items)
{
	var i;
	for(i=0; i<items.length; i++) {
		if(this.indexOf(items[i]) != -1)
			return true;
	}
	return false;
};

// Return whether all of a list of values exists in an array
Array.prototype.containsAll = function(items)
{
	var i;
	for(i = 0; i<items.length; i++) {
		if(this.indexOf(items[i]) == -1)
			return false;
	}
	return true;
};

// Push a new value into an array only if it is not already present in the array. If the optional unique parameter is false, it reverts to a normal push
Array.prototype.pushUnique = function(item,unique)
{
	if(unique === false) {
		this.push(item);
	} else {
		if(this.indexOf(item) == -1)
			this.push(item);
	}
};

Array.prototype.remove = function(item)
{
	var p = this.indexOf(item);
	if(p != -1)
		this.splice(p,1);
};

if(!Array.prototype.map) {
Array.prototype.map = function(fn,thisObj)
{
	var scope = thisObj || window;
	var i,j,a = [];
	for(i=0, j=this.length; i < j; ++i) {
		a.push(fn.call(scope,this[i],i,this));
	}
	return a;
};}

//--
//-- Augmented methods for the JavaScript String() object
//--

// Get characters from the right end of a string
String.prototype.right = function(n)
{
	return n < this.length ? this.slice(this.length-n) : this;
};

// Trim whitespace from both ends of a string
String.prototype.trim = function()
{
	return this.replace(/^\s*|\s*$/g,"");
};

// Convert a string from a CSS style property name to a JavaScript style name ("background-color" -> "backgroundColor")
String.prototype.unDash = function()
{
	var t,s = this.split("-");
	if(s.length > 1) {
		for(t=1; t<s.length; t++)
			s[t] = s[t].substr(0,1).toUpperCase() + s[t].substr(1);
	}
	return s.join("");
};

// Substitute substrings from an array into a format string that includes '%1'-type specifiers
String.prototype.format = function(s)
{
	var substrings = s && s.constructor == Array ? s : arguments;
	var subRegExp = /(?:%(\d+))/mg;
	var currPos = 0;
	var match,r = [];
	do {
		match = subRegExp.exec(this);
		if(match && match[1]) {
			if(match.index > currPos)
				r.push(this.substring(currPos,match.index));
			r.push(substrings[parseInt(match[1],10)]);
			currPos = subRegExp.lastIndex;
		}
	} while(match);
	if(currPos < this.length)
		r.push(this.substring(currPos,this.length));
	return r.join("");
};

// Escape any special RegExp characters with that character preceded by a backslash
String.prototype.escapeRegExp = function()
{
	var s = "\\^$*+?()=!|,{}[].";
	var t,c = this;
	for(t=0; t<s.length; t++)
		c = c.replace(new RegExp("\\" + s.substr(t,1),"g"),"\\" + s.substr(t,1));
	return c;
};

// Convert "\" to "\s", newlines to "\n" (and remove carriage returns)
String.prototype.escapeLineBreaks = function()
{
	return this.replace(/\\/mg,"\\s").replace(/\n/mg,"\\n").replace(/\r/mg,"");
};

// Convert "\n" to newlines, "\b" to " ", "\s" to "\" (and remove carriage returns)
String.prototype.unescapeLineBreaks = function()
{
	return this.replace(/\\n/mg,"\n").replace(/\\b/mg," ").replace(/\\s/mg,"\\").replace(/\r/mg,"");
};

// Convert & to "&amp;", < to "&lt;", > to "&gt;" and " to "&quot;"
String.prototype.htmlEncode = function()
{
	return this.replace(/&/mg,"&amp;").replace(/</mg,"&lt;").replace(/>/mg,"&gt;").replace(/\"/mg,"&quot;");
};

// Convert "&amp;" to &, "&lt;" to <, "&gt;" to > and "&quot;" to "
String.prototype.htmlDecode = function()
{
	return this.replace(/&lt;/mg,"<").replace(/&gt;/mg,">").replace(/&quot;/mg,"\"").replace(/&amp;/mg,"&");
};

// Parse a space-separated string of name:value parameters
// The result is an array of objects:
//   result[0] = object with a member for each parameter name, value of that member being an array of values
//   result[1..n] = one object for each parameter, with 'name' and 'value' members
String.prototype.parseParams = function(defaultName,defaultValue,allowEval,noNames,cascadeDefaults)
{
	var parseToken = function(match,p) {
		var n;
		if(match[p]) // Double quoted
			n = match[p];
		else if(match[p+1]) // Single quoted
			n = match[p+1];
		else if(match[p+2]) // Double-square-bracket quoted
			n = match[p+2];
		else if(match[p+3]) // Double-brace quoted
			try {
				n = match[p+3];
				if(allowEval && config.evaluateMacroParameters != "none") {
					if(config.evaluateMacroParameters == "restricted") {
						if(window.restrictedEval) {
							n = window.restrictedEval(n);
						}
					} else {
						n = window.eval(n);
					}
				}
			} catch(ex) {
				throw "Unable to evaluate {{" + match[p+3] + "}}: " + exceptionText(ex);
			}
		else if(match[p+4]) // Unquoted
			n = match[p+4];
		else if(match[p+5]) // empty quote
			n = "";
		return n;
	};
	var r = [{}];
	var dblQuote = "(?:\"((?:(?:\\\\\")|[^\"])+)\")";
	var sngQuote = "(?:'((?:(?:\\\\\')|[^'])+)')";
	var dblSquare = "(?:\\[\\[((?:\\s|\\S)*?)\\]\\])";
	var dblBrace = "(?:\\{\\{((?:\\s|\\S)*?)\\}\\})";
	var unQuoted = noNames ? "([^\"'\\s]\\S*)" : "([^\"':\\s][^\\s:]*)";
	var emptyQuote = "((?:\"\")|(?:''))";
	var skipSpace = "(?:\\s*)";
	var token = "(?:" + dblQuote + "|" + sngQuote + "|" + dblSquare + "|" + dblBrace + "|" + unQuoted + "|" + emptyQuote + ")";
	var re = noNames ? new RegExp(token,"mg") : new RegExp(skipSpace + token + skipSpace + "(?:(\\:)" + skipSpace + token + ")?","mg");
	var match;
	do {
		match = re.exec(this);
		if(match) {
			var n = parseToken(match,1);
			if(noNames) {
				r.push({name:"",value:n});
			} else {
				var v = parseToken(match,8);
				if(v == null && defaultName) {
					v = n;
					n = defaultName;
				} else if(v == null && defaultValue) {
					v = defaultValue;
				}
				r.push({name:n,value:v});
				if(cascadeDefaults) {
					defaultName = n;
					defaultValue = v;
				}
			}
		}
	} while(match);
	// Summarise parameters into first element
	var t;
	for(t=1; t<r.length; t++) {
		if(r[0][r[t].name])
			r[0][r[t].name].push(r[t].value);
		else
			r[0][r[t].name] = [r[t].value];
	}
	return r;
};

// Process a string list of macro parameters into an array. Parameters can be quoted with "", '',
// [[]], {{ }} or left unquoted (and therefore space-separated). Double-braces {{}} results in
// an *evaluated* parameter: e.g. {{config.options.txtUserName}} results in the current user's name.
String.prototype.readMacroParams = function(notAllowEval)
{
	var p = this.parseParams("list",null,!notAllowEval,true);
	var t,n = [];
	for(t=1; t<p.length; t++)
		n.push(p[t].value);
	return n;
};

// Process a string list of unique tiddler names into an array. Tiddler names that have spaces in them must be [[bracketed]]
String.prototype.readBracketedList = function(unique)
{
	var p = this.parseParams("list",null,false,true);
	var t,n = [];
	for(t=1; t<p.length; t++) {
		if(p[t].value)
			n.pushUnique(p[t].value,unique);
	}
	return n;
};

// Returns array with start and end index of chunk between given start and end marker, or undefined.
String.prototype.getChunkRange = function(start,end)
{
	var s = this.indexOf(start);
	if(s != -1) {
		s += start.length;
		var e = this.indexOf(end,s);
		if(e != -1)
			return [s,e];
	}
};

// Replace a chunk of a string given start and end markers
String.prototype.replaceChunk = function(start,end,sub)
{
	var r = this.getChunkRange(start,end);
	return r ? this.substring(0,r[0]) + sub + this.substring(r[1]) : this;
};

// Returns a chunk of a string between start and end markers, or undefined
String.prototype.getChunk = function(start,end)
{
	var r = this.getChunkRange(start,end);
	if(r)
		return this.substring(r[0],r[1]);
};


// Static method to bracket a string with double square brackets if it contains a space
String.encodeTiddlyLink = function(title)
{
	return title.indexOf(" ") == -1 ? title : "[[" + title + "]]";
};

// Static method to encodeTiddlyLink for every item in an array and join them with spaces
String.encodeTiddlyLinkList = function(list)
{
	if(list) {
		var t,results = [];
		for(t=0; t<list.length; t++)
			results.push(String.encodeTiddlyLink(list[t]));
		return results.join(" ");
	} else {
		return "";
	}
};

// Convert a string as a sequence of name:"value" pairs into a hashmap
String.prototype.decodeHashMap = function()
{
	var fields = this.parseParams("anon","",false);
	var t,r = {};
	for(t=1; t<fields.length; t++)
		r[fields[t].name] = fields[t].value;
	return r;
};

// Static method to encode a hashmap into a name:"value"... string
String.encodeHashMap = function(hashmap)
{
	var t,r = [];
	for(t in hashmap)
		r.push(t + ':"' + hashmap[t] + '"');
	return r.join(" ");
};

// Static method to left-pad a string with 0s to a certain width
String.zeroPad = function(n,d)
{
	var s = n.toString();
	if(s.length < d)
		s = "000000000000000000000000000".substr(0,d-s.length) + s;
	return s;
};

String.prototype.startsWith = function(prefix)
{
	return !prefix || this.substring(0,prefix.length) == prefix;
};

// Returns the first value of the given named parameter.
function getParam(params,name,defaultValue)
{
	if(!params)
		return defaultValue;
	var p = params[0][name];
	return p ? p[0] : defaultValue;
}

// Returns the first value of the given boolean named parameter.
function getFlag(params,name,defaultValue)
{
	return !!getParam(params,name,defaultValue);
}

//--
//-- Augmented methods for the JavaScript Date() object
//--

// Substitute date components into a string
Date.prototype.formatString = function(template)
{
	var t = template.replace(/0hh12/g,String.zeroPad(this.getHours12(),2));
	t = t.replace(/hh12/g,this.getHours12());
	t = t.replace(/0hh/g,String.zeroPad(this.getHours(),2));
	t = t.replace(/hh/g,this.getHours());
	t = t.replace(/mmm/g,config.messages.dates.shortMonths[this.getMonth()]);
	t = t.replace(/0mm/g,String.zeroPad(this.getMinutes(),2));
	t = t.replace(/mm/g,this.getMinutes());
	t = t.replace(/0ss/g,String.zeroPad(this.getSeconds(),2));
	t = t.replace(/ss/g,this.getSeconds());
	t = t.replace(/[ap]m/g,this.getAmPm().toLowerCase());
	t = t.replace(/[AP]M/g,this.getAmPm().toUpperCase());
	t = t.replace(/wYYYY/g,this.getYearForWeekNo());
	t = t.replace(/wYY/g,String.zeroPad(this.getYearForWeekNo()-2000,2));
	t = t.replace(/YYYY/g,this.getFullYear());
	t = t.replace(/YY/g,String.zeroPad(this.getFullYear()-2000,2));
	t = t.replace(/MMM/g,config.messages.dates.months[this.getMonth()]);
	t = t.replace(/0MM/g,String.zeroPad(this.getMonth()+1,2));
	t = t.replace(/MM/g,this.getMonth()+1);
	t = t.replace(/0WW/g,String.zeroPad(this.getWeek(),2));
	t = t.replace(/WW/g,this.getWeek());
	t = t.replace(/DDD/g,config.messages.dates.days[this.getDay()]);
	t = t.replace(/ddd/g,config.messages.dates.shortDays[this.getDay()]);
	t = t.replace(/0DD/g,String.zeroPad(this.getDate(),2));
	t = t.replace(/DDth/g,this.getDate()+this.daySuffix());
	t = t.replace(/DD/g,this.getDate());
	var tz = this.getTimezoneOffset();
	var atz = Math.abs(tz);
	t = t.replace(/TZD/g,(tz < 0 ? '+' : '-') + String.zeroPad(Math.floor(atz / 60),2) + ':' + String.zeroPad(atz % 60,2));
	t = t.replace(/\\/g,"");
	return t;
};

Date.prototype.getWeek = function()
{
	var dt = new Date(this.getTime());
	var d = dt.getDay();
	if(d==0) d=7;// JavaScript Sun=0, ISO Sun=7
	dt.setTime(dt.getTime()+(4-d)*86400000);// shift day to Thurs of same week to calculate weekNo
	var n = Math.floor((dt.getTime()-new Date(dt.getFullYear(),0,1)+3600000)/86400000);
	return Math.floor(n/7)+1;
};

Date.prototype.getYearForWeekNo = function()
{
	var dt = new Date(this.getTime());
	var d = dt.getDay();
	if(d==0) d=7;// JavaScript Sun=0, ISO Sun=7
	dt.setTime(dt.getTime()+(4-d)*86400000);// shift day to Thurs of same week
	return dt.getFullYear();
};

Date.prototype.getHours12 = function()
{
	var h = this.getHours();
	return h > 12 ? h-12 : ( h > 0 ? h : 12 );
};

Date.prototype.getAmPm = function()
{
	return this.getHours() >= 12 ? config.messages.dates.pm : config.messages.dates.am;
};

Date.prototype.daySuffix = function()
{
	return config.messages.dates.daySuffixes[this.getDate()-1];
};

// Convert a date to local YYYYMMDDHHMM string format
Date.prototype.convertToLocalYYYYMMDDHHMM = function()
{
	return this.getFullYear() + String.zeroPad(this.getMonth()+1,2) + String.zeroPad(this.getDate(),2) + String.zeroPad(this.getHours(),2) + String.zeroPad(this.getMinutes(),2);
};

// Convert a date to UTC YYYYMMDDHHMM string format
Date.prototype.convertToYYYYMMDDHHMM = function()
{
	return this.getUTCFullYear() + String.zeroPad(this.getUTCMonth()+1,2) + String.zeroPad(this.getUTCDate(),2) + String.zeroPad(this.getUTCHours(),2) + String.zeroPad(this.getUTCMinutes(),2);
};

// Convert a date to UTC YYYYMMDD.HHMMSSMMM string format
Date.prototype.convertToYYYYMMDDHHMMSSMMM = function()
{
	return this.getUTCFullYear() + String.zeroPad(this.getUTCMonth()+1,2) + String.zeroPad(this.getUTCDate(),2) + "." + String.zeroPad(this.getUTCHours(),2) + String.zeroPad(this.getUTCMinutes(),2) + String.zeroPad(this.getUTCSeconds(),2) + String.zeroPad(this.getUTCMilliseconds(),3) +"0";
};

// Static method to create a date from a UTC YYYYMMDDHHMM format string
Date.convertFromYYYYMMDDHHMM = function(d)
{
	d = d?d.replace(/[^0-9]/g, ""):"";
	return Date.convertFromYYYYMMDDHHMMSSMMM(d.substr(0,12));
};

// Static method to create a date from a UTC YYYYMMDDHHMMSS format string
Date.convertFromYYYYMMDDHHMMSS = function(d)
{
	d = d?d.replace(/[^0-9]/g, ""):"";
	return Date.convertFromYYYYMMDDHHMMSSMMM(d.substr(0,14));
};

// Static method to create a date from a UTC YYYYMMDDHHMMSSMMM format string
Date.convertFromYYYYMMDDHHMMSSMMM = function(d)
{
	d = d ? d.replace(/[^0-9]/g, "") : "";
	return new Date(Date.UTC(parseInt(d.substr(0,4),10),
			parseInt(d.substr(4,2),10)-1,
			parseInt(d.substr(6,2),10),
			parseInt(d.substr(8,2)||"00",10),
			parseInt(d.substr(10,2)||"00",10),
			parseInt(d.substr(12,2)||"00",10),
			parseInt(d.substr(14,3)||"000",10)));
};

//--
//-- RGB colour object
//--

// Construct an RGB colour object from a '#rrggbb', '#rgb' or 'rgb(n,n,n)' string or from separate r,g,b values
function RGB(r,g,b)
{
	this.r = 0;
	this.g = 0;
	this.b = 0;
	if(typeof r == "string") {
		if(r.substr(0,1) == "#") {
			if(r.length == 7) {
				this.r = parseInt(r.substr(1,2),16)/255;
				this.g = parseInt(r.substr(3,2),16)/255;
				this.b = parseInt(r.substr(5,2),16)/255;
			} else {
				this.r = parseInt(r.substr(1,1),16)/15;
				this.g = parseInt(r.substr(2,1),16)/15;
				this.b = parseInt(r.substr(3,1),16)/15;
			}
		} else {
			var rgbPattern = /rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/;
			var c = r.match(rgbPattern);
			if(c) {
				this.r = parseInt(c[1],10)/255;
				this.g = parseInt(c[2],10)/255;
				this.b = parseInt(c[3],10)/255;
			}
		}
	} else {
		this.r = r;
		this.g = g;
		this.b = b;
	}
	return this;
}

// Mixes this colour with another in a specified proportion
// c = other colour to mix
// f = 0..1 where 0 is this colour and 1 is the new colour
// Returns an RGB object
RGB.prototype.mix = function(c,f)
{
	return new RGB(this.r + (c.r-this.r) * f,this.g + (c.g-this.g) * f,this.b + (c.b-this.b) * f);
};

// Return an rgb colour as a #rrggbb format hex string
RGB.prototype.toString = function()
{
	var clamp = function(x,min,max) {
		return x < min ? min : (x > max ? max : x);
	};
	return "#" +
			("0" + Math.floor(clamp(this.r,0,1) * 255).toString(16)).right(2) +
			("0" + Math.floor(clamp(this.g,0,1) * 255).toString(16)).right(2) +
			("0" + Math.floor(clamp(this.b,0,1) * 255).toString(16)).right(2);
};

//--
//-- DOM utilities - many derived from www.quirksmode.org
//--

function drawGradient(place,horiz,locolors,hicolors)
{
	if(!hicolors)
		hicolors = locolors;
	var t;
	for(t=0; t<= 100; t+=2) {
		var bar = document.createElement("div");
		place.appendChild(bar);
		bar.style.position = "absolute";
		bar.style.left = horiz ? t + "%" : 0;
		bar.style.top = horiz ? 0 : t + "%";
		bar.style.width = horiz ? (101-t) + "%" : "100%";
		bar.style.height = horiz ? "100%" : (101-t) + "%";
		bar.style.zIndex = -1;
		var p = t/100*(locolors.length-1);
		var hc = hicolors[Math.floor(p)];
		if(typeof hc == "string")
			hc = new RGB(hc);
		var lc = locolors[Math.ceil(p)];
		if(typeof lc == "string")
			lc = new RGB(lc);
		bar.style.backgroundColor = hc.mix(lc,p-Math.floor(p)).toString();
	}
}

function addEvent(obj,type,fn)
{
	if(obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function(){obj["e"+type+fn](window.event);};
		obj.attachEvent("on"+type,obj[type+fn]);
	} else {
		obj.addEventListener(type,fn,false);
	}
}

function removeEvent(obj,type,fn)
{
	if(obj.detachEvent) {
		obj.detachEvent("on"+type,obj[type+fn]);
		obj[type+fn] = null;
	} else {
		obj.removeEventListener(type,fn,false);
	}
}

// Find the closest relative with a given property value (property defaults to tagName, relative defaults to parentNode)
function findRelated(e,value,name,relative)
{
	name = name || "tagName";
	relative = relative || "parentNode";
	if(name == "className") {
		while(e && !jQuery(e).hasClass(value)) {
			e = e[relative];
		}
	} else {
		while(e && e[name] != value) {
			e = e[relative];
		}
	}
	return e;
}

// Get the scroll position for window.scrollTo necessary to scroll a given element into view
function ensureVisible(e)
{
	var posTop = findPosY(e);
	var posBot = posTop + e.offsetHeight;
	var winTop = findScrollY();
	var winHeight = findWindowHeight();
	var winBot = winTop + winHeight;
	if(posTop < winTop) {
		return posTop;
	} else if(posBot > winBot) {
		if(e.offsetHeight < winHeight)
			return posTop - (winHeight - e.offsetHeight);
		else
			return posTop;
	} else {
		return winTop;
	}
}

// Get the current width of the display window
function findWindowWidth()
{
	return window.innerWidth || document.documentElement.clientWidth;
}

// Get the current height of the display window
function findWindowHeight()
{
	return window.innerHeight || document.documentElement.clientHeight;
}

// Get the current height of the document
function findDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

// Get the current horizontal page scroll position
function findScrollX()
{
	return window.scrollX || document.documentElement.scrollLeft;
}

// Get the current vertical page scroll position
function findScrollY()
{
	return window.scrollY || document.documentElement.scrollTop;
}

function findPosX(obj)
{
	var curleft = 0;
	while(obj.offsetParent) {
		curleft += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	while(obj.offsetParent) {
		curtop += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return curtop;
}

// Blur a particular element
function blurElement(e)
{
	if(e && e.focus && e.blur) {
		e.focus();
		e.blur();
	}
}

// Create a non-breaking space
function insertSpacer(place)
{
	var e = document.createTextNode(String.fromCharCode(160));
	if(place)
		place.appendChild(e);
	return e;
}

// Replace the current selection of a textarea or text input and scroll it into view
function replaceSelection(e,text)
{
	if(e.setSelectionRange) {
		var oldpos = e.selectionStart;
		var isRange = e.selectionEnd > e.selectionStart;
		e.value = e.value.substr(0,e.selectionStart) + text + e.value.substr(e.selectionEnd);
		e.setSelectionRange(isRange ? oldpos : oldpos + text.length,oldpos + text.length);
		var linecount = e.value.split("\n").length;
		var thisline = e.value.substr(0,e.selectionStart).split("\n").length-1;
		e.scrollTop = Math.floor((thisline - e.rows / 2) * e.scrollHeight / linecount);
	} else if(document.selection) {
		var range = document.selection.createRange();
		if(range.parentElement() == e) {
			var isCollapsed = range.text == "";
			range.text = text;
			if(!isCollapsed) {
				range.moveStart("character", -text.length);
				range.select();
			}
		}
	}
}

// Set the caret position in a text area
function setCaretPosition(e,pos)
{
	if(e.selectionStart || e.selectionStart == '0') {
		e.selectionStart = pos;
		e.selectionEnd = pos;
		e.focus();
	} else if(document.selection) {
		// IE support
		e.focus ();
		var sel = document.selection.createRange();
		sel.moveStart('character', -e.value.length);
		sel.moveStart('character',pos);
		sel.moveEnd('character',0);
		sel.select();
	}
}

// Returns the text of the given (text) node, possibly merging subsequent text nodes
function getNodeText(e)
{
	var t = "";
	while(e && e.nodeName == "#text") {
		t += e.nodeValue;
		e = e.nextSibling;
	}
	return t;
}

// Returns true if the element e has a given ancestor element
function isDescendant(e,ancestor)
{
	while(e) {
		if(e === ancestor)
			return true;
		e = e.parentNode;
	}
	return false;
}


// deprecate the following...

// Prevent an event from bubbling
function stopEvent(e)
{
	var ev = e || window.event;
	ev.cancelBubble = true;
	if(ev.stopPropagation) ev.stopPropagation();
	return false;
}

// Remove any event handlers or non-primitve custom attributes
function scrubNode(e)
{
	if(!config.browser.isIE)
		return;
	var att = e.attributes;
	if(att) {
		var t;
		for(t=0; t<att.length; t++) {
			var n = att[t].name;
			if(n !== "style" && (typeof e[n] === "function" || (typeof e[n] === "object" && e[n] != null))) {
				try {
					e[n] = null;
				} catch(ex) {
				}
			}
		}
	}
	var c = e.firstChild;
	while(c) {
		scrubNode(c);
		c = c.nextSibling;
	}
}

function setStylesheet(s,id,doc)
{
	jQuery.twStylesheet(s,{id:id,doc:doc});
}

function removeStyleSheet(id)
{
	jQuery.twStylesheet.remove({id:id});
}

//--
//-- LoaderBase and SaverBase
//--

function LoaderBase() {}

LoaderBase.prototype.loadTiddler = function(store,node,tiddlers)
{
	var title = this.getTitle(store,node);
	if(safeMode && store.isShadowTiddler(title))
		return;
	if(title) {
		var tiddler = store.createTiddler(title);
		this.internalizeTiddler(store,tiddler,title,node);
		tiddlers.push(tiddler);
	}
};

LoaderBase.prototype.loadTiddlers = function(store,nodes)
{
	var t,tiddlers = [];
	for(t = 0; t < nodes.length; t++) {
		try {
			this.loadTiddler(store,nodes[t],tiddlers);
		} catch(ex) {
			showException(ex,config.messages.tiddlerLoadError.format([this.getTitle(store,nodes[t])]));
		}
	}
	return tiddlers;
};

function SaverBase() {}

SaverBase.prototype.externalize = function(store)
{
	var results = [];
	var t,tiddlers = store.getTiddlers("title");
	for(t = 0; t < tiddlers.length; t++) {
		if(!tiddlers[t].doNotSave())
			results.push(this.externalizeTiddler(store, tiddlers[t]));
	}
	return results.join("\n");
};

//--
//-- TW21Loader (inherits from LoaderBase)
//--

function TW21Loader() {}

TW21Loader.prototype = new LoaderBase();

TW21Loader.prototype.getTitle = function(store,node)
{
	var title = null;
	if(node.getAttribute) {
		title = node.getAttribute("title");
		if(!title)
			title = node.getAttribute("tiddler");
	}
	if(!title && node.id) {
		var lenPrefix = store.idPrefix.length;
		if(node.id.substr(0,lenPrefix) == store.idPrefix)
			title = node.id.substr(lenPrefix);
	}
	return title;
};

TW21Loader.prototype.internalizeTiddler = function(store,tiddler,title,node)
{
	var e = node.firstChild;
	var text = null;
	if(node.getAttribute("tiddler")) {
		text = getNodeText(e).unescapeLineBreaks();
	} else {
		while(e.nodeName!="PRE" && e.nodeName!="pre") {
			e = e.nextSibling;
		}
		text = e.innerHTML.replace(/\r/mg,"").htmlDecode();
	}
	var creator = node.getAttribute("creator");
	var modifier = node.getAttribute("modifier");
	var c = node.getAttribute("created");
	var m = node.getAttribute("modified");
	var created = c ? Date.convertFromYYYYMMDDHHMMSS(c) : version.date;
	var modified = m ? Date.convertFromYYYYMMDDHHMMSS(m) : created;
	var tags = node.getAttribute("tags");
	var fields = {};
	var i,attrs = node.attributes;
	for(i = attrs.length-1; i >= 0; i--) {
		var name = attrs[i].name;
		if(attrs[i].specified && !TiddlyWiki.isStandardField(name)) {
			fields[name] = attrs[i].value.unescapeLineBreaks();
		}
	}
	tiddler.assign(title,text,modifier,modified,tags,created,fields,creator);
	return tiddler;
};

//--
//-- TW21Saver (inherits from SaverBase)
//--

function TW21Saver() {}

TW21Saver.prototype = new SaverBase();

TW21Saver.prototype.externalizeTiddler = function(store,tiddler)
{
	try {
		var extendedAttributes = "";
		var usePre = config.options.chkUsePreForStorage;
		store.forEachField(tiddler,
			function(tiddler,fieldName,value) {
				// don't store stuff from the temp namespace
				if(typeof value != "string")
					value = "";
				if(!fieldName.match(/^temp\./))
					extendedAttributes += ' %0="%1"'.format([fieldName,value.escapeLineBreaks().htmlEncode()]);
			},true);
		var created = tiddler.created;
		var modified = tiddler.modified;
		var attributes = tiddler.creator ? ' creator="' + tiddler.creator.htmlEncode() + '"' : "";
		attributes += tiddler.modifier ? ' modifier="' + tiddler.modifier.htmlEncode() + '"' : "";
		attributes += (usePre && created == version.date) ? "" :' created="' + created.convertToYYYYMMDDHHMM() + '"';
		attributes += (usePre && modified == created) ? "" : ' modified="' + modified.convertToYYYYMMDDHHMM() +'"';
		var tags = tiddler.getTags();
		if(!usePre || tags)
			attributes += ' tags="' + tags.htmlEncode() + '"';
		return ('<div %0="%1"%2%3>%4</'+'div>').format([
				usePre ? "title" : "tiddler",
				tiddler.title.htmlEncode(),
				attributes,
				extendedAttributes,
				usePre ? "\n<pre>" + tiddler.text.htmlEncode() + "</pre>\n" : tiddler.text.escapeLineBreaks().htmlEncode()
			]);
	} catch (ex) {
		throw exceptionText(ex,config.messages.tiddlerSaveError.format([tiddler.title]));
	}
};

/***
|''Name''|TiddlyWebAdaptor|
|''Description''|adaptor for interacting with TiddlyWeb|
|''Author:''|FND|
|''Contributors''|Chris Dent, Martin Budden|
|''Version''|1.4.10|
|''Status''|stable|
|''Source''|http://svn.tiddlywiki.org/Trunk/association/adaptors/TiddlyWebAdaptor.js|
|''CodeRepository''|http://svn.tiddlywiki.org/Trunk/association/|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.5|
|''Keywords''|serverSide TiddlyWeb|
!Notes
This plugin includes [[jQuery JSON|http://code.google.com/p/jquery-json/]].
!To Do
* createWorkspace
* document custom/optional context attributes (e.g. filters, query, revision) and tiddler fields (e.g. server.title, origin)
!Code
***/
//{{{
(function($) {

var adaptor = config.adaptors.tiddlyweb = function() {};

adaptor.prototype = new AdaptorBase();
adaptor.serverType = "tiddlyweb";
adaptor.serverLabel = "TiddlyWeb";
adaptor.mimeType = "application/json";

adaptor.parsingErrorMessage = "Error parsing result from server";
adaptor.noBagErrorMessage = "no bag specified for tiddler";
adaptor.locationIDErrorMessage = "no bag or recipe specified for tiddler"; // TODO: rename

// retrieve current status (requires TiddlyWeb status plugin)
adaptor.prototype.getStatus = function(context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/status";
	var uri = uriTemplate.format([context.host]);
	var req = httpReq("GET", uri, adaptor.getStatusCallback, context,
		null, null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getStatusCallback = function(status, context, responseText, uri, xhr) {
	context.status = responseText ? status : false;
	try {
		context.statusText = xhr.statusText;
	} catch(exc) { // offline (Firefox)
		context.status = false;
		context.statusText = null;
	}
	context.httpStatus = xhr.status;
	if(context.status) {
		context.serverStatus = $.evalJSON(responseText); // XXX: error handling!?
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// retrieve a list of workspaces
adaptor.prototype.getWorkspaceList = function(context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.workspaces = [];
	var uriTemplate = "%0/recipes"; // XXX: bags?
	var uri = uriTemplate.format([context.host]);
	var req = httpReq("GET", uri, adaptor.getWorkspaceListCallback,
		context, { accept: adaptor.mimeType }, null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getWorkspaceListCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		try {
			var workspaces = $.evalJSON(responseText);
		} catch(ex) {
			context.status = false; // XXX: correct?
			context.statusText = exceptionText(ex, adaptor.parsingErrorMessage);
			if(context.callback) {
				context.callback(context, context.userParams);
			}
			return;
		}
		context.workspaces = workspaces.map(function(itm) { return { title: itm }; });
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// retrieve a list of tiddlers
adaptor.prototype.getTiddlerList = function(context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/%1/%2/tiddlers%3";
	var params = context.filters ? "?" + context.filters : "";
	if(context.format) {
		params = context.format + params;
	}
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name), params]);
	var req = httpReq("GET", uri, adaptor.getTiddlerListCallback,
		context, merge({ accept: adaptor.mimeType }, context.headers), null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerListCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		context.tiddlers = [];
		try {
			var tiddlers = $.evalJSON(responseText); //# NB: not actual tiddler instances
		} catch(ex) {
			context.status = false; // XXX: correct?
			context.statusText = exceptionText(ex, adaptor.parsingErrorMessage);
			if(context.callback) {
				context.callback(context, context.userParams);
			}
			return;
		}
		for(var i = 0; i < tiddlers.length; i++) {
			var tiddler = adaptor.toTiddler(tiddlers[i], context.host);
			context.tiddlers.push(tiddler);
		}
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// perform global search
adaptor.prototype.getSearchResults = function(context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/search?q=%1%2";
	var filterString = context.filters ? ";" + context.filters : "";
	var uri = uriTemplate.format([context.host, context.query, filterString]); // XXX: parameters need escaping?
	var req = httpReq("GET", uri, adaptor.getSearchResultsCallback,
		context, { accept: adaptor.mimeType }, null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getSearchResultsCallback = function(status, context, responseText, uri, xhr) {
	adaptor.getTiddlerListCallback(status, context, responseText, uri, xhr); // XXX: use apply?
};

// retrieve a particular tiddler's revisions
adaptor.prototype.getTiddlerRevisionList = function(title, limit, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/%1/%2/tiddlers/%3/revisions";
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name), adaptor.normalizeTitle(title)]);
	var req = httpReq("GET", uri, adaptor.getTiddlerRevisionListCallback,
		context, merge({ accept: adaptor.mimeType }, context.headers), null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerRevisionListCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		context.revisions = [];
		try {
			var tiddlers = $.evalJSON(responseText); //# NB: not actual tiddler instances
		} catch(ex) {
			context.status = false; // XXX: correct?
			context.statusText = exceptionText(ex, adaptor.parsingErrorMessage);
			if(context.callback) {
				context.callback(context, context.userParams);
			}
			return;
		}
		for(var i = 0; i < tiddlers.length; i++) {
			var tiddler = adaptor.toTiddler(tiddlers[i], context.host);
			context.revisions.push(tiddler);
		}
		var sortField = "server.page.revision";
		context.revisions.sort(function(a, b) {
			return a.fields[sortField] < b.fields[sortField] ? 1 :
				(a.fields[sortField] == b.fields[sortField] ? 0 : -1);
		});
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// retrieve an individual tiddler revision -- XXX: breaks with standard arguments list -- XXX: convenience function; simply use getTiddler?
adaptor.prototype.getTiddlerRevision = function(title, revision, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.revision = revision;
	return this.getTiddler(title, context, userParams, callback);
};

// retrieve an individual tiddler
adaptor.prototype.getTiddler = function(title, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = title;
	if(context.revision) {
		var uriTemplate = "%0/%1/%2/tiddlers/%3/revisions/%4";
	} else {
		uriTemplate = "%0/%1/%2/tiddlers/%3";
	}
	if(!context.tiddler) {
		context.tiddler = new Tiddler(title);
	}
	context.tiddler.fields["server.type"] = adaptor.serverType;
	context.tiddler.fields["server.host"] = AdaptorBase.minHostName(context.host);
	context.tiddler.fields["server.workspace"] = context.workspace;
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name), adaptor.normalizeTitle(title),
		context.revision]);
	var req = httpReq("GET", uri, adaptor.getTiddlerCallback, context,
		merge({ accept: adaptor.mimeType }, context.headers), null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		try {
			var tid = $.evalJSON(responseText);
		} catch(ex) {
			context.status = false;
			context.statusText = exceptionText(ex, adaptor.parsingErrorMessage);
			if(context.callback) {
				context.callback(context, context.userParams);
			}
			return;
		}
		var tiddler = adaptor.toTiddler(tid, context.host);
		tiddler.title = context.tiddler.title;
		tiddler.fields["server.etag"] = xhr.getResponseHeader("Etag");
		// normally we'd assign context.tiddler = tiddler here - but we can't do
		// that because of IE, which triggers getTiddler in putTiddlerCallback,
		// and since ServerSideSavingPlugin foolishly relies on persistent
		// object references, we need to merge the data into the existing object
		$.extend(context.tiddler, tiddler);
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// retrieve tiddler chronicle (all revisions)
adaptor.prototype.getTiddlerChronicle = function(title, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = title;
	var uriTemplate = "%0/%1/%2/tiddlers/%3/revisions?fat=1";
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name), adaptor.normalizeTitle(title)]);
	var req = httpReq("GET", uri, adaptor.getTiddlerChronicleCallback,
		context, { accept: adaptor.mimeType }, null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerChronicleCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(status) {
		context.responseText = responseText;
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// store an individual tiddler
adaptor.prototype.putTiddler = function(tiddler, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = tiddler.title;
	context.tiddler = tiddler;
	context.host = context.host || this.fullHostName(tiddler.fields["server.host"]);
	var uriTemplate = "%0/%1/%2/tiddlers/%3";
	try {
		context.workspace = context.workspace || tiddler.fields["server.workspace"];
		var workspace = adaptor.resolveWorkspace(context.workspace);
	} catch(ex) {
		return adaptor.locationIDErrorMessage;
	}
	var uri = uriTemplate.format([context.host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name),
		adaptor.normalizeTitle(tiddler.title)]);
	var etag = adaptor.generateETag(workspace, tiddler);
	var headers = etag ? { "If-Match": etag } : null;
	var payload = {
		type: tiddler.fields["server.content-type"] || null,
		text: tiddler.text,
		tags: tiddler.tags,
		fields: $.extend({}, tiddler.fields)
	};
	delete payload.fields.changecount;
	$.each(payload.fields, function(key, value) {
		if(key.indexOf("server.") == 0) {
			delete payload.fields[key];
		}
	});
	payload = $.toJSON(payload);
	var req = httpReq("PUT", uri, adaptor.putTiddlerCallback,
		context, headers, payload, adaptor.mimeType, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.putTiddlerCallback = function(status, context, responseText, uri, xhr) {
	context.status = [204, 1223].contains(xhr.status);
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(context.status) {
		var loc = xhr.getResponseHeader("Location");
		var etag = xhr.getResponseHeader("Etag");
		if(loc && etag) {
			var bag = loc.split("/bags/").pop().split("/")[0];
			context.tiddler.fields["server.bag"] = bag;
			context.tiddler.fields["server.workspace"] = "bags/" + bag;
			var rev = etag.split("/").pop().split(/;|:/)[0];
			context.tiddler.fields["server.page.revision"] = rev;
			context.tiddler.fields["server.etag"] = etag;
			if(context.callback) {
				context.callback(context, context.userParams);
			}
		} else { // IE
			context.adaptor.getTiddler(context.tiddler.title, context,
				context.userParams, context.callback);
		}
	} else if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// store a tiddler chronicle
adaptor.prototype.putTiddlerChronicle = function(revisions, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = revisions[0].title;
	var headers = null;
	var uriTemplate = "%0/%1/%2/tiddlers/%3/revisions";
	var host = context.host || this.fullHostName(tiddler.fields["server.host"]);
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name),
		adaptor.normalizeTitle(context.title)]);
	if(workspace.type == "bag") { // generate ETag
		var etag = [adaptor.normalizeTitle(workspace.name),
			adaptor.normalizeTitle(context.title), 0].join("/"); //# zero-revision prevents overwriting existing contents
		headers = { "If-Match": '"' + etag + '"' };
	}
	var payload = $.toJSON(revisions);
	var req = httpReq("POST", uri, adaptor.putTiddlerChronicleCallback,
		context, headers, payload, adaptor.mimeType, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.putTiddlerChronicleCallback = function(status, context, responseText, uri, xhr) {
	context.status = [204, 1223].contains(xhr.status);
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// store a collection of tiddlers (import TiddlyWiki HTML store)
adaptor.prototype.putTiddlerStore = function(store, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	var uriTemplate = "%0/%1/%2/tiddlers";
	var host = context.host;
	var workspace = adaptor.resolveWorkspace(context.workspace);
	var uri = uriTemplate.format([host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name)]);
	var req = httpReq("POST", uri, adaptor.putTiddlerStoreCallback,
		context, null, store, "text/x-tiddlywiki", null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.putTiddlerStoreCallback = function(status, context, responseText, uri, xhr) {
	context.status = [204, 1223].contains(xhr.status);
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// rename an individual tiddler or move it to a different workspace -- TODO: make {from|to}.title optional
adaptor.prototype.moveTiddler = function(from, to, context, userParams, callback) { // XXX: rename parameters (old/new)?
	var self = this;
	var newTiddler = store.getTiddler(from.title) || store.getTiddler(to.title); //# local rename might already have occurred
	var oldTiddler = $.extend(true, {}, newTiddler); //# required for eventual deletion
	oldTiddler.title = from.title; //# required for original tiddler's ETag
	var _getTiddlerChronicle = function(title, context, userParams, callback) {
		return self.getTiddlerChronicle(title, context, userParams, callback);
	};
	var _putTiddlerChronicle = function(context, userParams) {
		if(!context.status) {
			return callback(context, userParams);
		}
		var revisions = $.evalJSON(context.responseText); // XXX: error handling?
		// change current title while retaining previous location
		for(var i = 0; i < revisions.length; i++) {
			delete revisions[i].revision;
			if(!revisions[i].fields.origin) { // NB: origin = "<workspace>/<title>"
				revisions[i].fields.origin = ["bags", revisions[i].bag, revisions[i].title].join("/");
			}
			revisions[i].title = to.title;
		}
		// add new revision
		var rev = $.extend({}, revisions[0]);
		$.each(newTiddler, function(i, item) {
			if(!$.isFunction(item)) {
				rev[i] = item;
			}
		});
		rev.title = to.title;
		rev.created = rev.created.convertToYYYYMMDDHHMM();
		rev.modified = new Date().convertToYYYYMMDDHHMM();
		delete rev.fields.changecount;
		revisions.unshift(rev);
		if(to.workspace) {
			context.workspace = to.workspace;
		} else if(context.workspace.substring(0, 4) != "bags") { // NB: target workspace must be a bag
			context.workspace = "bags/" + rev.bag;
		}
		var subCallback = function(context, userParams) {
			if(!context.status) {
				return callback(context, userParams);
			}
			context.adaptor.getTiddler(newTiddler.title, context, userParams, _deleteTiddler);
		};
		return self.putTiddlerChronicle(revisions, context, context.userParams, subCallback);
	};
	var _deleteTiddler = function(context, userParams) {
		if(!context.status) {
			return callback(context, userParams);
		}
		$.extend(true, newTiddler, context.tiddler);
		context.callback = null;
		return self.deleteTiddler(oldTiddler, context, context.userParams, callback);
	};
	callback = callback || function() {};
	context = this.setContext(context, userParams);
	context.host = context.host || oldTiddler.fields["server.host"];
	context.workspace = from.workspace || oldTiddler.fields["server.workspace"];
	return _getTiddlerChronicle(from.title, context, userParams, _putTiddlerChronicle);
};

// delete an individual tiddler
adaptor.prototype.deleteTiddler = function(tiddler, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = tiddler.title; // XXX: not required!?
	var uriTemplate = "%0/bags/%1/tiddlers/%2";
	var host = context.host || this.fullHostName(tiddler.fields["server.host"]);
	var bag = tiddler.fields["server.bag"];
	if(!bag) {
		return adaptor.noBagErrorMessage;
	}
	var uri = uriTemplate.format([host, adaptor.normalizeTitle(bag),
		adaptor.normalizeTitle(tiddler.title)]);
	var etag = adaptor.generateETag({ type: "bag", name: bag }, tiddler);
	var headers = etag ? { "If-Match": etag } : null;
	var req = httpReq("DELETE", uri, adaptor.deleteTiddlerCallback, context, headers,
		null, null, null, null, true);
	return typeof req == "string" ? req : true;
};

adaptor.deleteTiddlerCallback = function(status, context, responseText, uri, xhr) {
	context.status = [204, 1223].contains(xhr.status);
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// compare two revisions of a tiddler (requires TiddlyWeb differ plugin)
adaptor.prototype.getTiddlerDiff = function(title, context, userParams, callback) {
	context = this.setContext(context, userParams, callback);
	context.title = title;

	var tiddler = store.getTiddler(title);
	try {
		var workspace = adaptor.resolveWorkspace(tiddler.fields["server.workspace"]);
	} catch(ex) {
		return adaptor.locationIDErrorMessage;
	}
	var tiddlerRef = [workspace.type + "s", workspace.name, tiddler.title].join("/");

	var rev1 = context.rev1 ? [tiddlerRef, context.rev1].join("/") : tiddlerRef;
	var rev2 = context.rev2 ? [tiddlerRef, context.rev2].join("/") : null;

	var uriTemplate = "%0/diff?rev1=%1";
	if(rev2) {
		uriTemplate += "&rev2=%2";
	}
	if(context.format) {
		uriTemplate += "&format=%3";
	}
	var host = context.host || this.fullHostName(tiddler.fields["server.host"]);
	var uri = uriTemplate.format([host, adaptor.normalizeTitle(rev1),
		adaptor.normalizeTitle(rev2), context.format]);

	if(rev2) {
		var req = httpReq("GET", uri, adaptor.getTiddlerDiffCallback, context, null,
			null, null, null, null, true);
	} else {
		var payload = {
			title: tiddler.title,
			text: tiddler.text,
			modifier: tiddler.modifier,
			tags: tiddler.tags,
			fields: $.extend({}, tiddler.fields)
		}; // XXX: missing attributes!?
		payload = $.toJSON(payload);
		req = httpReq("POST", uri, adaptor.getTiddlerDiffCallback, context,
			null, payload, adaptor.mimeType, null, null, true);
	}
	return typeof req == "string" ? req : true;
};

adaptor.getTiddlerDiffCallback = function(status, context, responseText, uri, xhr) {
	context.status = status;
	context.statusText = xhr.statusText;
	context.httpStatus = xhr.status;
	context.uri = uri;
	if(status) {
		context.diff = responseText;
	}
	if(context.callback) {
		context.callback(context, context.userParams);
	}
};

// generate tiddler information
adaptor.prototype.generateTiddlerInfo = function(tiddler) {
	var info = {};
	var uriTemplate = "%0/%1/%2/tiddlers/%3";
	var host = this.host || tiddler.fields["server.host"]; // XXX: this.host obsolete?
	host = this.fullHostName(host);
	var workspace = adaptor.resolveWorkspace(tiddler.fields["server.workspace"]);
	info.uri = uriTemplate.format([host, workspace.type + "s",
		adaptor.normalizeTitle(workspace.name),
		adaptor.normalizeTitle(tiddler.title)]);
	return info;
};

// create Tiddler instance from TiddlyWeb tiddler JSON
adaptor.toTiddler = function(json, host) {
	var created = Date.convertFromYYYYMMDDHHMM(json.created);
	var modified = Date.convertFromYYYYMMDDHHMM(json.modified);
	var fields = json.fields;
	fields["server.type"] = adaptor.serverType;
	fields["server.host"] = AdaptorBase.minHostName(host);
	fields["server.bag"] = json.bag;
	fields["server.title"] = json.title;
	if(json.recipe) {
		fields["server.recipe"] = json.recipe;
	}
	if(json.type && json.type != "None") {
		fields["server.content-type"] = json.type;
	}
	fields["server.permissions"] = json.permissions.join(", ");
	fields["server.page.revision"] = json.revision;
	fields["server.workspace"] = "bags/" + json.bag;
	var tiddler = new Tiddler(json.title);
	tiddler.assign(tiddler.title, json.text, json.modifier, modified, json.tags,
		created, json.fields, json.creator);
	return tiddler;
};

adaptor.resolveWorkspace = function(workspace) {
	var components = workspace.split("/");
	return {
		type: components[0] == "bags" ? "bag" : "recipe",
		name: components[1] || components[0]
	};
};

adaptor.generateETag = function(workspace, tiddler) {
	var revision = tiddler.fields["server.page.revision"];
	var etag = revision == "false" ? null : tiddler.fields["server.etag"];
	if(!etag && workspace.type == "bag") {
		if(typeof revision == "undefined") {
			revision = "0";
		} else if(revision == "false") {
			return null;
		}
		etag = [adaptor.normalizeTitle(workspace.name),
			adaptor.normalizeTitle(tiddler.title), revision].join("/");
		etag = '"' + etag + '"';
	}
	return etag;
};

adaptor.normalizeTitle = function(title) {
	return encodeURIComponent(title);
};

})(jQuery);


/*
 * jQuery JSON Plugin
 * version: 1.3
 * source: http://code.google.com/p/jquery-json/
 * license: MIT (http://www.opensource.org/licenses/mit-license.php)
 */
(function($){function toIntegersAtLease(n)
{return n<10?'0'+n:n;}
Date.prototype.toJSON=function(date)
{return this.getUTCFullYear()+'-'+
toIntegersAtLease(this.getUTCMonth())+'-'+
toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(string)
{if(escapeable.test(string))
{return'"'+string.replace(escapeable,function(a)
{var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};$.toJSON=function(o,compact)
{var type=typeof(o);if(type=="undefined")
return"undefined";else if(type=="number"||type=="boolean")
return o+"";else if(o===null)
return"null";if(type=="string")
{return $.quoteString(o);}
if(type=="object"&&typeof o.toJSON=="function")
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
if(compact)
return"["+ret.join(",")+"]";else
return"["+ret.join(", ")+"]";}
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
if(compact)
ret.push(name+":"+val);else
ret.push(name+": "+val);}
return"{"+ret.join(", ")+"}";};$.compactJSON=function(o)
{return $.toJSON(o,true);};$.evalJSON=function(src)
{return eval("("+src+")");};$.secureEvalJSON=function(src)
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};})(jQuery);
//}}}
/***
|''Name''|ServerSideSavingPlugin|
|''Description''|server-side saving|
|''Author''|FND|
|''Version''|0.6.5|
|''Status''|stable|
|''Source''|http://svn.tiddlywiki.org/Trunk/association/plugins/ServerSideSavingPlugin.js|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.5.3|
|''Keywords''|serverSide|
!Notes
This plugin relies on a dedicated adaptor to be present.
The specific nature of this plugin depends on the respective server.
!Revision History
!!v0.1 (2008-11-24)
* initial release
!!v0.2 (2008-12-01)
* added support for local saving
!!v0.3 (2008-12-03)
* added Save to Web macro for manual synchronization
!!v0.4 (2009-01-15)
* removed ServerConfig dependency by detecting server type from the respective tiddlers
!!v0.5 (2009-08-25)
* raised CoreVersion to 2.5.3 to take advantage of core fixes
!!v0.6 (2010-04-21)
* added notification about cross-domain restrictions to ImportTiddlers
!To Do
* conflict detection/resolution
* rename to ServerLinkPlugin?
* document deletion/renaming convention
!Code
***/
//{{{
(function($) {

readOnly = false; //# enable editing over HTTP

var plugin = config.extensions.ServerSideSavingPlugin = {};

plugin.locale = {
	saved: "%0 saved successfully",
	saveError: "Error saving %0: %1",
	saveConflict: "Error saving %0: edit conflict",
	deleted: "Removed %0",
	deleteError: "Error removing %0: %1",
	deleteLocalError: "Error removing %0 locally",
	removedNotice: "This tiddler has been deleted.",
	connectionError: "connection could not be established",
	hostError: "Unable to import from this location due to cross-domain restrictions."
};

plugin.sync = function(tiddlers) {
	tiddlers = tiddlers && tiddlers[0] ? tiddlers : store.getTiddlers();
	$.each(tiddlers, function(i, tiddler) {
		var changecount = parseInt(tiddler.fields.changecount, 10);
		if(tiddler.fields.deleted === "true" && changecount === 1) {
			plugin.removeTiddler(tiddler);
		} else if(tiddler.isTouched() && !tiddler.doNotSave() &&
				tiddler.getServerType() && tiddler.fields["server.host"]) { // XXX: server.host could be empty string
			delete tiddler.fields.deleted;
			plugin.saveTiddler(tiddler);
		}
	});
};

plugin.saveTiddler = function(tiddler) {
	try {
		var adaptor = this.getTiddlerServerAdaptor(tiddler);
	} catch(ex) {
		return false;
	}
	var context = {
		tiddler: tiddler,
		changecount: tiddler.fields.changecount,
		workspace: tiddler.fields["server.workspace"]
	};
	var serverTitle = tiddler.fields["server.title"]; // indicates renames
	if(!serverTitle) {
		tiddler.fields["server.title"] = tiddler.title;
	} else if(tiddler.title != serverTitle) {
		return adaptor.moveTiddler({ title: serverTitle },
			{ title: tiddler.title }, context, null, this.saveTiddlerCallback);
	}
	var req = adaptor.putTiddler(tiddler, context, {}, this.saveTiddlerCallback);
	return req ? tiddler : false;
};

plugin.saveTiddlerCallback = function(context, userParams) {
	var tiddler = context.tiddler;
	if(context.status) {
		if(tiddler.fields.changecount == context.changecount) { //# check for changes since save was triggered
			tiddler.clearChangeCount();
		} else if(tiddler.fields.changecount > 0) {
			tiddler.fields.changecount -= context.changecount;
		}
		plugin.reportSuccess("saved", tiddler);
		store.setDirty(false);
	} else {
		if(context.httpStatus == 412) {
			plugin.reportFailure("saveConflict", tiddler);
		} else {
			plugin.reportFailure("saveError", tiddler, context);
		}
	}
};

plugin.removeTiddler = function(tiddler) {
	try {
		var adaptor = this.getTiddlerServerAdaptor(tiddler);
	} catch(ex) {
		return false;
	}
	var context = {
		host: tiddler.fields["server.host"],
		workspace: tiddler.fields["server.workspace"],
		tiddler: tiddler
	};
	var req = adaptor.deleteTiddler(tiddler, context, {}, this.removeTiddlerCallback);
	return req ? tiddler : false;
};

plugin.removeTiddlerCallback = function(context, userParams) {
	var tiddler = context.tiddler;
	if(context.status) {
		if(tiddler.fields.deleted === "true") {
			store.deleteTiddler(tiddler.title);
		} else {
			plugin.reportFailure("deleteLocalError", tiddler);
		}
		plugin.reportSuccess("deleted", tiddler);
		store.setDirty(false);
	} else {
		plugin.reportFailure("deleteError", tiddler, context);
	}
};

plugin.getTiddlerServerAdaptor = function(tiddler) { // XXX: rename?
	var type = tiddler.fields["server.type"] || config.defaultCustomFields["server.type"];
	return new config.adaptors[type]();
};

plugin.reportSuccess = function(msg, tiddler) {
	displayMessage(plugin.locale[msg].format([tiddler.title]));
};

plugin.reportFailure = function(msg, tiddler, context) {
	var desc = (context && context.httpStatus) ? context.statusText :
		plugin.locale.connectionError;
	displayMessage(plugin.locale[msg].format([tiddler.title, desc]));
};

config.macros.saveToWeb = { // XXX: hijack existing sync macro?
	locale: { // TODO: merge with plugin.locale?
		btnLabel: "save to web",
		btnTooltip: "synchronize changes",
		btnAccessKey: null
	},

	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		createTiddlyButton(place, this.locale.btnLabel, this.locale.btnTooltip,
			plugin.sync, null, null, this.locale.btnAccessKey);
	}
};

window.saveChanges = function(onlyIfDirty, tiddlers) {
	plugin.sync(tiddlers);
};

// override removeTiddler to flag tiddler as deleted -- XXX: use hijack to preserve compatibility?
TiddlyWiki.prototype.removeTiddler = function(title) { // XXX: should override deleteTiddler instance method?
	var tiddler = this.fetchTiddler(title);
	if(tiddler) {
		tiddler.tags = ["excludeLists", "excludeSearch", "excludeMissing"];
		tiddler.text = plugin.locale.removedNotice;
		tiddler.fields.deleted = "true"; // XXX: rename to removed/tiddlerRemoved?
		tiddler.fields.changecount = "1";
		this.notify(title, true);
		this.setDirty(true);
	}
};

// hijack ImportTiddlers wizard to handle cross-domain restrictions
var _onOpen = config.macros.importTiddlers.onOpen;
config.macros.importTiddlers.onOpen = function(ev) {
	var btn = $(resolveTarget(ev));
	var url = btn.closest(".wizard").find("input[name=txtPath]").val();
	if(window.location.protocol != "file:" && url.indexOf("://") != -1) {
		var host = url.split("/")[2];
		var macro = config.macros.importTiddlers;
		if(host != window.location.host) {
			btn.text(macro.cancelLabel).attr("title", macro.cancelPrompt);
			btn[0].onclick = macro.onCancel;
			$('<span class="status" />').text(plugin.locale.hostError).insertAfter(btn);
			return false;
		}
	}
	return _onOpen.apply(this, arguments);
};

})(jQuery);
//}}}
//--
//-- Backstage
//--
// Backstage tasks
config.tasks.save.action = saveChanges;

var backstage = {
	area: null,
	toolbar: null,
	button: null,
	showButton: null,
	hideButton: null,
	cloak: null,
	panel: null,
	panelBody: null,
	panelFooter: null,
	currTabName: null,
	currTabElem: null,
	content: null,

	init: function() {
		var cmb = config.messages.backstage;
		this.area = document.getElementById("backstageArea");
		this.toolbar = jQuery("#backstageToolbar").empty()[0];
		this.button = jQuery("#backstageButton").empty()[0];
		this.button.style.display = "block";
		var t = cmb.open.text + " " + glyph("bentArrowLeft");
		this.showButton = createTiddlyButton(this.button,t,cmb.open.tooltip,
						function(e) {backstage.show(); return false;},null,"backstageShow");
		t = glyph("bentArrowRight") + " " + cmb.close.text;
		this.hideButton = createTiddlyButton(this.button,t,cmb.close.tooltip,
						function(e) {backstage.hide(); return false;},null,"backstageHide");
		this.cloak = document.getElementById("backstageCloak");
		this.panel = document.getElementById("backstagePanel");
		this.panelFooter = createTiddlyElement(this.panel,"div",null,"backstagePanelFooter");
		this.panelBody = createTiddlyElement(this.panel,"div",null,"backstagePanelBody");
		this.cloak.onmousedown = function(e) {backstage.switchTab(null);};
		createTiddlyText(this.toolbar,cmb.prompt);
		for(t=0; t<config.backstageTasks.length; t++) {
			var taskName = config.backstageTasks[t];
			var task = config.tasks[taskName];
			var handler = task.action ? this.onClickCommand : this.onClickTab;
			var text = task.text + (task.action ? "" : glyph("downTriangle"));
			var btn = createTiddlyButton(this.toolbar,text,task.tooltip,handler,"backstageTab");
			jQuery(btn).addClass(task.action ? "backstageAction" : "backstageTask");
			btn.setAttribute("task", taskName);
			}
		this.content = document.getElementById("contentWrapper");
		if(config.options.chkBackstage)
			this.show();
		else
			this.hide();
	},

	isVisible: function() {
		return this.area ? this.area.style.display == "block" : false;
	},

	show: function() {
		this.area.style.display = "block";
		if(anim && config.options.chkAnimate) {
			backstage.toolbar.style.left = findWindowWidth() + "px";
			var p = [{style: "left", start: findWindowWidth(), end: 0, template: "%0px"}];
			anim.startAnimating(new Morpher(backstage.toolbar,config.animDuration,p));
		} else {
			backstage.area.style.left = "0px";
		}
		jQuery(this.showButton).hide();
		jQuery(this.hideButton).show();
		config.options.chkBackstage = true;
		saveOption("chkBackstage");
		jQuery(this.content).addClass("backstageVisible");
	},

	hide: function() {
		if(this.currTabElem) {
			this.switchTab(null);
		} else {
			backstage.toolbar.style.left = "0px";
			if(anim && config.options.chkAnimate) {
				var p = [{style: "left", start: 0, end: findWindowWidth(), template: "%0px"}];
				var c = function(element,properties) {backstage.area.style.display = "none";};
				anim.startAnimating(new Morpher(backstage.toolbar,config.animDuration,p,c));
			} else {
				this.area.style.display = "none";
			}
			this.showButton.style.display = "block";
			this.hideButton.style.display = "none";
			config.options.chkBackstage = false;
			saveOption("chkBackstage");
			jQuery(this.content).removeClass("backstageVisible");
		}
	},

	onClickCommand: function(e) {
		var task = config.tasks[this.getAttribute("task")];
		if(task.action) {
			backstage.switchTab(null);
			task.action();
		}
		return false;
	},

	onClickTab: function(e) {
		backstage.switchTab(this.getAttribute("task"));
		return false;
	},

	// Switch to a given tab, or none if null is passed
	switchTab: function(tabName) {
		var tabElem = null;
		var e = this.toolbar.firstChild;
		while(e) {
			if(e.getAttribute && e.getAttribute("task") == tabName)
				tabElem = e;
			e = e.nextSibling;
		}
		if(tabName == backstage.currTabName) {
			backstage.hidePanel();
			return;
		}
		if(backstage.currTabElem) {
			jQuery(this.currTabElem).removeClass("backstageSelTab");
		}
		if(tabElem && tabName) {
			backstage.preparePanel();
			jQuery(tabElem).addClass("backstageSelTab");
			var task = config.tasks[tabName];
			wikify(task.content,backstage.panelBody,null,null);
			backstage.showPanel();
		} else if(backstage.currTabElem) {
			backstage.hidePanel();
		}
		backstage.currTabName = tabName;
		backstage.currTabElem = tabElem;
	},

	isPanelVisible: function() {
		return backstage.panel ? backstage.panel.style.display == "block" : false;
	},

	preparePanel: function() {
		backstage.cloak.style.height = findDocHeight() + "px";
		backstage.cloak.style.display = "block";
		jQuery(backstage.panelBody).empty();
		return backstage.panelBody;
	},

	showPanel: function() {
		backstage.panel.style.display = "block";
		if(anim && config.options.chkAnimate) {
			backstage.panel.style.top = (-backstage.panel.offsetHeight) + "px";
			var p = [{style: "top", start: -backstage.panel.offsetHeight, end: 0, template: "%0px"}];
			anim.startAnimating(new Morpher(backstage.panel,config.animDuration,p),new Scroller(backstage.panel,false));
		} else {
			backstage.panel.style.top = "0px";
		}
		return backstage.panelBody;
	},

	hidePanel: function() {
		if(backstage.currTabElem)
			jQuery(backstage.currTabElem).removeClass("backstageSelTab");
		backstage.currTabElem = null;
		backstage.currTabName = null;
		if(anim && config.options.chkAnimate) {
			var p = [
				{style: "top", start: 0, end: -(backstage.panel.offsetHeight), template: "%0px"},
				{style: "display", atEnd: "none"}
			];
			var c = function(element,properties) {backstage.cloak.style.display = "none";};
			anim.startAnimating(new Morpher(backstage.panel,config.animDuration,p,c));
		} else {
			jQuery([backstage.panel,backstage.cloak]).hide();
		}
	}
};

config.macros.backstage = {};

config.macros.backstage.handler = function(place,macroName,params)
{
	var backstageTask = config.tasks[params[0]];
	if(backstageTask)
		createTiddlyButton(place,backstageTask.text,backstageTask.tooltip,function(e) {backstage.switchTab(params[0]); return false;});
};

//--
//-- Main
//--

var params = null; // Command line parameters
var store = null; // TiddlyWiki storage
var story = null; // Main story
var formatter = null; // Default formatters for the wikifier
var anim = typeof Animator == "function" ? new Animator() : null; // Animation engine
var readOnly = false; // Whether we're in readonly mode
var highlightHack = null; // Embarrassing hack department...
var hadConfirmExit = false; // Don't warn more than once
var safeMode = false; // Disable all plugins and cookies
var showBackstage; // Whether to include the backstage area
var installedPlugins = []; // Information filled in when plugins are executed
var startingUp = false; // Whether we're in the process of starting up
var pluginInfo,tiddler; // Used to pass information to plugins in loadPlugins()

jQuery(document).ready(function() {

jQuery("#contentWrapper").addClass("loading").text("Loading Space...");

var total_tiddlers = -1;
ajaxReq({ dataType: "text", url: "/tiddlers", success: function(text) {
	total_tiddlers = text.split("\n").length;
}
});

ajaxReq({ dataType: "json", url: "/status", success: function(status) {
	var host = window.location.protocol + "//" + window.location.hostname;
	var workspace = "recipes/" + status["space"]["recipe"];
	config.defaultCustomFields = {
		"server.workspace": workspace,
		"server.type": "tiddlyweb",
		"server.host": host
	};
	var defaults = config.defaultCustomFields;
	var filter = "?mselect=tag:systemConfig,tag:excludeLists&type:!text/css&select=type:!text/html&select=type:!image/png&select=type:!image/jpg&select=type:!image/gif&select=type:!image/jpeg";
	var time = 0, start = 0, total = 50;
	var lazy_load_content = function(title) {
		window.setTimeout(function() {
			if(time < 0) {
				return;
			}
			ajaxReq({
				dataType: "json",
				data: {
					"fat": "1"
				},
				url: host + "/tiddlers?sort=-modified&limit=" + start + "," + total,
				success: function(tids) {
					for(var i = 0; i < tids.length; i++) {
						var tid = config.adaptors.tiddlyweb.toTiddler(tids[i], host);
						store.addTiddler(tid);
						store.notify(tid.title);
						story.refreshTiddler(tid.title, null, true);
					}
					if(tids.length === 0) {
						time = -1;
					} else {
						if(total_tiddlers > -1) {
							var pc = 100 - Math.floor(((total_tiddlers - store.getTiddlers().length) / total_tiddlers) * 100);
							displayMessage(pc + "% of document loaded.");
						}
						start += total;
						time += 100;
						lazy_load_content(title);
					}
				},
			});
		}, time);
	}
	var success = function(json) {
		store = new TiddlyWiki({config:config});
		invokeParamifier(params,"oninit");
		story = new Story("tiddlerDisplay","tiddler");
		jQuery("#contentWrapper").removeClass("loading");
		for(var i = 0; i < json.length; i++) {
			var title = json[i].title;
			if(["ServerSideSavingPlugin",
				"TiddlySpaceInit", "TiddlyWebAdaptor", "LoadMissingTiddlersPlugin"].indexOf(title) === -1) {
				var tid = config.adaptors.tiddlyweb.toTiddler(json[i], host);
				store.addTiddler(tid);
			}
		}
		lazy_load_content();
		main();
	};
	ajaxReq({
		dataType: "json",
		data: {
			"fat": "1"
		},
		url: host + "/" + workspace + "/tiddlers" + filter,
		success: function(tiddlers) {
			success(tiddlers);
		},
		error: function() {
			jQuery("#contentWrapper").addClass("error").text("Error occurred loading your tiddlers");
		}
	});
}});
});

// Starting up
function main()
{
	var t10,t9,t8,t7,t6,t5,t4,t3,t2,t1,t0 = new Date();
	startingUp = true;
	var doc = jQuery(document);
	jQuery.noConflict();
	window.onbeforeunload = function(e) {if(window.confirmExit) return confirmExit();};
	params = getParameters();
	if(params)
		params = params.parseParams("open",null,false);
	addEvent(document,"click",Popup.onDocumentClick);
	var s;
	for(s=0; s<config.notifyTiddlers.length; s++)
		store.addNotification(config.notifyTiddlers[s].name,config.notifyTiddlers[s].notify);
	t1 = new Date();
	loadShadowTiddlers();
	doc.trigger("loadShadows");
	t2 = new Date();
	store.loadFromDiv("storeArea","store",true);
	doc.trigger("loadTiddlers");
	loadOptions();
	t3 = new Date();
	invokeParamifier(params,"onload");
	t4 = new Date();
	readOnly = (window.location.protocol == "file:") ? false : config.options.chkHttpReadOnly;
	var pluginProblem = loadPlugins("systemConfig");
	doc.trigger("loadPlugins");
	t5 = new Date();
	formatter = new Formatter(config.formatters);
	invokeParamifier(params,"onconfig");
	story.switchTheme(config.options.txtTheme);
	showBackstage = showBackstage !== undefined ? showBackstage : !readOnly;
	t6 = new Date();
	var m;
	for(m in config.macros) {
		if(config.macros[m].init)
			config.macros[m].init();
	}
	t7 = new Date();
	store.notifyAll();
	t8 = new Date();
	restart();
	refreshDisplay();
	t9 = new Date();
	if(pluginProblem) {
		story.displayTiddler(null,"PluginManager");
		displayMessage(config.messages.customConfigError);
	}
	if(showBackstage)
		backstage.init();
	t10 = new Date();
	if(config.options.chkDisplayInstrumentation) {
		displayMessage("LoadShadows " + (t2-t1) + " ms");
		displayMessage("LoadFromDiv " + (t3-t2) + " ms");
		displayMessage("LoadPlugins " + (t5-t4) + " ms");
		displayMessage("Macro init " + (t7-t6) + " ms");
		displayMessage("Notify " + (t8-t7) + " ms");
		displayMessage("Restart " + (t9-t8) + " ms");
		displayMessage("Total: " + (t10-t0) + " ms");
	}
	startingUp = false;
	doc.trigger("startup");
}

// Called on unload. All functions called conditionally since they themselves may have been unloaded.
function unload()
{
	if(window.checkUnsavedChanges)
		checkUnsavedChanges();
	if(window.scrubNodes)
		scrubNodes(document.body);
}

// Restarting
function restart()
{
	invokeParamifier(params,"onstart");
	if(story.isEmpty()) {
		story.displayDefaultTiddlers();
	}
	window.scrollTo(0,0);
}

function loadShadowTiddlers()
{
	var shadows = new TiddlyWiki();
	shadows.loadFromDiv("shadowArea","shadows",true);
	shadows.forEachTiddler(function(title,tiddler){config.shadowTiddlers[title] = tiddler.text;});
}

function loadPlugins(tag)
{
	if(safeMode)
		return false;
	var tiddlers = store.getTaggedTiddlers(tag);
	tiddlers.sort(function(a,b) {return a.title < b.title ? -1 : (a.title == b.title ? 0 : 1);});
	var toLoad = [];
	var nLoaded = 0;
	var map = {};
	var nPlugins = tiddlers.length;
	installedPlugins = [];
	var i;
	for(i=0; i<nPlugins; i++) {
		var p = getPluginInfo(tiddlers[i]);
		installedPlugins[i] = p;
		var n = p.Name || p.title;
		if(n)
			map[n] = p;
		n = p.Source;
		if(n)
			map[n] = p;
	}
	var visit = function(p) {
		if(!p || p.done)
			return;
		p.done = 1;
		var reqs = p.Requires;
		if(reqs) {
			reqs = reqs.readBracketedList();
			var i;
			for(i=0; i<reqs.length; i++)
				visit(map[reqs[i]]);
		}
		toLoad.push(p);
	};
	for(i=0; i<nPlugins; i++)
		visit(installedPlugins[i]);
	for(i=0; i<toLoad.length; i++) {
		p = toLoad[i];
		pluginInfo = p;
		tiddler = p.tiddler;
		if(isPluginExecutable(p)) {
			if(isPluginEnabled(p)) {
				p.executed = true;
				var startTime = new Date();
				try {
					if(tiddler.text)
						window.eval(tiddler.text);
					nLoaded++;
				} catch(ex) {
					p.log.push(config.messages.pluginError.format([exceptionText(ex)]));
					p.error = true;
					if(!console.tiddlywiki) {
						console.log("error evaluating " + tiddler.title, ex);
					}
				}
				pluginInfo.startupTime = String((new Date()) - startTime) + "ms";
			} else {
				nPlugins--;
			}
		} else {
			p.warning = true;
		}
	}
	return nLoaded != nPlugins;
}

function getPluginInfo(tiddler)
{
	var p = store.getTiddlerSlices(tiddler.title,["Name","Description","Version","Requires","CoreVersion","Date","Source","Author","License","Browsers"]);
	p.tiddler = tiddler;
	p.title = tiddler.title;
	p.log = [];
	return p;
}

// Check that a particular plugin is valid for execution
function isPluginExecutable(plugin)
{
	if(plugin.tiddler.isTagged("systemConfigForce")) {
		plugin.log.push(config.messages.pluginForced);
		return true;
	}
	if(plugin["CoreVersion"]) {
		var coreVersion = plugin["CoreVersion"].split(".");
		var w = parseInt(coreVersion[0],10) - version.major;
		if(w == 0 && coreVersion[1])
			w = parseInt(coreVersion[1],10) - version.minor;
		if(w == 0 && coreVersion[2])
			w = parseInt(coreVersion[2],10) - version.revision;
		if(w > 0) {
			plugin.log.push(config.messages.pluginVersionError);
			return false;
		}
	}
	return true;
}

function isPluginEnabled(plugin)
{
	if(plugin.tiddler.isTagged("systemConfigDisable")) {
		plugin.log.push(config.messages.pluginDisabled);
		return false;
	}
	return true;
}
To upload a file use the form below:
<<binaryUploadPublic>>

/***
|''Name''|JRgedcom|
|''Description''|Turns a text file GEDCOM into traversable XML.|
|''Version''|0.2.0|
|''Author''|Jon Robson|
|''License''|BSD|
!Notes
Note this implementation is incomplete and may not import all data from a GEDCOM file. It however should import the basic structure of a family tree.
***/
//{{{
var gedcom;
(function($) {
gedcom = {
	_convert_to_timestamp: function(value, time) {
		// TODO: cope with FROM 1 JAN 1980 TO 1 FEB 1982
		// TODO: cope with ABT 1809
		// TODO: cope with time arg
		var timestamp = "000000";
		// STRIP prefixes
		if(value.indexOf("ABT ") > -1) {
			value = value.substr(value.indexOf("ABT ") + "ABT ".length, value.length)
		}
		var parts = value.split(" ");
		if(parts.length === 1) { // assume just a year
			return parts[0] + "0000";
		} else if(parts.length > 1) {
			var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
			var monthid, date;
			if(parts.length > 2) {
				date = parts[0];
				monthid = months.indexOf(parts[1]) + 1;
			} else {
				date = "00";
				monthid = months.indexOf(parts[0]) + 1;
			}
			monthid = monthid < 10 ? "0" + monthid : monthid;
			return parts[2]  + monthid + date + timestamp;
		} else {
			return value;
		}
	},
	_get_info_from_line: function(line) {
		var level, tag, value;
		var m = line.match(/([^ ]*) ([^ ]*) (.*)/);
		if(m) {
			level = m[1]
			tag = m[2];
			value = m[3];
		} else {
			m = line.match(/([^ ]*) ([^ ]*)/);
			if(m) {
				level = m[1];
				tag = m[2];
			}
		}
		var rtn = {level: level, tag: tag, value: value};
		return rtn;
	},
	import: function(text) {
		var g = this;
		var xml = this.toXML(text);
		var tiddlers = {};
		function newTiddler(name) {
			if(name && !tiddlers[name]) {
				tiddlers[name] = { title: name, fields: { spouses: [] } };
			}
		}
		var families = [];
		$('[data-value="INDI"]', xml).each(function(i, el) {
			var name = $(el).attr("data-title");
			var value = $(el).attr("data-value");

			newTiddler(name);
			var title = $('[data-title="NAME"]', el).attr("data-value");
			var surname = title.match(/\/(.*)\//)[1];
			title = title.replace(/\/(.*)\//, "$1") + " (" + name + ")";
			var sex = $('[data-title="SEX"]', el).attr("data-value");
			var dob = $('[data-title="BIRT"] [data-title="DATE"]', el).attr("data-value");
			var dod = $('[data-title="DEAT"] [data-title="DATE"]', el).attr("data-value");
			var dob_time = $('[data-title="BIRT"] [data-title="TIME"]', el).attr("data-value");
			var dod_time = $('[data-title="DEAT"] [data-title="TIME"]', el).attr("data-value");
			var placeofbirth = $('[data-title="BIRT"] [data-title="PLAC"]', el).attr("data-value");
			var placeofdeath = $('[data-title="DEAT"] [data-title="PLAC"]', el).attr("data-value");
			var occupation = $('[data-title="OCCU"]', el).attr("data-value");
			var placeofburial = $('[data-title="BURI"] [data-title="PLAC"]', el).attr("data-value");
			var causeofdeath = $('[data-title="DEAT"] [data-title="CAUS"]', el).attr("data-value");
			tiddlers[name].fields.surname = surname;
			tiddlers[name].title = title;
			if(placeofburial) {
				tiddlers[name].fields.placeofburial = placeofburial;
			}
			if(placeofdeath) {
				tiddlers[name].fields.placeofdeath = placeofdeath;
			}
			if(dob) {
				if(dob.indexOf("ABT ") > -1) {
					tiddlers[name].fields.dobaccuracy = "about";
				}
				tiddlers[name].fields.dob = g._convert_to_timestamp(dob, dob_time);
			}
			tiddlers[name].fields.sex = sex;
			if(dod) {
				if(dod.indexOf("ABT ") > -1) {
					tiddlers[name].fields.dodaccuracy = "about";
				}
				tiddlers[name].fields.dod = g._convert_to_timestamp(dod, dod_time);
			}
			if(placeofbirth) {
				tiddlers[name].fields.placeofbirth = placeofbirth;
			}
			if(occupation) {
				tiddlers[name].fields.occupation = occupation;
			}
			if(causeofdeath) {
				tiddlers[name].fields.causeofdeath = causeofdeath;
			}
		});

		$('[data-value="FAM"]', xml).each(function(i, el) {
			var husb = $('[data-title="HUSB"]', el).attr("data-value");
			var wife = $('[data-title="WIFE"]', el).attr("data-value");
			newTiddler(husb);
			newTiddler(wife);
			$('[data-title="CHIL"]', el).each(function(i, child) {
				var name = $(child).attr("data-value");
				newTiddler(name);
				if(husb) {
					tiddlers[name].fields.father = tiddlers[husb].title;
				}
				if(wife) {
					tiddlers[name].fields.mother = tiddlers[wife].title;
				}
			});
			if(husb && wife) {
				tiddlers[husb].fields.spouses.push(tiddlers[wife].title);
				tiddlers[wife].fields.spouses.push(tiddlers[husb].title);
			}
			var dom = $('[data-title="MARR"] [data-title="DATE"]', el).attr("data-value");
			if(dom) {
				tiddlers[wife].fields.dom = dom;
				tiddlers[husb].fields.dom = dom;
			}
		});
		var tids = [];
		for(var i in tiddlers) {
			if(true) {
				tids.push(tiddlers[i]);
			}
		}
		return tids;
	},
	toXML: function(text) {
		var tree = document.createElement("div");
		tree.setAttribute("title", "root");
		var lines = text.split("\n");
		// lines.length
		var lastNode;
		for(var i = 0; i < lines.length - 1; i++) {
			var line = lines[i];
			var info = gedcom._get_info_from_line(line)
			var tag = info.tag;
			var val = info.value;
			var level = info.level;
			if(tag) {
				if(tag === "CONT") {
					if(lastNode) {
						var newVal = lastNode.getAttribute("data-value") + "\n" + val;
						lastNode.setAttribute("data-value", newVal);
					}
				} else if(tag == "CONC") {
					if(lastNode) {
						var newVal = lastNode.getAttribute("data-value") + val;
						lastNode.setAttribute("data-value", newVal);
					}
				} else {
					var node = document.createElement("div");
					node.setAttribute("data-title", tag);
					if(val) {
						node.setAttribute("data-value", val);
					}
					var levelNo = parseInt(level, 10);
					var parent = tree;
					for(var j = 0; j < levelNo; j++) {
						//console.log(j, levelNo, tree.childNodes);
						parent = parent.childNodes[parent.childNodes.length - 1];
					}
					parent.appendChild(node);
					lastNode = node;
				}
			}
		}
		return tree;
	}
}
})(jQuery);
//}}}
(function() {
var getCSRFToken = function(window) {
	// XXX: should not use RegEx - cf.
	// http://www.quirksmode.org/js/cookies.html
	// https://github.com/TiddlySpace/tiddlyspace/commit/5f4adbe009ed4bda3ce39058a3fb07de1420358d
	var regex = /^(?:.*; )?csrf_token=([^(;|$)]*)(?:;|$)/;
	var match = regex.exec(document.cookie);
	var csrf_token = null;
	if (match && (match.length === 2)) {
		csrf_token = match[1];
	}

	return csrf_token;
};

if (typeof config !== 'undefined' && config.extensions &&
		config.extensions.tiddlyspace &&
		config.extensions.tiddlyspace.getCSRFToken === null) {
	config.extensions.tiddlyspace.getCSRFToken = getCSRFToken;
} else {
	window.getCSRFToken = getCSRFToken;
}
})(window);
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" version="1.1" viewBox="434 218 68 68"
width="30" height="30">
<g stroke="none" stroke-opacity="1" stroke-dasharray="none" fill="none" fill-opacity="1">
	<g>
		<path d="M 478.39694 232.53705 L 478.39694 232.53705 
		C 477.1145 231.85132 475.77875 231.30147 474.41058 230.88734 L 474.41058 218.24994 L 461.58942 218.24994 
		L 461.58942 230.88734 C 460.22125 231.30147 458.8855 231.85132 457.60306 232.53705 L 448.66824 223.60214 
		L 439.6022 232.66814 L 448.53717 241.60304 C 447.8515 242.8854 447.30157 244.22116 446.88745 245.58936 
		L 434.25 245.58936 L 434.25 258.41052 L 446.88745 258.41052 
		C 447.30157 259.77869 447.8515 261.11447 448.53717 262.39688 L 439.6022 271.33173 L 448.66824 280.3978 
		L 457.60306 271.46283 C 458.8855 272.14862 460.22125 272.69846 461.58942 273.11252 L 461.58942 285.74988 
		L 474.41058 285.74988 L 474.41058 273.11252 C 475.77875 272.69846 477.1145 272.14862 478.39694 271.46283 
		L 487.33176 280.3978 L 496.39767 271.33173 L 487.46286 262.39688 
		C 488.14853 261.11447 488.69836 259.77869 489.11255 258.41052 L 501.74988 258.41052 L 501.74988 245.58936 
		L 489.11255 245.58936 C 488.69836 244.22116 488.14853 242.8854 487.46286 241.60304 L 496.39767 232.66814 
		L 487.33176 223.60214 Z M 475.3328 244.66714 C 479.3825 248.71698 479.3825 255.2829 475.3328 259.33273 
		C 471.28296 263.3826 464.71704 263.3826 460.66724 259.33273 
		C 456.61737 255.2829 456.61737 248.71698 460.66724 244.66714 
		C 464.71704 240.61734 471.28296 240.61734 475.3328 244.66714" fill="#111"
		class="glyph"/>
	</g>
</g>
</svg>
/***
|''Name''|GEDCOMImporterPlugin|
|''Description''|Imports gedcom files into tiddlywiki|
|''Version''|0.2.1|
|''Requires''|JRGgedcom.js|
|''Author''|Jon Robson|
|''License''|BSD|
***/
//{{{
(function($) {
var macro = config.macros.gedcomImport = {
	locale: {
		describe: "Please paste the text of your gedcom file into the box below to import it into this TiddlyWiki"
	},
	handler: function(place) {
		var container = $("<div />").appendTo(place)[0];
		$("<div/>").text(macro.locale.describe).appendTo(container);
		$("<textarea />").appendTo(container);
		$("<button />").appendTo(container).text("import gedcom").click(function(ev) {
			var text = $("textarea", container).val();
			$("textarea", container).val("");
			var tiddlers = gedcom.import(text);
			$(ev.target).attr("disabled", true);
			var save = [];
			for(var i = 0; i < tiddlers.length; i++) {
				var tid = tiddlers[i];
				var tiddler = new Tiddler(tid.title);
				tiddler.text = tid.text || "";
				tiddler.fields = tid.fields;
				if(tid.fields.spouses) {
					tiddler.fields.spouse = String.encodeTiddlyLinkList(tid.fields.spouses);
					delete tiddler.fields.spouses;
				}
				tiddler.tags = tid.tags || [];
				merge(tiddler.fields, config.defaultCustomFields);
				tiddler = store.saveTiddler(tiddler);
				save.push(tiddler);
			}
			autoSaveChanges(null, save)
			refreshAll();
			$(ev.target).attr("disabled", false);
		})
	}
};

})(jQuery);
//}}}
/***
|''Name''|TiddlySpaceFollowingWizard|
|''Version''|0.7.0|
|''Description''|Provides a following wizard macro and deleteButton view type|
|''Author''|Jon Robson|
|''Requires''|TiddlySpaceConfig TiddlySpaceFollowingPlugin TiddlySpaceTiddlerIconsPlugin|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
!Usage
{{{ <<followWizard>> }}}
!StyleSheet
.followWizard ul,
.followWizard li .siteIcon,
.followWizard li {
	list-style: none;
	display: inline-block;
}

.followWizard li {
	margin-right: 8px;
	background-color: #eee;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	padding: 4px;
}
!Code
***/
//{{{
(function($) {

var tweb = config.extensions.tiddlyweb;
var tiddlyspace = config.extensions.tiddlyspace;
var currentSpace = tiddlyspace.currentSpace.name;

var shadows = config.shadowTiddlers;
shadows.FollowersTemplate = "<<view server.bag SiteIcon width:24 height:24 spaceLink:yes label:no>> <<view server.bag spaceLink>>";
shadows.FollowingTemplate = "<<view title SiteIcon width:24 height:24 spaceLink:yes label:no>> <<view title spaceLink>> <<view title deleteButton>>";

var name = "StyleSheetFollowingWizard";
shadows[name] = "/*{{{*/\n%0\n/*}}}*/".
	format(store.getTiddlerText(tiddler.title + "##StyleSheet"));
store.addNotification(name, refreshStyles);

var wizard = config.macros.followWizard = {
	locale: {
		mission: "Which user or space would you like to follow?",
		badpermissions: "Only members of the space can maintain followers.",
		follow: "follow"
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var locale = wizard.locale;
		var container = $("<div />").addClass("followWizard").appendTo(place)[0];
		if(!readOnly) {
			var form = $("<form />").addClass("followForm").appendTo(container)[0];
			$("<span />").text(locale.mission).appendTo(form);
			var input = $("<input />").attr("name", "space").attr("type", "text").appendTo(form);
			$("<input />").attr("type", "submit").val(locale.follow).appendTo(form).click(function(ev) {
				wizard.addFollowing(ev, input.val());
				ev.preventDefault();
			});
		} else {
			$(container).addClass("annotation").text(locale.badpermissions);
		}
	},
	addFollowing: function(ev, space) {
		var name = tiddlyspace.resolveSpaceName(space);
		if(!name) {
			alert("That doesn't appear to be a valid space name. Please check and try again.");
			return;
		}
		var title = "@" + name;
		var tiddler = store.getTiddler(title);
		if(tiddler) {
			tiddler.tags.push("follow");
		} else {
			tiddler = new Tiddler(title);
			tiddler.tags.push("follow");
			merge(tiddler.fields, config.defaultCustomFields);
		}
		store.saveTiddler(tiddler);
		autoSaveChanges();
	}
};

config.macros.view.views.deleteButton = function(value,place,params,wikifier,paramString,tiddler) {
	var tid = store.getTiddler(value)
	if(tid && config.commands.deleteTiddler.isEnabled(tid)) {
		var handler = function(ev) {
			config.commands.deleteTiddler.handler(ev,ev.target,value);
		};
		createTiddlyButton(place, "X", "delete this tiddler", handler);
	}
};

})(jQuery);
//}}}
!Followers
<<followers>>
!Activity
[[Replies and Notifications]]

<<activity>>
!Following
All spaces tagged follow
<<list filter [tag[follow]][sort[title]]>>

<<followSuggestions>>
/***
!Description
Updates the html serialization in TiddlySpace to provide routes to the takenote tool
***/
$(document).ready(function() {
	var place = $("#container").length > 0 ? $("#container")[0] : document.body;
	var space = window.location.host.split(".")[0]
	var bag = $(".bag").first().text() || space + "_public";
	var title = $("#title").text();
	// add edit link to notabene
	$.ajax({ url: "/spaces/" + space + "/members",
		success: function(r) {
			var isTiddler = $(".tiddler").length > 0;
			if(r) {
				if(bag == space + "_public") {
					if(isTiddler) {
						$("<a id='editLink' />").attr("href", "/takenote#!/quickedit/tiddler/" + title).
							text("edit note").prependTo(place);
					} else { // when viewing a collection add link to create new note in collection
						$("<a id='editLink' />").attr("href", "/takenote").
							text("take note").prependTo(place);
					}
				} else if(bag == space + "_private") {
					if(isTiddler) {
						$("<a id='editLink' />").attr("href", "/takenote#!/quickedit/bags/" + bag + "/tiddler/" + title).
							text("edit note").prependTo(place);
					}
				}
				if($("#backstage").length === 0) {
					$(['<ul id="backstage">',
						'<li><a href="/dashboard">dashboard</a></li><li><a href="/takenote">takenote</a></li>',
						'</ul>'].join("")).prependTo(document.body);
				}
			}
		}
	});
});
Male:M
Female:F
The activity feed is best for sharing opinions on something. To make best use of it create a tiddler and tag it with a username you would like to share thought with on this subject.

For instance I might create a tiddler called [[Animal I'd least like to be stuck in a cage with]]. I might say 
<<<
I would least like to be stuck in a cage with a lion as it could tear me apart amongst other reasons.
<<<
I then tag it @matias to get @matias's attention to see what he think. This flags it in @matias's activity feed and tells him that I am interested in his thoughts. Of course @matias can ignore it, and if he is not using the activity feed feature he may not even know about the message. If he wants to respond all @matias then has to do is create his own tiddler [[Animal I'd least like to be stuck in a cage with]]. Matias might say
<<<
A lion would be not as bad as a great white shark... not only would you be stuck in a cage with it but you would  be underwater with a likelihood of drowning to increase suffering.
<<<
It's not over yet.. now I can refine my original post with the thoughts of Matias. I might think mm, @matias has got a point there with the water, but I think a crocodile would more likely eat me then a great white shark and I fancy my chances with the great white.

I then update my tiddler to say 
<<<
I would least like to be stuck in a cage with a crocodile as it could tear me apart amongst other reasons. A lion would also be scary however I'm not a good swimmer so would be less likely to be able to make an escape. A crocodile is worse than a shark as shark attacks on humans are rare, so I'd fancy my chances.
<<<

We continue replying this way revising our tiddlers till the process finishes and I have a tiddler which clearly explains the [[Animal I'd least like to be stuck in a cage with]] with very detailed reasoning.
/***
|''Name:''|AETPlugin|
|''Description:''|Provides stuff the standard edit macro doesn't. First things first.. dropdowns!|
|''Author:''|JonRobson |
|''Version:''|0.9.1dev|
|''Date:''|Jan 2011|
|''Source''|https://github.com/jdlrobson/TiddlyWiki/raw/master/plugins/AET/plugins/AETPlugin.js|
|''Comments:''|Please make comments at http://groups.google.co.uk/group/TiddlyWikiDev |
|''License:''|[[BSD License|http://www.opensource.org/licenses/bsd-license.php]] |
!Usage
{{{<<aet type:dropdown field:foo values:{{tiddler title}}>>}}}
!Parameters
autosavechanges - updates fields as they change (For use in ViewTemplates)
***/
//{{{
(function($){
try{
		config.locationData = [];
		config.geoData = {};
	config.shadowTiddlers.AdvancedEditTemplateStyle = "/*{{{*/\n" +
	".clearboth {clear:both;}\n"+
	".aet_radioboxes label {width:auto;float:left;}\n"+
	".aet_radioboxes input {width:auto;float:left;}\n"+
	".tip {font-style:italic;font-weight:bold;}\n"+
	".dp-popup {position:absolute;background-color:white;} a.dp-choose-date {float: left; width: 16px; height: 16px; padding: 0; margin: 5px 3px 0; display: block; text-indent: -2000px; overflow: hidden; background: url(calendar.png) no-repeat; }a.dp-choose-date.dp-disabled { background-position: 0 -20px;	cursor: default;}input.dp-applied { width: 140px; float: left;}\n"+
	".filebrowser{background-color:white; border:solid 1px black;}\n"+
	"a.dp-choose-date {border:solid 1px black;}\n"+
	".dp-nav-prev {float:left;}\n"+
	".dp-nav-next {float:right;}\n"+
	".dp-calendar {clear:both;}\n"+
	".dp-popup {padding:10px;border:solid 1px black;z-index:4;}\n"+
	".jCalendar .selected {background-color:gray;}\n"+
	"/*}}}*/"
store.addNotification("AdvancedEditTemplateStyle", refreshStyles);
} catch(e) {
};

String.prototype.toJSON = function(){
	var namedprms = this.parseParams(null, null, true);
	var options = {};
	for(var i=0; i < namedprms.length;i++){
		var nameval = namedprms[i];
		if(nameval.name) {
			options[nameval.name] = nameval.value;
		}
	}
	return options;
};

var aet = config.macros.AdvancedEditTemplate = {
	lingo:{
		"aet_upload":"Upload a local file:",
		"aet_imgpreview":"a preview of currently selected image will be shown here",
		"aet_select":"Please select.."
	},
	translate: function(id){
		if(!aet.lingo[id]) {
			return id;
		} else {
			return aet.lingo[id];
		}
	},
	extensions: {
		"if":{
			_doStatement: function(stmt, tiddler, or){
				var delimiter = "&";
				if(or) {
					delimiter = "|";
				}
				var params = stmt.split(delimiter);
				var finalEval = true;
				if(or) finalEval = false;
				for(var i=0; i < params.length; i++){
					var evaluatesTo = true;
					var arg = params[i];
					if(arg.indexOf("!") == 0){
							var x = tiddler.fields[arg.substr(1)];
							if(x) {
								evaluatesTo = false;
							} else {
								evaluatesTo = true;
							}
					} else{
						var x = tiddler.fields[arg];
						if(!x){
								evaluatesTo = false;
						}
					}
					if(or) {
						finalEval = evaluatesTo || finalEval;
					} else{
						finalEval = evaluatesTo && finalEval;
					}
				}
				return finalEval;
			},
			doIfStatement: function(place, stmt, tiddler){
				var or = false;
				if(stmt.indexOf("|") > -1) {
					or = true;
				}
				var finalEval = this._doStatement(stmt, tiddler, or);
				if(!finalEval) {
					$(place).empty();
				}
				return finalEval;
			}
		}
	},
	controlTypes: {},
	handler: function(place, macroName, p, wikifier, paramString, tiddler) {
		var options = paramString.toJSON();
		if(options["if"]){
			aet.extensions["if"].doIfStatement(place,options["if"],tiddler);
		}
		var controlType = options.type;
		var field = options.field || options.metaDataName;
		options.field = field;
		var controlHandler = aet.controlTypes[controlType];
		if(controlHandler) {
			var container = $("<span class='editField' />").appendTo(place)[0];
			controlHandler(container,tiddler,field,options);
		}
	},
	getMetaData: function(title, extField){
		extField = extField.toLowerCase();
		var tiddler = store.getTiddler(title);
		var edit = $("[edit=%0]".format(extField), story.getTiddler(title));
		if(edit.length > 0) {
			var val = edit.val();
			return val ? val : false;
		} else if(!tiddler) {
			return false;
		} else {
			if(!tiddler.fields[extField]){
				return false;
			}
			else{
				return tiddler.fields[extField];
			}
		}
	},
	setMetaData: function(title, extField, extFieldVal, autosavechanges){
		if(autosavechanges) {
			var t = store.getTiddler(title);
			if(!t) {
				t = new Tiddler(title);
				if(config.shadowTiddlers[title]) {
					t.text = config.shadowTiddlers[title];
				}
				merge(t.fields, config.defaultCustomFields);
			}
			t.fields[extField] = extFieldVal;
			t = store.saveTiddler(t);
			if(aet.savetimeout) {
				window.clearTimeout(aet.savetimeout);
			}
			aet.savetimeout = window.setTimeout(function() {
					autoSaveChanges(null, [t]);
				}, 1000);
		} else {
			extField = extField.toLowerCase();
			var tidEl = story.getTiddler(title);
			var edit = $("[edit=%0]".format(extField), tidEl);
			if(edit.length === 0) {
				edit = $("<input />").attr("type", "hidden").attr("edit", extField).appendTo(tidEl);
			}
			extFieldVal = extFieldVal ? extFieldVal : "";
			edit.val(extFieldVal);
		}
	},
	getVariableFromQueryString:function(varName){
		var qs = window.location.search.substring(1);
		var atts = qs.split("&");
		for(var i =0; i <atts.length; i++){
			var varVal = atts[i].split("=");
			if(varVal[0]==varName){
				return decodeURI(varVal[1]);
			}
		}
		return false;
	}
};

config.macros.aet = aet;
if(config.macros.view){
	if(!config.macros.view.views) {
		config.macros.view.views = {};
	}
	config.macros.view.views.linklist = function(value,place,params,wikifier,paramString,tiddler) {
		var classname = "";
		var values = value.split("\n");
		for(var i = 0; i < values.length; i++){
				wikify("[[%0]]\n".format([values[i]]), place);
		}
	};
	config.macros.view.views.hiddeninput = function(value,place,params,wikifier,paramString,tiddler) {
		var classname="";
		if(params[2]) {
			classname = params[2];
		}
		$(place).append("<input type='hidden' value='"+value+"'/>");
	};
}
})(jQuery);
//}}}
(function($){$.jQTouch=function(_2){$.support.WebKitCSSMatrix=(typeof WebKitCSSMatrix=="object");$.support.touch=(typeof Touch=="object");$.support.WebKitAnimationEvent=(typeof WebKitTransitionEvent=="object");var _3,$head=$("head"),hist=[],newPageCount=0,jQTSettings={},hashCheck,currentPage,orientation,isMobileWebKit=RegExp(" Mobile/").test(navigator.userAgent),tapReady=true,lastAnimationTime=0,touchSelectors=[],publicObj={},extensions=$.jQTouch.prototype.extensions,defaultAnimations=["slide","flip","slideup","swap","cube","pop","dissolve","fade","back"],animations=[],hairextensions="";init(_2);function init(_4){var _5={addGlossToIcon:true,backSelector:".back, .cancel, .goback",cacheGetRequests:true,cubeSelector:".cube",dissolveSelector:".dissolve",fadeSelector:".fade",fixedViewport:true,flipSelector:".flip",formSelector:"form",fullScreen:true,fullScreenClass:"fullscreen",icon:null,touchSelector:"a, .touch",popSelector:".pop",preloadImages:false,slideSelector:"body > * > ul li a",slideupSelector:".slideup",startupScreen:null,statusBar:"default",submitSelector:".submit",swapSelector:".swap",useAnimations:true,useFastTouch:true};jQTSettings=$.extend({},_5,_4);if(jQTSettings.preloadImages){for(var i=jQTSettings.preloadImages.length-1;i>=0;i--){(new Image()).src=jQTSettings.preloadImages[i];}}if(jQTSettings.icon){var _7=(jQTSettings.addGlossToIcon)?"":"-precomposed";hairextensions+="<link rel=\"apple-touch-icon"+_7+"\" href=\""+jQTSettings.icon+"\" />";}if(jQTSettings.startupScreen){hairextensions+="<link rel=\"apple-touch-startup-image\" href=\""+jQTSettings.startupScreen+"\" />";}if(jQTSettings.fixedViewport){hairextensions+="<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;\"/>";}if(jQTSettings.fullScreen){hairextensions+="<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />";if(jQTSettings.statusBar){hairextensions+="<meta name=\"apple-mobile-web-app-status-bar-style\" content=\""+jQTSettings.statusBar+"\" />";}}if(hairextensions){$head.append(hairextensions);}$(document).ready(function(){for(var i in extensions){var fn=extensions[i];if($.isFunction(fn)){$.extend(publicObj,fn(publicObj));}}for(var i in defaultAnimations){var _a=defaultAnimations[i];var _b=jQTSettings[_a+"Selector"];if(typeof (_b)=="string"){addAnimation({name:_a,selector:_b});}}touchSelectors.push("input");touchSelectors.push(jQTSettings.touchSelector);touchSelectors.push(jQTSettings.backSelector);touchSelectors.push(jQTSettings.submitSelector);$(touchSelectors.join(", ")).css("-webkit-touch-callout","none");$(jQTSettings.backSelector).tap(liveTap);$(jQTSettings.submitSelector).tap(submitParentForm);_3=$("body");if(jQTSettings.fullScreenClass&&window.navigator.standalone==true){_3.addClass(jQTSettings.fullScreenClass+" "+jQTSettings.statusBar);}_3.bind("touchstart",handleTouch).bind("orientationchange",updateOrientation).trigger("orientationchange").submit(submitForm);if(jQTSettings.useFastTouch&&$.support.touch){_3.click(function(e){var _d=$(e.target);if(_d.attr("target")=="_blank"||_d.attr("rel")=="external"||_d.is("input[type=\"checkbox\"]")){return true;}else{return false;}});_3.mousedown(function(e){var _f=(new Date()).getTime()-lastAnimationTime;if(_f<200){return false;}});}if($("body > .current").length==0){currentPage=$("body > *:first");}else{currentPage=$("body > .current:first");$("body > .current").removeClass("current");}$(currentPage).addClass("current");location.hash=$(currentPage).attr("id");addPageToHistory(currentPage);scrollTo(0,0);dumbLoopStart();});}function goBack(to){if(hist.length>1){var _11=Math.min(parseInt(to||1,10),hist.length-1);if(isNaN(_11)&&typeof (to)==="string"&&to!="#"){for(var i=1,length=hist.length;i<length;i++){if("#"+hist[i].id===to){_11=i;break;}}}if(isNaN(_11)||_11<1){_11=1;}var _13=hist[0].animation;var _14=hist[0].page;hist.splice(0,_11);var _15=hist[0].page;animatePages(_14,_15,_13,true);return publicObj;}else{console.error("No pages in history.");return false;}}function goTo(_16,_17){var _18=hist[0].page;if(typeof (_16)==="string"){_16=$(_16);}if(typeof (_17)==="string"){for(var i=animations.length-1;i>=0;i--){if(animations[i].name===_17){_17=animations[i];break;}}}if(animatePages(_18,_16,_17)){addPageToHistory(_16,_17);return publicObj;}else{console.error("Could not animate pages.");return false;}}function getOrientation(){return orientation;}function liveTap(e){var $el=$(e.target);if($el.attr("nodeName")!=="A"){$el=$el.parent("a");}var _1c=$el.attr("target"),hash=$el.attr("hash"),animation=null;if(tapReady==false||!$el.length){console.warn("Not able to tap element.");return false;}if($el.attr("target")=="_blank"||$el.attr("rel")=="external"){return true;}for(var i=animations.length-1;i>=0;i--){if($el.is(animations[i].selector)){animation=animations[i];break;}}if(_1c=="_webapp"){window.location=$el.attr("href");}else{if($el.is(jQTSettings.backSelector)){goBack(hash);}else{if(hash&&hash!="#"){$el.addClass("active");goTo($(hash).data("referrer",$el),animation);}else{$el.addClass("loading active");showPageByHref($el.attr("href"),{animation:animation,callback:function(){$el.removeClass("loading");setTimeout($.fn.unselect,250,$el);},$referrer:$el});}}}return false;}function addPageToHistory(_1e,_1f){var _20=_1e.attr("id");hist.unshift({page:_1e,animation:_1f,id:_20});}function animatePages(_21,_22,_23,_24){if(_22.length===0){$.fn.unselect();console.error("Target element is missing.");return false;}$(":focus").blur();scrollTo(0,0);var _25=function(_26){if(_23){_22.removeClass("in reverse "+_23.name);_21.removeClass("current out reverse "+_23.name);}else{_21.removeClass("current");}_22.trigger("pageAnimationEnd",{direction:"in"});_21.trigger("pageAnimationEnd",{direction:"out"});clearInterval(dumbLoop);currentPage=_22;location.hash=currentPage.attr("id");dumbLoopStart();var _27=_22.data("referrer");if(_27){_27.unselect();}lastAnimationTime=(new Date()).getTime();tapReady=true;};_21.trigger("pageAnimationStart",{direction:"out"});_22.trigger("pageAnimationStart",{direction:"in"});if($.support.WebKitAnimationEvent&&_23&&jQTSettings.useAnimations){_22.one("webkitAnimationEnd",_25);tapReady=false;_22.addClass(_23.name+" in current "+(_24?" reverse":""));_21.addClass(_23.name+" out"+(_24?" reverse":""));}else{_22.addClass("current");_25();}return true;}function dumbLoopStart(){dumbLoop=setInterval(function(){var _28=currentPage.attr("id");if(location.hash==""){location.hash="#"+_28;}else{if(location.hash!="#"+_28){try{goBack(location.hash);}catch(e){console.error("Unknown hash change.");}}}},100);}function insertPages(_29,_2a){var _2b=null;$(_29).each(function(_2c,_2d){var _2e=$(this);if(!_2e.attr("id")){_2e.attr("id","page-"+(++newPageCount));}_2e.appendTo(_3);if(_2e.hasClass("current")||!_2b){_2b=_2e;}});if(_2b!==null){goTo(_2b,_2a);return _2b;}else{return false;}}function showPageByHref(_2f,_30){var _31={data:null,method:"GET",animation:null,callback:null,$referrer:null};var _32=$.extend({},_31,_30);if(_2f!="#"){$.ajax({url:_2f,data:_32.data,type:_32.method,success:function(_33,_34){var _35=insertPages(_33,_32.animation);if(_35){if(_32.method=="GET"&&jQTSettings.cacheGetRequests&&_32.$referrer){_32.$referrer.attr("href","#"+_35.attr("id"));}if(_32.callback){_32.callback(true);}}},error:function(_36){if(_32.$referrer){_32.$referrer.unselect();}if(_32.callback){_32.callback(false);}}});}else{if($referrer){$referrer.unselect();}}}function submitForm(e,_38){var _39=(typeof (e)==="string")?$(e):$(e.target);if(_39.length&&_39.is(jQTSettings.formSelector)&&_39.attr("action")){showPageByHref(_39.attr("action"),{data:_39.serialize(),method:_39.attr("method")||"POST",animation:animations[0]||null,callback:_38});return false;}return true;}function submitParentForm(e){var _3b=$(this).closest("form");if(_3b.length){evt=jQuery.Event("submit");evt.preventDefault();_3b.trigger(evt);return false;}return true;}function addAnimation(_3c){if(typeof (_3c.selector)=="string"&&typeof (_3c.name)=="string"){animations.push(_3c);$(_3c.selector).tap(liveTap);touchSelectors.push(_3c.selector);}}function updateOrientation(){orientation=window.innerWidth<window.innerHeight?"profile":"landscape";_3.removeClass("profile landscape").addClass(orientation).trigger("turn",{orientation:orientation});}function handleTouch(e){var $el=$(e.target);if(!$(e.target).is(touchSelectors.join(", "))){var _3f=$(e.target).closest("a");if(_3f.length){$el=_3f;}else{return;}}if(event){var _40=null,startX=event.changedTouches[0].clientX,startY=event.changedTouches[0].clientY,startTime=(new Date).getTime(),deltaX=0,deltaY=0,deltaT=0;$el.bind("touchmove",touchmove).bind("touchend",touchend);_40=setTimeout(function(){$el.makeActive();},100);}function touchmove(e){updateChanges();var _42=Math.abs(deltaX);var _43=Math.abs(deltaY);if(_42>_43&&(_42>35)&&deltaT<1000){$el.trigger("swipe",{direction:(deltaX<0)?"left":"right"}).unbind("touchmove touchend");}else{if(_43>1){$el.removeClass("active");}}clearTimeout(_40);}function touchend(){updateChanges();if(deltaY===0&&deltaX===0){$el.makeActive();$el.trigger("tap");}else{$el.removeClass("active");}$el.unbind("touchmove touchend");clearTimeout(_40);}function updateChanges(){var _44=event.changedTouches[0]||null;deltaX=_44.pageX-startX;deltaY=_44.pageY-startY;deltaT=(new Date).getTime()-startTime;}}$.fn.unselect=function(obj){if(obj){obj.removeClass("active");}else{$(".active").removeClass("active");}};$.fn.makeActive=function(){return $(this).addClass("active");};$.fn.swipe=function(fn){if($.isFunction(fn)){return this.each(function(i,el){$(el).bind("swipe",fn);});}};$.fn.tap=function(fn){if($.isFunction(fn)){var _4a=(jQTSettings.useFastTouch&&$.support.touch)?"tap":"click";return $(this).live(_4a,fn);}else{$(this).trigger("tap");}};publicObj={getOrientation:getOrientation,goBack:goBack,goTo:goTo,addAnimation:addAnimation,submitForm:submitForm};return publicObj;};$.jQTouch.prototype.extensions=[];$.jQTouch.addExtension=function(_4b){$.jQTouch.prototype.extensions.push(_4b);};})(jQuery);
CACHE MANIFEST
# version 0.6.4

CACHE:
/takenote
/dashboard
/bags/common/tiddlers/jquery-ui.custom.css
/bags/common/tiddlers/jquery-ui.custom.js
/notabene.css
/notabene.js
/bags/common/tiddlers/jquery-json.js
/bags/common/tiddlers/jquery.js
/bags/tiddlyspace/tiddlers/chrjs
/bags/common/tiddlers/chrjs-store.js
/touchicon_takenote.png
/bags/common/tiddlers/cancelTiddler.png
/bags/common/tiddlers/saveTiddler.png
/bags/common/tiddlers/deleteTiddler.png
/bags/common/tiddlers/HtmlBackground
/bags/common/tiddlers/icon-search.png
/bags/common/tiddlers/icon-incomplete.png
/bags/common/tiddlers/icon-recent.png
/bags/common/tiddlers/bookmark_bubble.js
NETWORK:
*
/*{{{*/
/* Version 0.8.5 */
#contentWrapper.highlight {
background: none;
opacity: 0.5;
}
#popup a {
display: inline;
}
#popup ul {
list-style: none;
margin-left: 0px;
padding-left: 0px;
}
#popup li {
clear: both;
}
.viewer .wikifiedImage img {
max-width: 450px;
height: auto;
}
.loggedInUser.readOnly #sidebar .tools .button {
margin-left: 0px;
margin-right: 16px;
}
.loggedInUser.readOnly #sidebar .tools .pushLeft.button {
margin-right: 0px;
}

@media all and (max-width: 960px) {
	#header { width: 300px; }
	#sidebar { display: none; }
	.tiddler .modifierIcon img,
	.tiddler .modifierIcon svg,
	.tiddler .spaceSiteIcon .originButton img,
	.originButton svg {
		width: 32px;
		height: 32px;
		margin-left: 15px;
		margin-right: 0px;
	}
}
#backstageArea .button:active {
color: white;
background: #DB4;
border: 1px solid #841;
}
#backstageArea .button:hover {
color: #014;
background: #FE8;
border-color: #DB4;
}
#contentWrapper {
margin-left: 166px;
margin-right: 166px;
width: 845px;
}
#searchResults {
margin: auto;
background: white;
margin-bottom: 20px;
padding: 8px;
border-radius: 8px;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
}

body.readOnly,
body {
background-image: url(/BackgroundImage);
background-color: [[ColorPalette::PrimaryMid]] !important; 
}
#contentWrapper {
width: 845px;
font-size: 0.8em;
}
#header {
margin-left: 12px;
color: white;
width: 845px;
margin-top: 30px;
margin-bottom: 30px;
letter-spacing: -1px;
font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
font-size: 50px;
font-weight: bold;
height: 58px;
text-shadow: rgba(0, 0, 0, 0.496094) 1px 3px 5px;
}

/* content */
#content {
width: 520px;
float: left;
}
#content .tiddler {
border-top: none;
/*box-shadow: 1px 10px 10px [[ColorPalette::PrimaryLight]];*/
}
.tiddler .subtitle {
font-style: normal;
}
.tiddler .titleBar {
margin-left: 68px;
}
a.externalLink {
background: transparent url(/externalLink.png) no-repeat scroll 100% 45%;
padding-right: 1em !important;
}

.tiddler div.toolbar {
right: -6px;
}
#content  .tiddler .heading {
left: -55px;
}
.tiddler.missing .spaceSiteIcon {
display: none;
}
.readOnly .tiddler .spaceSiteIcon,
.tiddler .spaceSiteIcon {
visibility: hidden;
}
.tiddler.selected .spaceSiteIcon {
visibility: visible;
}
.readOnly .tiddler.selected .spaceSiteIcon {
visibility: hidden;
}
#content .tiddler .spaceSiteIcon {
margin-right: 10px;
padding: 5px;
border-radius: 10px 0px 0px 10px;
o-border-radius: 10px 0px 0px 10px;
moz-border-radius: 10px 0px 0px 10px;
webkit-border-radius: 10px 0px 0px 10px;
}
#content  .tiddler .editorHeading {
left: 0px;
}
#content .tiddler .modifierIcon {
right: -18px
}
#content  .tiddler .heading,
#content .tiddler .content {
width: 490px;
}
.tiddler .viewer {
margin: 0px 0px 0px 10px;
}
#displayArea, #tiddlerDisplay {
margin:auto;
width: 500px;
}
.tagInfo {
border-left: none;
border-right: none;
margin-left: 0px;
}
/* side bar */
.anonymousUser #sidebar .tools .button.followMenuButton {
display: none;
}
#sidebar {
width: 250px;
float: right;
position: relative;
right: auto;
/*font-family: 'Lucida Sans', 'Lucida Grande', 'Lucida Sans Unicode', sans-serif;*/
}
.tabContents .timeline {
background: none;
}
#sidebar .avatar {
-webkit-box-shadow: #CCC 1px 4px 4px;
background-color: white;
left: -5px;
padding: 8px;
position: relative;
top: -24px;
width: 128px;
}
#sidebar .avatar .image {
display: block;
background-color: whiteSmoke;
}
.twSearch .searchButton {
display: none;
}
.twSearch .searchField {
width: 210px;
}
#sidebar .tools .button {
width: 91px;
height: 32px;
display: inline-block;
text-align: center;
vertical-align: middle;
margin-top: 6px;
line-height: 32px;
font-size: 12px;
color: white;
background-color: #408DAC !important;
font-weight: bold;
border: none;
border-radius: 5px;
margin-right: 0px;
margin-left: 16px;
margin-bottom: 6px;
}
#sidebar .tools .pushLeft.button,
#sidebar .tools .pushLeft .button{
margin-left: 0px;
}
.readOnly #sidebar .tools .button{
margin-left: 0px;
margin-right: 16px;
}
#sidebar .tools .button a {
color: white;
}
#sidebar .tools .button:hover {
opacity:0.8;
}
#sidebarCaspian {
padding-left: 20px;
padding-right: 20px;
width: 210px;
background-color: white;
border-radius: 10px;
-webkit-border-radius: 10px;
position: relative;
}
.twSearch input {
float: left;
}

/*}}}*/
/***
|''Name:''|TiddlySpaceIntraSpaceInclusion|
|''Description:''|Provides support for {{{<<tiddler Foo@bar>>}}} and {{{<<tiddler [[Foo]]@bar>>}}}|
|''Author:''|Jon Robson|
|''Source:''|https://github.com/jdlrobson/TiddlyWikiPlugins/raw/master/plugins/TiddlySpaceIntraSpaceInclusion/TiddlySpaceIntraSpaceInclusion.js|
|''Version:''|0.3.8a|
|''License:''|[[BSD License|http://www.opensource.org/licenses/bsd-license.php]] |
|''Comments:''|Please make comments at http://groups.google.co.uk/group/TiddlyWikiDev |
|''~CoreVersion:''|2.4|
***/
//{{{
(function() {
	var _tidtext = TiddlyWiki.prototype.getTiddlerText;
	var cache = {};

	// allmost the same regExp as in TiddlySpaceLinkPlugin but .. no "mg" parameter, because it didn't work for this usecase.
	config.textPrimitives.spacenameLinkRegExp = new RegExp(config.textPrimitives.unWikiLink + 
													 "?(" + config.textPrimitives.bareTiddlerLetter + "*)@(" + config.textPrimitives.spaceName + ")", "");
	config.textPrimitives.tiddlyLinkSpacenameLinkRegExp = new RegExp("\\[\\[(.*?)(?:\\|(.*?))?\\]\\]@(" + config.textPrimitives.spaceName + ")", "");
	
	TiddlyWiki.prototype.getTiddlerText = function(title, defaultText) {
		var ct = config.textPrimitives;
		var match = ct.spacenameLinkRegExp.exec(title);	// foo@bar
		var match2 = ct.tiddlyLinkSpacenameLinkRegExp.exec(title); 	// [[foo]]@bar
		
		if(match || match2) {
		//	console.log('inner: ', 'spacename: ', match, 'tiddlyLink: ', match2, 'place: ');
			var tidtitle, space;
			if(match[1] && match.length === 3) {
				tidtitle = match[1];
				space = match[2];
			} else if(match2 && match2.length === 4) {
				tidtitle = match2[1];
				space = match2[3];
			}
			var newtitle = tidtitle + "@" + space;
			if(tidtitle && space) {
				title = newtitle;
			}
			if(tidtitle && space && !store.getTiddler(newtitle)) {
				var tiddler = new Tiddler(title);
				// get the tiddler, where the macro is rendered. //XXX will need more testing
				var el = story.findContainingTiddler(place);
				var refreshTitle = (el) ? el.getAttribute('tiddler') : null;

				tiddler.text = "//retrieving from server//";
				tiddler.fields.doNotSave = "true";
				tiddler.tags = ["excludeLists", "excludeSearch", "excludeMissing"];
				merge(tiddler.fields, config.defaultCustomFields);
				tiddler.fields["server.bag"] = space + "_public";
				tiddler = store.addTiddler(tiddler);
				ajaxReq({ url: "/bags/" + space + "_public/tiddlers/" + tidtitle,
					dataType: "json",
					success: function(tid) {
						var tiddler = store.getTiddler(title);
						tiddler.text = tid.text;
						store.addTiddler(tiddler);
						// store.notify(title,true);
						story.refreshTiddler(refreshTitle,null,true);
						// story.refreshAllTiddlers(); // hacky but above link doesn't always seem to work!
					},
					error: function() {
						var tiddler = store.getTiddler(title);
						tiddler.text = "//error retrieving tiddler {{{" + title + "}}} from space @" + space + "//";
						store.addTiddler(tiddler);
						// store.notify(title,true);
						story.refreshTiddler(refreshTitle,null,true);
						// story.refreshAllTiddlers(); // hacky but above link doesn't always seem to work!
					}
				});
			}
		}
		return _tidtext.apply(this, [title, defaultText]);
	}
})();
//}}}
noscript {
	border: 5px solid red;
	display: block;
	margin: auto;
	padding: 50px;
	text-align: center;
	width: 300px;
}

.syncButton {
	font-size: 2em;
	border: solid 1px #CCC;
	padding: 5px;
	-moz-border-radius: 5px 5px 5px;
	-webkit-border-radius: 5px 5px 5px;
	width: 48px;
	height: 48px;
	background-image: url(/bags/common/tiddlers/icon-sync.png);
	background-repeat: no-repeat;
	background-position: center;
	text-indent: -999px;
	overflow: hidden;
	display: block;
	text-align: center;
	cursor: pointer;
	right: 120px;
	top: 80px;
	position: absolute;
}

#note.active #deletenote {
	display: none;
}

body {
	font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";
	margin: 0;
	background-image: url(/bags/common/tiddlers/HtmlBackground);
}

#backstage {
	width: 100%;
	padding: 0px;
	background-color: black;
	margin: 0px 0px 0px 0px;
	height: 32px;
	text-align: center;
	background: -moz-linear-gradient(center bottom,#222 0%, #333 50%, #555 100%);
	background: -webkit-gradient(linear,left bottom,left top,color-stop(0, #222),color-stop(0.5, #333),color-stop(1, #555));
	background: -moz-linear-gradient(center bottom,#222 0%, #333 50%, #555 100%);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#F5555, endColorstr=#F2222);
	-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#F5555, endColorstr=#F2222)";
}

#backstage a {
	color: white;
	padding: 4px;
	display: block;
	text-decoration: none;
}

#backstage li:first-child {
	border-right: solid 1px #777;
}

#backstage li:nth-child(2) {
	border-left: solid 1px #555;
}

#backstage a:hover {
	background-color: #FFA500;
}

#backstage li {
	display: inline-block;
	line-height: 18px;
	margin-top: 2px;
	padding: 0px 10px;
}

#backstage .status {
	color: #CCC;
	float: right;
	font-size: 0.8em;
}

#backstage .status.nonmember {
	color: #666;
	opacity: 0.5;
}

h2,h3,h4,h5 {
	margin-bottom: 0px;
}

a {
	color: royalBlue;
}

a:hover {
	color:#4169C8;
}

.header {
	border-bottom: 7px solid rgba(26, 31, 30, 0.95);
	padding-bottom: 20px;
	position: relative;
}

.siteheading {
	position: relative;
}

.header h1 {
	color: #4C4A54;
	font-size: 4em;
	line-height: 48px;
	text-shadow: 0px 2px 2px white;
	padding-top: 10px;
	margin-top: 0px;
	padding-left: 72px;
}

.toolpanel .info,
.toolpanel input,
.toolpanel h2,
.toolpanel ul {
	margin-left: 120px;
}

.toolpanel h2 {
	text-shadow: 0px 1px 1px white;
}

.toolpanel .section {
	border-bottom: 1px solid #DCE7F1;
	border-top: 1px solid #F8F8F8;
	padding: 24px;
	position: relative;
}

.section.searchSection {
	background-image: url(/bags/common/tiddlers/icon-search.png);
	background-position: 80px 15px;
	background-repeat: no-repeat;
}

.section.recentSection {
	background-image: url(/bags/common/tiddlers/icon-recent.png);
	background-position: 80px 15px;
	background-repeat: no-repeat;
}

.section.incompleteSection {
	background-image: url(/bags/common/tiddlers/icon-incomplete.png);
	background-position: 80px 15px;
	background-repeat: no-repeat;
	min-height: 100px;
}

.toolpanel .section ul {
	list-style: none;
}

.siteicon {
	background-image: url(SiteIcon);
	height: 56px;
	width: 56px;
	background-repeat: no-repeat;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px;
	-o-border-radius: 10px;
	border-radius: 10px;
	background-size: 56px 56px;
	position: absolute;
	left: 6px;
	top: 8px;
}

.toolbar {
	position: absolute;
	top: -40px;
	width: 100%;
}


.takenotedashboard .footer {
	text-align: center;
	font-style: italic;
	font-size: 0.8em;
	color: gray;
	font-weight: bold;
	border-top: solid 1px #CCC;
}

.takenotedashboard .footer,
#note,
.messageArea {
	width: 500px;
}

.note_title {
	font-family: Georgia;
	line-height: 48px;
	color: #4C4A54;
	width: 468px; /* 500 - 32 padding */
}

.takenotecontainer {
	width: 540px;
	background: rgba(255,255,255, 0.7);
}

.takenotedashboard {
	width: 540px;
	background-color: #F0F4F8;
	padding-bottom: 40px;
}

.note_title_container {
	width: 556px;
	margin-left: -28px;
	-webkit-box-shadow: 0px 1px 1px rgb(96,106,115);
	position:relative;
	background-color: #DCE7F1;
}

@media all and (min-width: 480px) {
	.note_title_container:before {
		content: "";
		position: absolute;
		bottom: -8px;
		left: 0px;
		border-width: 0px 8px 8px 0px;
		border-style: solid;
		border-color: rgba(0,0,0,0) #3A4955 rgba(0,0,0,0) #3A4955;
		background: rgba(0,0,0,0);
		display: block;
		width: 0;
	}

	.note_title_container:after {
		content: "";
		position: absolute;
		bottom: -8px;
		right: 0px;
		border-width: 8px 8px 0px 0px;
		border-style: solid;
		border-color: #3A4955 rgba(0,0,0,0) rgba(0,0,0,0) #3A4955;
		background: rgba(0,0,0,0);
		display: block;
		width: 0;
	}
}

.note_title {
	background: none;
	width: 500px;
	margin-left: 10px;
}

.takenotedashboard,
.takenotecontainer {
	margin: auto;
	margin-top: 20px;
	position: relative;
	display: none;
}

.takenotedashboard,
.takenotecontainer.ready {
	display: block;
}

#note {
	position: relative;
}

.takenotedashboard .footer,
#note,
.messageArea {
	margin: 0 auto;
}

.messageArea {
	position: relative;
	margin-bottom: 20px;
	font-family: monospace;
	border: solid 1px #ccc;
	color: #333;
	padding: 10px 0px 20px 0px;
	text-indent: 4px;
	color: green;
	opacity: 0;
}

.messageArea.warning {
	color: #B38600;
}

.messageArea.error {
	color: red;
}

.messageArea.displayed {
	opacity: 1;
	-webkit-transition: opacity 0.4s ease-in;
}

.takenotecontainer h1 {
	font-size: 3em;
}

#notebody {
	position: relative;
	border: 1px solid gray;
	background: rgba(255,255,255, 0.7);
	margin-top: 18px;
	padding: 16px;
	box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5), -1px -1px 2px rgba(0, 0, 0, 0.5);
}

#newnote {
	height: 24px;
	width: 30px;
	position: absolute;
	top: 6px;
	right: 4px;
	padding: 5px;
	background-repeat: no-repeat;
	background-image: url(/bags/common/tiddlers/saveTiddler.png);
}

.notedate {
	float: right;
	color: rgba(0,0,0, 0.5);
	margin-left: 32px;
}

#notebody .note_text {
	color: #1A1F1E;
	background: transparent;
	width: 100%;
	border: none;
	outline: none;
	clear: both;
	font-family: Georgia;
	font-size: 1.3em;
	line-height: 1.3em;
}

#tips {
	padding: 8px;
	background-color: #DDD;
}

.imageTip img {
	width: 16px;
	height: 16px;
}

.boldTip, .underlineTip, .italicTip {
	margin-left: 2px;
	margin-right: 2px;
}

.boldTip {
	font-weight: bold;
}

.underlineTip {
	text-decoration: underline;
}

.italicTip {
	font-style: italic;
}

#metabutton {
	background: gray;
	width: 32px;
	height: 32px;
	background-repeat: no-repeat;
	background-position: center;
	opacity: 0.3;
	border-radius: 0 0 5px 5px;
	padding: 10px;
	position: absolute;
	bottom: -52px;
	left: 224px;
	-webkit-transition: height 0.2s ease-in-out, bottom 0.2s ease-in-out, opacity 0.2s ease-in-out;
	-moz-transition: height 0.2s ease-in-out, bottom 0.2s ease-in-out, opacity 0.2s ease-in-out;
	-o-transition: height 0.2s ease-in-out, bottom 0.2s ease-in-out, opacity 0.2s ease-in-out;
	-ms-transition: height 0.2s ease-in-out, bottom 0.2s ease-in-out, opacity 0.2s ease-in-out;
	transition: height 0.2s ease-in-out, bottom 0.2s ease-in-out, opacity 0.2s ease-in-out;
}

#metabutton:hover {
	opacity: 0.7;
	height: 35px;
	bottom: -55px;
}

#newnote:hover,
#metabutton:hover {
	cursor: pointer;
}

#notemeta .paddedbox {
	padding: 10px;
}

#notemeta ul {
	list-style: none;
}

.removeTag {
	background-image: url(/bags/common/tiddlers/deleteTiddler.png);
	background-size: 12px 16px;
	background-repeat: no-repeat;
	text-indent: -999px;
	overflow: hidden;
	width: 12px;
	height: 16px;
	display: inline-block;
	margin-left: 8px;
	margin-right: 8px;
	cursor: pointer;
}

.note_title {
	border: none;
	font-size: 3em;
	outline: none;
	padding: 0px 16px;
	text-align: center;
	text-shadow: 0px 1px 1px white;
}

.note_title:focus {
	text-shadow: none;
}

#deletenote {
	position: absolute;
	top: 4px;
	left: 4px;
	background-image: url(/bags/common/tiddlers/deleteTiddler.png);
	background-repeat: no-repeat;
	height: 30px;
	width: 20px;
}

#cancelnote {
	position: absolute;
	top: 4px;
	visibility: hidden;
	right: 235px; /* 500 / 2 - 15px (half width of cancel button) */
	background-image: url(/bags/common/tiddlers/cancelTiddler.png);
	background-repeat: no-repeat;
	height: 30px;
	width: 30px;
}

.validatedNote #cancelnote {
	visibility: visible;
}

#cancelnote,
#deletenote,
#newnote {
	cursor: pointer;
	opacity: 0.3;
	overflow: hidden;
	text-indent: -9999px;
}

#cancelnote:hover,
#newnote:hover,
#deletenote:hover {
	opacity: 1;
}

#backstage a.connectionStatus:hover,
.connectionStatus {
	display: block;
	position: relative;
	-webkit-border-radius: 5px;
	background-color: red;
}

.online #backstage a.connectionStatus:hover,
.online .connectionStatus {
	display: block;
	background-color: green;
}

.connectionStatus:after {
	content: "offline";
	position: absolute;
	top: -6px;
	left: 15px;
	color: #ccc;
}
.online .connectionStatus:after {
	content: "online";
	position: absolute;
	top: -6px;
	left: 15px;
	color: #eee;
}

.requiresConnection {
	display: none;
}

.online .requiresConnection {
	display: block;
}


/* iphone mode */
@media screen and (orientation:portrait) and (max-width: 320px) {
	.note_title {
		padding: 0px;
	}

	#backstage {
		font-size: 0.8em;
	}

	.takenotedashboard,
	.takenotecontainer {
		width: 320px;
		font-size: 0.7em;
	}

	.header h1 {
		font-size: 2em;
	}

	.takenotedashboard .footer,
	#note,
	.messageArea {
		width: 300px;
	}

	#cancelnote {
		right: 145px; /* 320 / 2 - 15px (half width of cancel button) - 16px (padding on note_title) */
	}

	.note_title,
	.note_title_container {
		width: 300px;
		margin: auto;
	}
}

/* portrait mode */
@media screen and (orientation:portrait) and (min-width: 480px) {
	.note_title {
		padding: 0px;
	}

	.takenotedashboard,
	.takenotecontainer {
		width: 480px;
	}

	.takenotedashboard .footer,
	#note,
	.messageArea {
		width: 460px;
	}

	#cancelnote {
		right: 199px; /* 460 / 2 - 15px (half width of cancel button) - 16px (padding on note_title) */
	}

	.note_title,
	.note_title_container {
		width: 460px;
		margin: auto;
	}
}
/***
|''Name:''|FamilyTreeUtilsPlugin|
|''Description:''|Adds useful macros for the purpose of family tree related fun|
|''Version:''|0.3.12|
|''Date:''|July 2010|
|''Source:''|http://familytree.tiddlyspace.com|
|''Author:''|Jon Robson |
|''License:''|[[BSD open source license]]|
|''CoreVersion:''|2.3|
!Notes
Updates newTiddler macro
Updates saveTiddler to update other tiddlers when a spouse is added / a mother/father renamed
updates date view type to show years when the rest of the string is 0s
additional bracketedlist and year view type
listChildren, tiddlerGender, age and familytreelist macros
 macro
***/
//{{{
(function($) {
if(!config.macros.showInstall) {
config.macros.showInstall = {handler:function(){}};
}
merge(config.shadowTiddlers, { excludeTreeViewTemplate : "", systemConfigViewTemplate: "",
ListOfWomen: "", ListOfMen: "", ListOfPlaces: "", placeViewTemplate: "", sexDefinition: ""});

var _date = config.macros.view.views.date;
config.macros.view.views.date = function(value,place,params,wikifier,paramString,tiddler) {
	var isString = typeof(value) == "string";
	if(isString && value.substr(4, 4) == "0000") { // only year
		config.macros.view.views.year.apply(this, arguments);
	} else if(isString && value.substr(6, 4) == "0000") { // only month and year
		var year = value.substr(0, 4);
		var month = config.messages.dates.shortMonths[parseInt(value.substr(4, 2), 10) - 1];
		$("<span />").addClass("year").text("%0 %1".format([month, year])).appendTo(place);
	} else {
		_date.apply(this, arguments);
	}
};

config.macros.view.views.year = function(value,place,params,wikifier,paramString,tiddler) {
	var year = value.substr(0,4);
	$("<span />").addClass("year").text(year).appendTo(place);
};

config.macros.view.views.bracketedlist = function(value, place, params, wikifier, paramString, tiddler) {
	var links = value.readBracketedList();
	for(var i = 0; i < links.length; i++){
		config.macros.view.views.link(links[i], place, params, wikifier, paramString, tiddler);
		$("<span />").html("&nbsp;").appendTo(place);
	}
};


var _saveTiddler = TiddlyWiki.prototype.saveTiddler;
TiddlyWiki.prototype.saveTiddler = function(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created) {
	var tiddler, titleThis, newTitleThis;
	if(title instanceof Tiddler) {
		tiddler = $.extend(new Tiddler(title.title), title);
		titleThis = title.title;
		newTitleThis = newTitle;
	} else {
		tiddler = new Tiddler(newTitle);
		tiddler.fields = fields;
		tiddler.tags = tags;
		titleThis = title;
		newTitleThis = newTitle;
	}
	if(!newTitle) {
		newTitleThis = titleThis;
	}
	var changed = [];
	var changedTitle = newTitleThis != titleThis;
	var spousesToUpdate = [];
	if(tiddler.fields && tiddler.fields.spouses) {
		spousesToUpdate = tiddler.fields.spouses.readBracketedList();
	}
	if(changedTitle){
		var tiddlers = store.getTiddlers();
		for(var i = 0; i < tiddlers.length; i++) {
			var tid = tiddlers[i];
			var changedTiddler = false;
			if(spousesToUpdate.indexOf(tid.title) != -1) { // make sure the other tiddler knows they have a spouse
				var theirSpouses = tid.fields.spouses ? tid.fields.spouses.readBracketedList() : [];
				theirSpouses.pushUnique(newTitleThis);
				tid.fields.spouses = String.encodeTiddlyLinkList(spouseList);
				changedTiddler = true;
			}

			if(changedTitle) { // update other tiddlers in case of changed name
				if(tid.fields.mother == titleThis){
					tid.fields.mother = newTitleThis;
					changedTiddler = true;
				}
				if(tid.fields.father == titleThis){
					tid.fields.father = newTitleThis;
					changedTiddler = true;
				}
				if(tid.fields.spouse) {
					var spouseList = tid.fields.spouse.readBracketedList();
					var update = spouseList.indexOf(titleThis);
					if(update != -1) {
						spouseList[update] = newTitleThis;
						tid.fields.spouse = String.encodeTiddlyLinkList(spouseList);
						changedTiddler = true;
					}
				}
			}

			if(changedTiddler) {
				tid = _saveTiddler.apply(this, [tid]);
				changed.push(tid)
			}
		}
		autoSaveChanges(null, changed);
	}
	return _saveTiddler.apply(this, arguments);
};
config.macros.age ={
	handler: function(place, macroName, params, wikifier, paramString, tiddler){
		var d1 = tiddler.fields["dob"];
		var d2 = tiddler.fields["dod"] || new Date().formatString("YYYY0MM0DD000000");
		var y1 = parseInt(d1.substr(0,4));
		var y2 = parseInt(d2.substr(0,4));

		if(y1 == Number.NaN || y2 == Number.NaN || y1== 0 || y2 == 0) {
			return;
		}
		var m1 = parseInt(d1.substr(4,2));
		var m2 = parseInt(d2.substr(4,2));

		var day1 = parseInt(d1.substr(6,2));
		var day2 = parseInt(d2.substr(6,2));

		var ageY = y2 - y1;
		var ageM = m2 - m1;
		if(m2 > m1){
			ageM = m2 - m1;
		} else if(m2 < m1){
			ageM = 12 -(m1- m2);
			ageY -= 1;
		}

		if(ageY != Number.NaN) {
			var ageStr = ageY + " years";
			if(ageM != 0 && ageM != Number.NaN) {
				 ageStr += " and " + ageM + " months";
			}
		}
		$(place).text(ageStr);
	}
};

config.macros.familytreelist = {
	handler: function(place, macroName, params, wikifier, paramString, tiddler){
		var param = paramString.parseParams();
		var sex = getParam(param, "sex");
		var filter = getParam(param, "filter")
		var print = "";
		var tiddlers = !filter ? store.getTiddlers() : store.filterTiddlers(filter);
		var sort = getParam(param,"sort");
		tiddlers = sort ? store.sortTiddlers(tiddlers, sort) : tiddlers;

		for(var i=0; i < tiddlers.length;i++) {
			var tid = tiddlers[i];
			var good = false;
			if(!sex) {
				good = true;
			} else if(tid.fields.sex && tid.fields.sex == sex) {
				good = true;
			}
			if("excludeTree" in tiddler.tags) {
				good = false;
			}
			if(good) {
				print += tid.title+"\n";
			}
		}
		wikify(print, place);
	}
};

var listChildren = config.macros.listchildren = {
	locale: {
		noChildren: "No children"
	},
	handler: function(place, macroName, params, wikifier, paramString, tiddler){
		var parent = tiddler.title;
		var children = [];
		var t = store.getTiddlers();

		for(var i=0; i < t.length; i++){
			var person = t[i];
			if(person.fields.father == parent){
				children.push(person);
			}
			else if(person.fields.mother == parent){
				children.push(person);
			}
		}

		var param = paramString.parseParams();
		var sort = getParam(param, "sort");
		if(sort){
			children = store.sortTiddlers(children, sort);
		}

		if(children.length === 0){
			var div = $("<div />").text(listChildren.locale.noChildren).appendTo(place);
		} else{
			var ul = $("<ul />").appendTo(place);
			for(var i = 0; i < children.length; i++) {
				var child = children[i];
				var name = child.title;
				var dob = child.fields.dob;
				var dod = child.fields.dod;
				dob = dob ? dob.substr(0,4) : "";
				dod = dod ? dod.substr(0,4) : "";
				var lifespan = dob || dod ? " (%0-%1)".format([dob, dod]) : "";
				var child = $("<a />").addClass("child").text(name + lifespan).attr("title", name).click(function(ev){
					story.displayTiddler(ev.target,this.title);
				});
				var li = $("<li />").append(child).appendTo(ul);
			}
		}
	}
};
config.macros.tiddlerGender ={
	handler: function(place, macroName, params, wikifier, paramString, tiddler){
		place = $(place);
		var sex = tiddler.fields.sex;
		if(sex == 'M'){
			place.addClass("sexMale");
		}
		else if(sex == 'F'){
			place.addClass("sexFemale");
		}
	}
};

config.commands.addChild = {
	text: "Add Child",
	tooltip: "add a child",

	handler: function(event, src, title){
		var parent = store.getTiddler(title);
		var parentSex = parent.fields.sex;
		var spouses = parent.fields.spouse || "";
		var spouseList = spouses.readBracketedList();
		var parent2;
		for(var i = 0; i < spouseList.length && !parent2; i++) {
			var s = spouseList[i];
			var answer = confirm("was %0 the other parent?".format([s]));
			if(answer) {
				parent2 = s;
			}
		}
		parent2 = parent2 ? parent2 : "";
		var childName = prompt("What is the name of the child?");
		var custom = "";
		if(parentSex && childName){
			if(parentSex == "F") {
				custom = 'mother:"%0" father:"%1"'.format([title, parent2]);
			} else if(parentSex == "M") {
				custom = 'father:"%0" mother:"%1"'.format([title, parent2]);
			}
			story.displayTiddler(null, childName, DEFAULT_EDIT_TEMPLATE, null, null, custom);
		} else {
			alert("I can't do this without the child name and the sex of this person..");
		}
	}
};

merge(config.macros.newTiddler,{
	label: "new person",
	prompt: "Create a new person in your family tree",
	title: "New Person",
	accessKey: "N"});

config.macros.viewFieldTiddler = {
	handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		var field = params[0];
		var reference = tiddler[field] || tiddler.fields[field];
		tiddler = reference ? store.getTiddler(reference) : null;
		var newParams = params.slice(1, params.length);
		var newParamString = newParams.join(" ");
		config.macros.view.handler(place,macroName,newParams,wikifier,newParamString,tiddler);
	}
};
}(jQuery))
//}}}
<<activity show:reply show:notify>>

/***
|''Name''|TiddlySpaceFollowingSuggestions|
|''Version''|0.2.5dev|
|''Description''|Provides a following macro|
|''Author''|Jon Robson|
|''Requires''|TiddlySpaceFollowingPlugin|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
!Usage

!Code
***/
//{{{
(function($) {

var tweb = config.extensions.tiddlyweb;
var tiddlyspace = config.extensions.tiddlyspace;
var followMacro = config.macros.followTiddlers;

var followSuggestions = config.macros.followSuggestions = {
	cache: {},
	handler: function(place, macroName, params) {
		// to do - limit results
		place = $('<div class="suggestions" />').appendTo(place)[0];
		var currentSpace = tiddlyspace.currentSpace.name;
		var user = params[0] || currentSpace;
		var pleaseWait = $("<div class='loading' />").text("please wait..").appendTo(place);
		tweb.getUserInfo(function(activeUser) {
			if(activeUser.name != tiddlyspace.currentSpace.name) {
				pleaseWait.hide();
				return;
			}
			followMacro.getFollowers(function(users) {
				// suggestions are followers of people that you follow that you don't follow
				var bags = followMacro._getFollowerBags(users);
				var _bags = [];
				for(var i = 0; i < bags.length; i++) {
					_bags.push("bag:%0".format([bags[i]]));
				}
				var bagString = _bags.join(" OR ");
				ajaxReq({
					beforeSend: followMacro.beforeSend,
					url: "/search?q=(%0)&select=title:!%1&select=title:!@%1".format([bagString, activeUser.name]),
					dataType: "json",
					success: function(tiddlers) {
						pleaseWait.hide();
						var suggestions = [];
						for(var i = 0; i < tiddlers.length; i++) {
							var tiddler = tiddlers[i];
							if(tiddler.tags.contains("follow")) {
								var title = tiddler.title;
								if(title.indexOf("@") === 0) {
									title = title.substr(1);
								}
								if(!users.contains(title)) {
									suggestions.pushUnique(title);
								}
							}
						}
						$(place).append("<div>suggestions:</div>");
						var suggestionArea = $("<div class='suggestionArea' />").appendTo(place)[0];
						var id = "more_%0".format([Math.random()]);
						var more = $("<div class='moreButton' />").text("more...").appendTo(place).attr("id", id);
						followSuggestions.cache[id] = suggestions;
						var limit = suggestions.length;
						more.click(function(ev) {
							var suggestions = config.macros.followSuggestions.cache[id];
							var newSuggestions = followSuggestions.suggest(place, suggestions, limit);
							config.macros.followSuggestions.cache[id] = newSuggestions;
						});
						followSuggestions.suggest(place, suggestions, limit);
					
					}
				});
			
			}, user);
		});
	},
	randomize: function(a, b) {
		if(Math.random() < Math.random()) {
			return -1;
		} else {
			return 1;
		}
	},
	suggest: function(place, suggestions, limit) {
		var currentSpace = tiddlyspace.currentSpace.name;
		suggestions = suggestions.sort(followSuggestions.randomize);
		var suggestionsArea = $(".suggestionArea", place)[0];
		if(suggestions.length === 0) {
			$("<span />").text("no suggestions..").appendTo(suggestionsArea);
			return;
		}
		limit = limit < suggestions.length ? limit : suggestions.length;
		for(var j = 0; j < limit; j++) {
			var link = $("<span />").appendTo(suggestionsArea)[0];
			var title = suggestions[j];
			var newTiddler = '@%0 <<newTiddler title:"@%0" fields:"server.workspace:bags/%1_public" tag:follow label:"follow">>\n'.format([title, currentSpace]);
			wikify(newTiddler, link);
		}
		var newSuggestions = suggestions.slice(limit, suggestions.length);
		var more = $(".moreButton", place);
		if(newSuggestions.length == 0) {
			more.remove();
		}
		return newSuggestions;
	}
};
})(jQuery);
//}}}
<!--{{{-->
<div class='toolbar'
	macro='toolbar [[ToolbarCommands::EditToolbar]] icons:yes'>
</div>
<div class='heading editorHeading'>
	<div class='editor title' macro='edit title'></div>
	<div class='tagClear'></div>
</div>
<div class='annotationsBox' macro='annotations'>
	<div class='editSpaceSiteIcon'
		macro='tiddlerOrigin height:16 width:16 label:no interactive:no'>
	</div>
	<div class="privacyEdit" macro='setPrivacy label:no interactive:no defaultValue:public'></div>
	<div class='tagClear'></div>
</div>
<div class='editor' macro='edit text'></div>
<div class='editorFooter'>
	<div class='tagsection'>
	tags:<span class='editor' macro='niceTagger'></span>
</div>
<!--}}}-->
/*{{{*/
.tiddler {position: relative;}
.tiddlerOrigin {position: absolute; top: 60px; right: 5px;}
.tiddler .modifier {
position:absolute;
right:10px;
top:120px;
}
.tiddler .modifier .siteIcon {
width:48px;
height:48px;
}
.niceTaggerAdder input {width:auto;display:inline;}
.niceTaggerAdder .adder {display:inline;width:auto;}
.clear {clear:both;}
.tagged a {display:block;}
body {background-color:white;}
.tip {font-style:italic;font-weight:bold;}
.dp-popup {position:absolute;background-color:white;} 
a.dp-choose-date { float: left; 
width: 16px; height: 16px; padding: 0; margin: 5px 3px 0; display: block; 
text-indent: -2000px; overflow: hidden; background: url(calendar.png) no-repeat; }
a.dp-choose-date.dp-disabled { background-position: 0 -20px; cursor: default;}input.dp-applied { width: 140px; float: left;}
.niceTagger input {width:200px; float:left;}
.deleter {color:red; font-weight:bold; padding:2px; cursor:pointer;}
.tiddler img {
	-moz-box-shadow: 2px 2px 4px 4px black;
	-webkit-box-shadow: 2px 2px 4px 4px black;
}

.ftLabelText {float:left;}
.ftLabelImage {height:25px;float:left;}
#contentWrapper .FamilyTree .VGraph {height:150px;width:600px;margin:auto;}
.FamilyTree {
background-color:white;
border-bottom:7px solid black;
border-left:7px solid black;
height:230px;
left:420px;
position:absolute;
right:7px;
top:0;
z-index:3;
}

.changeAlgorithm {right:65px;}
.canvasLabel {position:absolute; font-size:0.7em;color:black;cursor:pointer;}
.fromRoot0 {font-size:1.2em;}
.fromRoot1 {font-size:1.1em;}
.fromRoot2 {font-size:1.0em;}
.fromRoot3 {font-size:0.9em;}
.fromRoot4 {font-size:0.8em;}
.hoverNode {background-color:white;font-weight:bold;z-index:2;font-size:1.2em;}

.ac_results {	padding: 0px;	border: 1px solid black;	background-color: white;	overflow: hidden;	z-index: 99999;}
.ac_results ul {	width: 100%;	list-style-position: outside;	list-style: none;	padding: 0;	margin: 0;}
.ac_results li {	margin: 0px;	padding: 2px 5px;	cursor: default;	display: block;	/* 
	if width will be 100% horizontal scrollbar will apear 
	when scroll mode will be used
	*/
	/*width: 100%;*/
	font: menu;	font-size: 12px;	/* 
	it is very important, if line-height not setted or setted 
	in relative units scroll will be broken in firefox
	*/
	line-height: 16px;	overflow: hidden;}
.ac_loading {	background: white url('indicator.gif') right center no-repeat;}
.ac_odd {	background-color: #eee;}
.ac_over {background-color:#4DA6C9;color: white;}


a,.tabSelected,#sidebarOptions .sliderPanel a{color:#008500;}
.button {background-color:white;border:1px solid #FFFFFF;color:green;margin-right:2px;padding:10px;}
#topToolbar {margin-top:10px;margin-left:-12px;}
#messageArea {background:#39ac1b;border:1px solid white;z-index:100;}
.nodeLabel {width:200px; overflow:hidden;}
.factbox {border:1px dashed #024E02;
color:black;
font-weight:bold;
padding:10px;}
.subtitle {padding-top:5px;}
.ftSubTitle {color:white;
font-size:1.2em;
left:20px;
position:relative;
top:80px;
z-index:3;}
.ftSubTitle a {color:white;}
#sidebarOptions input,.tagging, .tagged {
background-color:none;
border:1px dashed #024E02;
}



.tagsection input {width:150px;}
.button:hover {background-color:rgb(110,220,90);color:white;border-left:solid 1px black;border-right:solid 1px black;border-top:solid 1px black;}
.tiddler .button {padding:0.4em 1.2em;} 

.sexMale .title,.command_addFather, .sexFemale .command_addSpouse {border-bottom:solid 5px #71B4FF;}
.sexFemale .title,.command_addMother,.sexMale .command_addSpouse{border-bottom:solid 5px #ed00f5;}
.yourSearchResult {z-index:99999;}
.tiddler {background-color:white;margin-top:10px;padding:0 10px 20px;}
#displayArea {margin:1em 17em 0 1em;padding:0px;}
body {font-family: Helvetica, Arial, Sans-serif;color:#024E02;}
h1,h2,h3,h4,h5,.title{color:#39ac1b;}
.title {font-size:3em;}
.siteIcon {float:left;height:51px;margin-right:10px;}
.ftTitle {color:#39ac1b;font-size:52px;float:left;position:relative;font-weight:700;margin-bottom:10px;}
.ftContainer {background-color:#39ac1b;padding:20px;position:relative;top:-12px;margin-right:17px;left:10px;z-index:2;}
#sidebarOptions .sliderPanel {background-color:#EEEEEE;}
.ftTitleBG {color:white;z-index:2;}
.ftContainer #displayArea {background-color:auto;}
.ftContainer #sidebar {background-color:white;margin-right:40px;}
.ft_tooltip {background-color:white;padding:10px;color:#39ac1b;z-index:40; font-weight:bold;}
#tiddlerDisplay {margin-top:70px;}

.tiddlerContainer {margin-left:10px;margin-right:10px;}
.toolbar {margin-top:10px;}

.tabContents {
color:black;
}
.tagging .listTitle, .tagged .listTitle {
color:black;
}

.ftHideCorner {border-color:#39AC1B #39AC1B white white;
border-style:solid;
border-width:20px 20px 10px 10px;
position:absolute;
left:0;
bottom:0;
z-index:1;
}
.zooming {cursor:crosshair;}
.panning {cursor:move;}
.VismoCanvas {z-index:11;margin-left:10px;}
.changeroot {margin-left:50%;width:200px;right:100px;z-index:10;position:relative;}
.changeAlgorithm {z-index:100;position:absolute;right:70px;bottom:0px;}
.yourSearchNaviBar .currentPage {color:#39AC1B;}

#yourSearchResult {background-color:#EEEEEE;background:#EEEEEE none repeat scroll 0 0;}
.yourSearchResult .button {padding:0px;}
/*}}}*/
@@Please do not modify this tiddler; it was created automatically upon space creation.@@
iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAKGmlDQ1BJQ0MgUHJvZmlsZQAAeAHVlmdUFMkWx6t7ciLNkNOQc84gOSfJUVSGAYY4wpAxIbK4AooiIgLKEpao4KoEWQMiigERUEBF3UEWAWVdDIiKyuuBd9w977z99r6826eqfn3r9q3quvXhDwDpIyMpKQEWACCRncrxdbajB4eE0nGTAAIUgAe6wJDBTEmy9fb2AP9oH8aRaMTua/Fy/WPYf58QjIxKYQIAeSPTEZEpzESEzyNsyEzipCI8h/BwRmoSwnA3wjQOskGEB3nMWmcujyPW+f1ajL+vPQAoPAB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P1etseMPrdn5RherIJkC3B/TXUkqKCymRBlom0K/SPzT7H3p41/tLBc18T8uSCDAjweBdZq/jytcNBu5Gi9XE07cSjyeTBJrddL2iqOr+B7c/8cG0w1J/L5kAAxQM3mR022+gwy18dNO0W1O0Vx/Y/sTRUoMtZK8kBAoZvlxtc2aMywViKX7+D10+ywDx0s0HAAAAAElFTkSuQmCC
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" version="1.1" viewBox="72 648 70 70" 
width="30" height="30">
<g stroke="none" stroke-opacity="1" stroke-dasharray="none" fill="none" fill-opacity="1">
	<g>
		<path d="M 77.59005 669.34003 C 71.532745 681.90424 73.714462 697.4441 84.135193 707.86475 
		C 97.315445 721.0451 118.684715 721.0451 131.8649 707.86475 
		C 145.04515 694.68457 145.04515 673.31537 131.8649 660.13513 
		C 121.4441 649.7141 105.90419 647.53253 93.339905 653.5899 L 102.047455 662.2976 
		C 109.58637 660.2373 117.987976 662.16803 123.90997 668.08997 
		C 132.69673 676.8767 132.69673 691.12317 123.90997 699.90985 
		C 115.12313 708.6966 100.87699 708.6966 92.09012 699.90985 
		C 86.168266 693.98804 84.23744 685.58643 86.297653 678.04755 Z M 72 648 L 72 668.25 L 78.75 661.49957 
		L 99.00019 681.7502 L 105.750175 675.00006 L 85.50013 654.75012 L 92.249985 648 Z" fill="black"
		class="glyph"/>
	</g>
</g>
</svg>
config.extensions.tiddlyweb.getUserInfo(function(user){
  if(user.anon) {
    config.extensions.tiddlyspace.disableTab(["TabMoreOrphans", "TabMoreShadowed", "TabMoreMissing"]);
  }
});
/*!
 * jQuery Form Plugin
 * version: 2.83 (11-JUL-2011)
 * @requires jQuery v1.3.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function(e) {
			e.preventDefault(); // <-- important
			$(this).ajaxSubmit({
				target: '#output'
			});
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}
	
	var method, action, url, $form = this;

	if (typeof options == 'function') {
		options = { success: options };
	}

	method = this.attr('method');
	action = this.attr('action');
	url = (typeof action === 'string') ? $.trim(action) : '';
	url = url || window.location.href || '';
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
	}

	options = $.extend(true, {
		url:  url,
		success: $.ajaxSettings.success,
		type: method || 'GET',
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options);

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var n,v,a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (n in options.data) {
			if(options.data[n] instanceof Array) {
				for (var k in options.data[n]) {
					a.push( { name: n, value: options.data[n][k] } );
				}
			}
			else {
				v = options.data[n];
				v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
				a.push( { name: n, value: v } );
			}
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else {
		options.data = q; // data is the query string for 'post'
	}

	var callbacks = [];
	if (options.resetForm) {
		callbacks.push(function() { $form.resetForm(); });
	}
	if (options.clearForm) {
		callbacks.push(function() { $form.clearForm(); });
	}

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			var fn = options.replaceTarget ? 'replaceWith' : 'html';
			$(options.target)[fn](data).each(oldSuccess, arguments);
		});
	}
	else if (options.success) {
		callbacks.push(options.success);
	}

	options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
		var context = options.context || options;   // jQuery 1.4+ supports scope context 
		for (var i=0, max=callbacks.length; i < max; i++) {
			callbacks[i].apply(context, [data, status, xhr || $form, $form]);
		}
	};

	// are there files to upload?
	var fileInputs = $('input:file', this).length > 0;
	var mp = 'multipart/form-data';
	var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive) {
		   $.get(options.closeKeepAlive, function() { fileUpload(a); });
		}
	   else {
		   fileUpload(a);
		}
   }
   else {
		// IE7 massage (see issue 57)
		if ($.browser.msie && method == 'get') { 
			var ieMeth = $form[0].getAttribute('method');
			if (typeof ieMeth === 'string')
				options.type = ieMeth;
		}
		$.ajax(options);
   }

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload(a) {
		var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
        var useProp = !!$.fn.prop;

        if (a) {
        	// ensure that every serialized input is still enabled
          	for (i=0; i < a.length; i++) {
                el = $(form[a[i].name]);
                el[ useProp ? 'prop' : 'attr' ]('disabled', false);
          	}
        }

		if ($(':input[name=submit],:input[id=submit]', form).length) {
			// if there is an input with a name or id of 'submit' then we won't be
			// able to invoke the submit fn on the form (at least not x-browser)
			alert('Error: Form elements must not have name or id of "submit".');
			return;
		}
		
		s = $.extend(true, {}, $.ajaxSettings, options);
		s.context = s.context || s;
		id = 'jqFormIO' + (new Date().getTime());
		if (s.iframeTarget) {
			$io = $(s.iframeTarget);
			n = $io.attr('name');
			if (n == null)
			 	$io.attr('name', id);
			else
				id = n;
		}
		else {
			$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
			$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
		}
		io = $io[0];


		xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function(status) {
				var e = (status === 'timeout' ? 'timeout' : 'aborted');
				log('aborting upload... ' + e);
				this.aborted = 1;
				$io.attr('src', s.iframeSrc); // abort op in progress
				xhr.error = e;
				s.error && s.error.call(s.context, xhr, e, status);
				g && $.event.trigger("ajaxError", [xhr, s, e]);
				s.complete && s.complete.call(s.context, xhr, e);
			}
		};

		g = s.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) {
			$.event.trigger("ajaxStart");
		}
		if (g) {
			$.event.trigger("ajaxSend", [xhr, s]);
		}

		if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
			if (s.global) {
				$.active--;
			}
			return;
		}
		if (xhr.aborted) {
			return;
		}

		// add submitting element to data if we know it
		sub = form.clk;
		if (sub) {
			n = sub.name;
			if (n && !sub.disabled) {
				s.extraData = s.extraData || {};
				s.extraData[n] = sub.value;
				if (sub.type == "image") {
					s.extraData[n+'.x'] = form.clk_x;
					s.extraData[n+'.y'] = form.clk_y;
				}
			}
		}
		
		var CLIENT_TIMEOUT_ABORT = 1;
		var SERVER_ABORT = 2;

		function getDoc(frame) {
			var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document;
			return doc;
		}
		
		// take a breath so that pending repaints get some cpu time before the upload starts
		function doSubmit() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (!method) {
				form.setAttribute('method', 'POST');
			}
			if (a != s.url) {
				form.setAttribute('action', s.url);
			}

			// ie borks in some cases when setting encoding
			if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (s.timeout) {
				timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
			}
			
			// look for server aborts
			function checkState() {
				try {
					var state = getDoc(io).readyState;
					log('state = ' + state);
					if (state.toLowerCase() == 'uninitialized')
						setTimeout(checkState,50);
				}
				catch(e) {
					log('Server abort: ' , e, ' (', e.name, ')');
					cb(SERVER_ABORT);
					timeoutHandle && clearTimeout(timeoutHandle);
					timeoutHandle = undefined;
				}
			}

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (s.extraData) {
					for (var n in s.extraData) {
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" />').attr('value',s.extraData[n])
								.appendTo(form)[0]);
					}
				}

				if (!s.iframeTarget) {
					// add iframe to doc and submit the form
					$io.appendTo('body');
	                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
				}
				setTimeout(checkState,15);
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				if(t) {
					form.setAttribute('target', t);
				} else {
					$form.removeAttr('target');
				}
				$(extraInputs).remove();
			}
		}

		if (s.forceSync) {
			doSubmit();
		}
		else {
			setTimeout(doSubmit, 10); // this lets dom updates render
		}

		var data, doc, domCheckCount = 50, callbackProcessed;

		function cb(e) {
			if (xhr.aborted || callbackProcessed) {
				return;
			}
			try {
				doc = getDoc(io);
			}
			catch(ex) {
				log('cannot access response document: ', ex);
				e = SERVER_ABORT;
			}
			if (e === CLIENT_TIMEOUT_ABORT && xhr) {
				xhr.abort('timeout');
				return;
			}
			else if (e == SERVER_ABORT && xhr) {
				xhr.abort('server abort');
				return;
			}

			if (!doc || doc.location.href == s.iframeSrc) {
				// response not received yet
				if (!timedOut)
					return;
			}
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

			var status = 'success', errMsg;
			try {
				if (timedOut) {
					throw 'timeout';
				}

				var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
					if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
						log('requeing onLoad callback, DOM not available');
						setTimeout(cb, 250);
						return;
					}
					// let this fall through because server response could be an empty document
					//log('Could not access iframe DOM after mutiple tries.');
					//throw 'DOMException: not available';
				}

				//log('response detected');
                var docRoot = doc.body ? doc.body : doc.documentElement;
                xhr.responseText = docRoot ? docRoot.innerHTML : null;
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				if (isXml)
					s.dataType = 'xml';
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': s.dataType};
					return headers[header];
				};
                // support for XHR 'status' & 'statusText' emulation :
                if (docRoot) {
                    xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
                    xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
                }

				var dt = s.dataType || '';
				var scr = /(json|script|text)/.test(dt.toLowerCase());
				if (scr || s.textarea) {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta) {
						xhr.responseText = ta.value;
                        // support for XHR 'status' & 'statusText' emulation :
                        xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
                        xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
					}
					else if (scr) {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						var b = doc.getElementsByTagName('body')[0];
						if (pre) {
							xhr.responseText = pre.textContent ? pre.textContent : pre.innerHTML;
						}
						else if (b) {
							xhr.responseText = b.innerHTML;
						}
					}
				}
				else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}

                try {
                    data = httpData(xhr, s.dataType, s);
                }
                catch (e) {
                    status = 'parsererror';
                    xhr.error = errMsg = (e || status);
                }
			}
			catch (e) {
				log('error caught: ',e);
				status = 'error';
                xhr.error = errMsg = (e || status);
			}

			if (xhr.aborted) {
				log('upload aborted');
				status = null;
			}

            if (xhr.status) { // we've set xhr.status
                status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
            }

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (status === 'success') {
				s.success && s.success.call(s.context, data, 'success', xhr);
				g && $.event.trigger("ajaxSuccess", [xhr, s]);
			}
            else if (status) {
				if (errMsg == undefined)
					errMsg = xhr.statusText;
				s.error && s.error.call(s.context, xhr, status, errMsg);
				g && $.event.trigger("ajaxError", [xhr, s, errMsg]);
            }

			g && $.event.trigger("ajaxComplete", [xhr, s]);

			if (g && ! --$.active) {
				$.event.trigger("ajaxStop");
			}

			s.complete && s.complete.call(s.context, xhr, status);

			callbackProcessed = true;
			if (s.timeout)
				clearTimeout(timeoutHandle);

			// clean up
			setTimeout(function() {
				if (!s.iframeTarget)
					var a = true;//$io.remove();
				xhr.responseXML = null;
			}, 100);
		}

		var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else {
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			}
			return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
		};
		var parseJSON = $.parseJSON || function(s) {
			return window['eval']('(' + s + ')');
		};

		var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4

			var ct = xhr.getResponseHeader('content-type') || '',
				xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
				data = xml ? xhr.responseXML : xhr.responseText;

			if (xml && data.documentElement.nodeName === 'parsererror') {
				$.error && $.error('parsererror');
			}
			if (s && s.dataFilter) {
				data = s.dataFilter(data, type);
			}
			if (typeof data === 'string') {
				if (type === 'json' || !type && ct.indexOf('json') >= 0) {
					data = parseJSON(data);
				} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
					$.globalEval(data);
				}
			}
			return data;
		};
	}
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	// in jQuery 1.3+ we can fix mistakes with the ready state
	if (this.length === 0) {
		var o = { s: this.selector, c: this.context };
		if (!$.isReady && o.s) {
			log('DOM not ready, queuing ajaxForm');
			$(function() {
				$(o.s,o.c).ajaxForm(options);
			});
			return this;
		}
		// is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
		log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
		return this;
	}

	return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
		if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
			e.preventDefault();
			$(this).ajaxSubmit(options);
		}
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0) {
				return;
			}
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length === 0) {
		return a;
	}

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) {
		return a;
	}

	var i,j,n,v,el,max,jmax;
	for(i=0, max=els.length; i < max; i++) {
		el = els[i];
		n = el.name;
		if (!n) {
			continue;
		}

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(j=0, jmax=v.length; j < jmax; j++) {
				a.push({name: n, value: v[j]});
			}
		}
		else if (v !== null && typeof v != 'undefined') {
			a.push({name: n, value: v});
		}
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0];
		n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) {
			return;
		}
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++) {
				a.push({name: n, value: v[i]});
			}
		}
		else if (v !== null && typeof v != 'undefined') {
			a.push({name: this.name, value: v});
		}
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
			continue;
		}
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (successful === undefined) {
		successful = true;
	}

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1)) {
			return null;
	}

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) {
			return null;
		}
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) { // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				}
				if (one) {
					return v;
				}
				a.push(v);
			}
		}
		return a;
	}
	return $(el).val();
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
	return this.each(function() {
		var t = this.type, tag = this.tagName.toLowerCase();
		if (re.test(t) || tag == 'textarea') {
			this.value = '';
		}
		else if (t == 'checkbox' || t == 'radio') {
			this.checked = false;
		}
		else if (tag == 'select') {
			this.selectedIndex = -1;
		}
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
			this.reset();
		}
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b === undefined) {
		b = true;
	}
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select === undefined) {
		select = true;
	}
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio') {
			this.checked = select;
		}
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
function log() {
	var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
	if (window.console && window.console.log) {
		window.console.log(msg);
	}
	else if (window.opera && window.opera.postError) {
		window.opera.postError(msg);
	}
};

})(jQuery);
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" version="1.1" viewBox="364 436 64 64" width="64pt" height="64pt"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:date>2010-09-01 12:45Z</dc:date><!-- Produced by OmniGraffle Professional 5.2.3 --></metadata><defs></defs><g stroke="none" stroke-opacity="1" stroke-dasharray="none" fill="none" fill-opacity="1"><title>Canvas 1</title><g><title>Layer 1</title><path d="M 389.90918 470.9098 L 382.49954 463.5 C 380.19644 463.4999 377.89328 462.62125 376.13608 460.86398 C 372.62137 457.34927 372.62137 451.65073 376.13608 448.13608 C 379.65079 444.6213 385.34927 444.6213 388.86404 448.13608 C 390.62158 449.89368 391.50024 452.19733 391.5 454.50092 L 398.90936 461.91003 C 401.90042 455.2835 400.67325 447.21735 395.22794 441.7721 C 388.19858 434.74268 376.80151 434.74268 369.77216 441.7721 C 362.74268 448.80151 362.74268 460.19852 369.77216 467.2279 C 375.21716 472.67303 383.2828 473.9003 389.90918 470.9098 Z M 393.09024 474.09082 C 390.09973 480.71725 391.32697 488.78296 396.7721 494.2279 C 403.80148 501.2574 415.19858 501.2574 422.2279 494.2279 C 429.25739 487.19858 429.25739 475.80154 422.2279 468.7721 C 416.78271 463.3268 408.71655 462.09967 402.09006 465.0906 L 409.49979 472.50003 C 411.8031 472.4999 414.10654 473.3786 415.86398 475.13608 C 419.3787 478.6508 419.3787 484.34927 415.86398 487.86398 C 412.34927 491.3787 406.65079 491.3787 403.13608 487.86398 C 401.37881 486.10678 400.50012 483.80374 400.50003 481.50064 Z M 380.25012 459.00006 L 405 483.75 L 411.75 477 L 387.00006 452.25 Z" fill="black"/></g></g></svg>
<<showInstall familytree "Create your own">>
!Author your tree
Start creating your family tree by clicking new person at the top of the screen.

!Import GEDCOM
If you have an existing GEDCOM file here is a way to get your information into TiddlySpace for experimentation purposes.
<<gedcomImport>>
//If you have any issues with these please send me your gedcom file and explain the problem to jdlrobson@gmail.com//

!Upload a family crest
Personalise your family tree by uploading a SiteIcon
<<image SiteIcon height:48 width:48>>
<<binaryUploadPublic title:SiteIcon>>

!Set your visualization
Then tweak the [[FamilyTree]] so that the rootNode is set to the ancestor you want to create the tree from. Alternatively exclude the tiddlytagmindmap space to disable the graph completely if you don't want to use it.

!Get rid of me
Remove the rootTree tag from this tiddler to stop it appearing every time you load the page.
/***
|''Name:''|AETDates|
|''Requires''|AETPlugin|
|''Version:''|0.8.5|
|''Description:''|Adds dates to the AdvancedEditTemplatePlugin|
|''Author:''|JonRobson |
|''Comments:''|Please make comments at http://groups.google.co.uk/group/TiddlyWikiDev |
|''License:''|[[BSD License|http://www.opensource.org/licenses/bsd-license.php]] |
|''Requires:''|[[AdvancedEditTemplate (core code)|http://svn.tiddlywiki.org/Trunk/contributors/JonRobson/plugins/AET/plugins/AET.js]]|
!Usage
{{{<<aet type:date field:fieldname>>}}}
***/
//{{{
(function($) {
var aet = config.macros.aet;
var ext = config.macros.aet.extensions.date = {
	format: "0DD/0MM/YYYY",
	_inputToYYYYMMDD: function(dmy) {
		if(dmy) {
			var d = "00", m = "00", y = "00";
			var separator;
			if(dmy.indexOf("/") > -1) {
				separator = "/";
			} else if(dmy.indexOf("-") > -1) {
				separator = "-";
			}
			if(separator) {
				dmy = dmy.split(separator);
				if(dmy.length == 3) {
					d = dmy[0] || d;
					m = dmy[1] || m;
					y = dmy[2] || y;
				} else if(dmy.length == 2) {
					m = dmy[0] || m;
					y = dmy[1] || y;
				}
			} else {
				d = "00";
				m = "00";
				y = dmy;
			}
			d = d.length == 1 ? "0" + d : d;
			m = m.length == 1 ? "0" + m : m;
			y = y.match(/[0-9]{4}$/) ? y : false;
			m = m.match(/[0-9]{2}$/) ? m : false;
			d = d.match(/[0-9]{2}$/) ? d : false;
			if(y && d && m) {
				val = y + m + d + "0000";
			} else {
				val = false;
			}
		} else {
			val = false;
		}
		return val;
	},
	_changeDate: function(ev, title, metaDataName, autosavechanges) {
		var dmy = $(ev.target).val();
		var val = ext._inputToYYYYMMDD(dmy);
		aet.setMetaData(title, metaDataName, val, autosavechanges);
		$("input[name=%0]".format(metaDataName)).
			val(ext._getDateString(val));
	},
	_getDateString: function(val, format) {
		format = format ||  aet.extensions.date.format;
		var noMonth = val.match(/^[0-9]{4}00/);
		var noDay = val.match(/^[0-9]{4}[0-9]{2}00/);
		if(noMonth || noDay) {
			return val.substr(0, 4);
		} else {
			var date = Date.convertFromYYYYMMDDHHMM(val);
			return date.formatString(format);
		}
	},
	createDatePicker: function(place,title,metaDataName,autosavechanges){
		var tiddler = store.getTiddler(title);
		var params = [metaDataName];
		var div = $("<div />").addClass("datePicker").appendTo(place);
		var input = $("<input />").addClass("date-pick").
			attr("name", metaDataName).appendTo(div);
		$("<div />").addClass("clearboth").appendTo(div);
		$(function() {
			var start = aet.getMetaData(title,metaDataName);
			start = start ? ext._getDateString(start) : "";
			$(input).datePicker({ startDate: '01/01/1600' }).val(start).trigger('change').
				change(function(ev) {
					ext._changeDate(ev, title, metaDataName, autosavechanges);
				});
		});
	}
};
config.macros.aet.controlTypes.date = function(place, tiddler, fieldName, options) {
	config.macros.aet.extensions.date.createDatePicker(place, tiddler.title, fieldName);
};
})(jQuery);

/*
 * Date prototype extensions. Doesn't depend on any
 * other code. Doens't overwrite existing methods.
 *
 * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
 * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
 * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
 *
 * Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 *
 * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
 * I've added my name to these methods so you know who to blame if they are broken!
 * 
 * Dual licensed under the MIT and GPL licenses:
 *	 http://www.opensource.org/licenses/mit-license.php
 *	 http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * An Array of day names starting with Sunday.
 * 
 * @example dayNames[0]
 * @result 'Sunday'
 *
 * @name dayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

/**
 * An Array of abbreviated day names starting with Sun.
 * 
 * @example abbrDayNames[0]
 * @result 'Sun'
 *
 * @name abbrDayNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

/**
 * An Array of month names starting with Janurary.
 * 
 * @example monthNames[0]
 * @result 'January'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

/**
 * An Array of abbreviated month names starting with Jan.
 * 
 * @example abbrMonthNames[0]
 * @result 'Jan'
 *
 * @name monthNames
 * @type Array
 * @cat Plugins/Methods/Date
 */
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

/**
 * The first day of the week for this locale.
 *
 * @name firstDayOfWeek
 * @type Number
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.firstDayOfWeek = 1;

/**
 * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';

/**
 * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
 * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
 *
 * @name format
 * @type String
 * @cat Plugins/Methods/Date
 * @author Kelvin Luck
 */
Date.fullYearStart = '20';

(function() {

	/**
	 * Adds a given method under the given name 
	 * to the Date prototype if it doesn't
	 * currently exist.
	 *
	 * @private
	 */
	function add(name, method) {
		if( !Date.prototype[name] ) {
			Date.prototype[name] = method;
		}
	};
	
	/**
	 * Checks if the year is a leap year.
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isLeapYear();
	 * @result true
	 *
	 * @name isLeapYear
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isLeapYear", function() {
		var y = this.getFullYear();
		return (y%4==0 && y%100!=0) || y%400==0;
	});
	
	/**
	 * Checks if the day is a weekend day (Sat or Sun).
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isWeekend();
	 * @result false
	 *
	 * @name isWeekend
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isWeekend", function() {
		return this.getDay()==0 || this.getDay()==6;
	});
	
	/**
	 * Check if the day is a day of the week (Mon-Fri)
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.isWeekDay();
	 * @result false
	 * 
	 * @name isWeekDay
	 * @type Boolean
	 * @cat Plugins/Methods/Date
	 */
	add("isWeekDay", function() {
		return !this.isWeekend();
	});
	
	/**
	 * Gets the number of days in the month.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDaysInMonth();
	 * @result 31
	 * 
	 * @name getDaysInMonth
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getDaysInMonth", function() {
		return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
	});
	
	/**
	 * Gets the name of the day.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayName();
	 * @result 'Saturday'
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayName(true);
	 * @result 'Sat'
	 * 
	 * @param abbreviated Boolean When set to true the name will be abbreviated.
	 * @name getDayName
	 * @type String
	 * @cat Plugins/Methods/Date
	 */
	add("getDayName", function(abbreviated) {
		return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
	});

	/**
	 * Gets the name of the month.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getMonthName();
	 * @result 'Janurary'
	 *
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getMonthName(true);
	 * @result 'Jan'
	 * 
	 * @param abbreviated Boolean When set to true the name will be abbreviated.
	 * @name getDayName
	 * @type String
	 * @cat Plugins/Methods/Date
	 */
	add("getMonthName", function(abbreviated) {
		return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
	});

	/**
	 * Get the number of the day of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getDayOfYear();
	 * @result 11
	 * 
	 * @name getDayOfYear
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getDayOfYear", function() {
		var tmpdtm = new Date("1/1/" + this.getFullYear());
		return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
	});
	
	/**
	 * Get the number of the week of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.getWeekOfYear();
	 * @result 2
	 * 
	 * @name getWeekOfYear
	 * @type Number
	 * @cat Plugins/Methods/Date
	 */
	add("getWeekOfYear", function() {
		return Math.ceil(this.getDayOfYear() / 7);
	});

	/**
	 * Set the day of the year.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.setDayOfYear(1);
	 * dtm.toString();
	 * @result 'Tue Jan 01 2008 00:00:00'
	 * 
	 * @name setDayOfYear
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("setDayOfYear", function(day) {
		this.setMonth(0);
		this.setDate(day);
		return this;
	});
	
	/**
	 * Add a number of years to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addYears(1);
	 * dtm.toString();
	 * @result 'Mon Jan 12 2009 00:00:00'
	 * 
	 * @name addYears
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addYears", function(num) {
		this.setFullYear(this.getFullYear() + num);
		return this;
	});
	
	/**
	 * Add a number of months to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addMonths(1);
	 * dtm.toString();
	 * @result 'Tue Feb 12 2008 00:00:00'
	 * 
	 * @name addMonths
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addMonths", function(num) {
		var tmpdtm = this.getDate();
		
		this.setMonth(this.getMonth() + num);
		
		if (tmpdtm > this.getDate())
			this.addDays(-this.getDate());
		
		return this;
	});
	
	/**
	 * Add a number of days to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addDays(1);
	 * dtm.toString();
	 * @result 'Sun Jan 13 2008 00:00:00'
	 * 
	 * @name addDays
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addDays", function(num) {
		//this.setDate(this.getDate() + num);
		this.setTime(this.getTime() + (num*86400000) );
		return this;
	});
	
	/**
	 * Add a number of hours to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addHours(24);
	 * dtm.toString();
	 * @result 'Sun Jan 13 2008 00:00:00'
	 * 
	 * @name addHours
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addHours", function(num) {
		this.setHours(this.getHours() + num);
		return this;
	});

	/**
	 * Add a number of minutes to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addMinutes(60);
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 01:00:00'
	 * 
	 * @name addMinutes
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addMinutes", function(num) {
		this.setMinutes(this.getMinutes() + num);
		return this;
	});
	
	/**
	 * Add a number of seconds to the date object.
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.addSeconds(60);
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:01:00'
	 * 
	 * @name addSeconds
	 * @type Date
	 * @cat Plugins/Methods/Date
	 */
	add("addSeconds", function(num) {
		this.setSeconds(this.getSeconds() + num);
		return this;
	});
	
	/**
	 * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
	 * 
	 * @example var dtm = new Date();
	 * dtm.zeroTime();
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:01:00'
	 * 
	 * @name zeroTime
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	add("zeroTime", function() {
		this.setMilliseconds(0);
		this.setSeconds(0);
		this.setMinutes(0);
		this.setHours(0);
		return this;
	});
	
	/**
	 * Returns a string representation of the date object according to Date.format.
	 * (Date.toString may be used in other places so I purposefully didn't overwrite it)
	 * 
	 * @example var dtm = new Date("01/12/2008");
	 * dtm.asString();
	 * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
	 * 
	 * @name asString
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	add("asString", function(format) {
		var r = format || Date.format;
		return r
			.split('yyyy').join(this.getFullYear())
			.split('yy').join((this.getFullYear() + '').substring(2))
			.split('mmmm').join(this.getMonthName(false))
			.split('mmm').join(this.getMonthName(true))
			.split('mm').join(_zeroPad(this.getMonth()+1))
			.split('dd').join(_zeroPad(this.getDate()));
	});
	
	/**
	 * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
	 * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
	 *
	 * @example var dtm = Date.fromString("12/01/2008");
	 * dtm.toString();
	 * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
	 * 
	 * @name fromString
	 * @type Date
	 * @cat Plugins/Methods/Date
	 * @author Kelvin Luck
	 */
	Date.fromString = function(s)
	{
		var f = Date.format;
		var d = new Date('01/01/1977');
		
		var mLength = 0;

		var iM = f.indexOf('mmmm');
		if (iM > -1) {
			for (var i=0; i<Date.monthNames.length; i++) {
				var mStr = s.substr(iM, Date.monthNames[i].length);
				if (Date.monthNames[i] == mStr) {
					mLength = Date.monthNames[i].length - 4;
					break;
				}
			}
			d.setMonth(i);
		} else {
			iM = f.indexOf('mmm');
			if (iM > -1) {
				var mStr = s.substr(iM, 3);
				for (var i=0; i<Date.abbrMonthNames.length; i++) {
					if (Date.abbrMonthNames[i] == mStr) break;
				}
				d.setMonth(i);
			} else {
				d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
			}
		}
		
		var iY = f.indexOf('yyyy');

		if (iY > -1) {
			if (iM < iY)
			{
				iY += mLength;
			}
			d.setFullYear(Number(s.substr(iY, 4)));
		} else {
			if (iM < iY)
			{
				iY += mLength;
			}
			// TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
			d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
		}
		var iD = f.indexOf('dd');
		if (iM < iD)
		{
			iD += mLength;
		}
		d.setDate(Number(s.substr(iD, 2)));
		if (isNaN(d.getTime())) {
			return false;
		}
		return d;
	};
	
	// utility method
	var _zeroPad = function(num) {
		var s = '0'+num;
		return s.substring(s.length-2)
		//return ('0'+num).substring(-2); // doesn't work on IE :(
	};
	
})();

/**
 * Copyright (c) 2008 Kelvin Luck (http://www.kelvinluck.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $Id: jquery.datePicker.js 70 2009-04-05 19:25:15Z kelvin.luck $
 **/

(function($){
		
	$.fn.extend({
/**
 * Render a calendar table into any matched elements.
 * 
 * @param Object s (optional) Customize your calendars.
 * @option Number month The month to render (NOTE that months are zero based). Default is today's month.
 * @option Number year The year to render. Default is today's year.
 * @option Function renderCallback A reference to a function that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Default is no callback.
 * @option Number showHeader Whether or not to show the header row, possible values are: $.dpConst.SHOW_HEADER_NONE (no header), $.dpConst.SHOW_HEADER_SHORT (first letter of each day) and $.dpConst.SHOW_HEADER_LONG (full name of each day). Default is $.dpConst.SHOW_HEADER_SHORT.
 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
 * @type $
 * @name renderCalendar
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#calendar-me').renderCalendar({month:0, year:2007});
 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me.
 *
 * @example
 * var testCallback = function($td, thisDate, month, year)
 * {
 * if ($td.is('.current-month') && thisDate.getDay() == 4) {
 *		var d = thisDate.getDate();
 *		$td.bind(
 *			'click',
 *			function()
 *			{
 *				alert('You clicked on ' + d + '/' + (Number(month)+1) + '/' + year);
 *			}
 *		).addClass('thursday');
 *	} else if (thisDate.getDay() == 5) {
 *		$td.html('Friday the ' + $td.html() + 'th');
 *	}
 * }
 * $('#calendar-me').renderCalendar({month:0, year:2007, renderCallback:testCallback});
 * 
 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me. Every Thursday in the current month has a class of "thursday" applied to it, is clickable and shows an alert when clicked. Every Friday on the calendar has the number inside replaced with text.
 **/
		renderCalendar	:	 function(s)
		{
			var dc = function(a)
			{
				return document.createElement(a);
			};

			s = $.extend({}, $.fn.datePicker.defaults, s);
			
			if (s.showHeader != $.dpConst.SHOW_HEADER_NONE) {
				var headRow = $(dc('tr'));
				for (var i=Date.firstDayOfWeek; i<Date.firstDayOfWeek+7; i++) {
					var weekday = i%7;
					var day = Date.dayNames[weekday];
					headRow.append(
						$(dc('th')).attr({'scope':'col', 'abbr':day, 'title':day, 'class':(weekday == 0 || weekday == 6 ? 'weekend' : 'weekday')}).html(s.showHeader == $.dpConst.SHOW_HEADER_SHORT ? day.substr(0, 1) : day)
					);
				}
			};
			
			var calendarTable = $(dc('table'))
									.attr(
										{
											'cellspacing':2
										}
									)
									.addClass('jCalendar')
									.append(
										(s.showHeader != $.dpConst.SHOW_HEADER_NONE ? 
											$(dc('thead'))
												.append(headRow)
											:
											dc('thead')
										)
									);
			var tbody = $(dc('tbody'));
			
			var today = (new Date()).zeroTime();
			
			var month = s.month == undefined ? today.getMonth() : s.month;
			var year = s.year || today.getFullYear();
			
			var currentDate = new Date(year, month, 1);
			
			
			var firstDayOffset = Date.firstDayOfWeek - currentDate.getDay() + 1;
			if (firstDayOffset > 1) firstDayOffset -= 7;
			var weeksToDraw = Math.ceil(( (-1*firstDayOffset+1) + currentDate.getDaysInMonth() ) /7);
			currentDate.addDays(firstDayOffset-1);
			
			var doHover = function(firstDayInBounds)
			{
				return function()
				{
					if (s.hoverClass) {
						var $this = $(this);
						if (!s.selectWeek) {
							$this.addClass(s.hoverClass);
						} else if (firstDayInBounds && !$this.is('.disabled')) {
							$this.parent().addClass('activeWeekHover');
						}
					}
				}
			};
			var unHover = function()
			{
				if (s.hoverClass) {
					var $this = $(this);
					$this.removeClass(s.hoverClass);
					$this.parent().removeClass('activeWeekHover');
				}
			};

			var w = 0;
			while (w++<weeksToDraw) {
				var r = $(dc('tr'));
				var firstDayInBounds = s.dpController ? currentDate > s.dpController.startDate : false;
				for (var i=0; i<7; i++) {
					var thisMonth = currentDate.getMonth() == month;
					var d = $(dc('td'))
								.text(currentDate.getDate() + '')
								.addClass((thisMonth ? 'current-month ' : 'other-month ') +
													(currentDate.isWeekend() ? 'weekend ' : 'weekday ') +
													(thisMonth && currentDate.getTime() == today.getTime() ? 'today ' : '')
								)
								.data('datePickerDate', currentDate.asString())
								.hover(doHover(firstDayInBounds), unHover)
							;
					r.append(d);
					if (s.renderCallback) {
						s.renderCallback(d, currentDate, month, year);
					}
					// addDays(1) fails in some locales due to daylight savings. See issue 39.
					//currentDate.addDays(1);
					currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()+1);
				}
				tbody.append(r);
			}
			calendarTable.append(tbody);
			
			return this.each(
				function()
				{
					$(this).empty().append(calendarTable);
				}
			);
		},
/**
 * Create a datePicker associated with each of the matched elements.
 *
 * The matched element will receive a few custom events with the following signatures:
 *
 * dateSelected(event, date, $td, status)
 * Triggered when a date is selected. event is a reference to the event, date is the Date selected, $td is a jquery object wrapped around the TD that was clicked on and status is whether the date was selected (true) or deselected (false)
 * 
 * dpClosed(event, selected)
 * Triggered when the date picker is closed. event is a reference to the event and selected is an Array containing Date objects.
 *
 * dpMonthChanged(event, displayedMonth, displayedYear)
 * Triggered when the month of the popped up calendar is changed. event is a reference to the event, displayedMonth is the number of the month now displayed (zero based) and displayedYear is the year of the month.
 *
 * dpDisplayed(event, $datePickerDiv)
 * Triggered when the date picker is created. $datePickerDiv is the div containing the date picker. Use this event to add custom content/ listeners to the popped up date picker.
 *
 * @param Object s (optional) Customize your date pickers.
 * @option Number month The month to render when the date picker is opened (NOTE that months are zero based). Default is today's month.
 * @option Number year The year to render when the date picker is opened. Default is today's year.
 * @option String startDate The first date date can be selected.
 * @option String endDate The last date that can be selected.
 * @option Boolean inline Whether to create the datePicker as inline (e.g. always on the page) or as a model popup. Default is false (== modal popup)
 * @option Boolean createButton Whether to create a .dp-choose-date anchor directly after the matched element which when clicked will trigger the showing of the date picker. Default is true.
 * @option Boolean showYearNavigation Whether to display buttons which allow the user to navigate through the months a year at a time. Default is true.
 * @option Boolean closeOnSelect Whether to close the date picker when a date is selected. Default is true.
 * @option Boolean displayClose Whether to create a "Close" button within the date picker popup. Default is false.
 * @option Boolean selectMultiple Whether a user should be able to select multiple dates with this date picker. Default is false.
 * @option Number numSelectable The maximum number of dates that can be selected where selectMultiple is true. Default is a very high number.
 * @option Boolean clickInput If the matched element is an input type="text" and this option is true then clicking on the input will cause the date picker to appear.
 * @option Boolean rememberViewedMonth Whether the datePicker should remember the last viewed month and open on it. If false then the date picker will always open with the month for the first selected date visible.
 * @option Boolean selectWeek Whether to select a complete week at a time...
 * @option Number verticalPosition The vertical alignment of the popped up date picker to the matched element. One of $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM. Default is $.dpConst.POS_TOP.
 * @option Number horizontalPosition The horizontal alignment of the popped up date picker to the matched element. One of $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT.
 * @option Number verticalOffset The number of pixels offset from the defined verticalPosition of this date picker that it should pop up in. Default in 0.
 * @option Number horizontalOffset The number of pixels offset from the defined horizontalPosition of this date picker that it should pop up in. Default in 0.
 * @option (Function|Array) renderCallback A reference to a function (or an array of seperate functions) that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Each callback function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year. Default is no callback.
 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
 * @type $
 * @name datePicker
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('input.date-picker').datePicker();
 * @desc Creates a date picker button next to all matched input elements. When the button is clicked on the value of the selected date will be placed in the corresponding input (formatted according to Date.format).
 *
 * @example demo/index.html
 * @desc See the projects homepage for many more complex examples...
 **/
		datePicker : function(s)
		{			
			if (!$.event._dpCache) $.event._dpCache = [];
			
			// initialise the date picker controller with the relevant settings...
			s = $.extend({}, $.fn.datePicker.defaults, s);
			
			return this.each(
				function()
				{
					var $this = $(this);
					var alreadyExists = true;
					
					if (!this._dpId) {
						this._dpId = $.event.guid++;
						$.event._dpCache[this._dpId] = new DatePicker(this);
						alreadyExists = false;
					}
					
					if (s.inline) {
						s.createButton = false;
						s.displayClose = false;
						s.closeOnSelect = false;
						$this.empty();
					}
					
					var controller = $.event._dpCache[this._dpId];
					
					controller.init(s);
					
					if (!alreadyExists && s.createButton) {
						// create it!
						controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>')
								.bind(
									'click',
									function()
									{
										$this.dpDisplay(this);
										this.blur();
										return false;
									}
								);
						$this.after(controller.button);
					}
					
					if (!alreadyExists && $this.is(':text')) {
						$this
							.bind(
								'dateSelected',
								function(e, selectedDate, $td)
								{
									this.value = selectedDate.asString();
								}
							).bind(
								'change',
								function()
								{
									if (this.value == '') {
										controller.clearSelected();
									} else {
										var d = Date.fromString(this.value);
										if (d) {
											controller.setSelected(d, true, true);
										}
									}
								}
							);
						if (s.clickInput) {
							$this.bind(
								'click',
								function()
								{
									// The change event doesn't happen until the input loses focus so we need to manually trigger it...
									$this.trigger('change');
									$this.dpDisplay();
								}
							);
						}
						var d = Date.fromString(this.value);
						if (this.value != '' && d) {
							controller.setSelected(d, true, true);
						}
					}
					
					$this.addClass('dp-applied');
					
				}
			)
		},
/**
 * Disables or enables this date picker
 *
 * @param Boolean s Whether to disable (true) or enable (false) this datePicker
 * @type $
 * @name dpSetDisabled
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetDisabled(true);
 * @desc Prevents this date picker from displaying and adds a class of dp-disabled to it (and it's associated button if it has one) for styling purposes. If the matched element is an input field then it will also set the disabled attribute to stop people directly editing the field.
 **/
		dpSetDisabled : function(s)
		{
			return _w.call(this, 'setDisabled', s);
		},
/**
 * Updates the first selectable date for any date pickers on any matched elements.
 *
 * @param String d A string representing the first selectable date (formatted according to Date.format).
 * @type $
 * @name dpSetStartDate
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetStartDate('01/01/2000');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the first selectable date for each of these to the first day of the millenium.
 **/
		dpSetStartDate : function(d)
		{
			return _w.call(this, 'setStartDate', d);
		},
/**
 * Updates the last selectable date for any date pickers on any matched elements.
 *
 * @param String d A string representing the last selectable date (formatted according to Date.format).
 * @type $
 * @name dpSetEndDate
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetEndDate('01/01/2010');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the last selectable date for each of these to the first Janurary 2010.
 **/
		dpSetEndDate : function(d)
		{
			return _w.call(this, 'setEndDate', d);
		},
/**
 * Gets a list of Dates currently selected by this datePicker. This will be an empty array if no dates are currently selected or NULL if there is no datePicker associated with the matched element.
 *
 * @type Array
 * @name dpGetSelected
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * alert($('.date-picker').dpGetSelected());
 * @desc Will alert an empty array (as nothing is selected yet)
 **/
		dpGetSelected : function()
		{
			var c = _getController(this[0]);
			if (c) {
				return c.getSelected();
			}
			return null;
		},
/**
 * Selects or deselects a date on any matched element's date pickers. Deselcting is only useful on date pickers where selectMultiple==true. Selecting will only work if the passed date is within the startDate and endDate boundries for a given date picker.
 *
 * @param String d A string representing the date you want to select (formatted according to Date.format).
 * @param Boolean v Whether you want to select (true) or deselect (false) this date. Optional - default = true.
 * @param Boolean m Whether you want the date picker to open up on the month of this date when it is next opened. Optional - default = true.
 * @param Boolean e Whether you want the date picker to dispatch events related to this change of selection. Optional - default = true.
 * @type $
 * @name dpSetSelected
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetSelected('01/01/2010');
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
 **/
		dpSetSelected : function(d, v, m, e)
		{
			if (v == undefined) v=true;
			if (m == undefined) m=true;
			if (e == undefined) e=true;
			return _w.call(this, 'setSelected', Date.fromString(d), v, m, e);
		},
/**
 * Sets the month that will be displayed when the date picker is next opened. If the passed month is before startDate then the month containing startDate will be displayed instead. If the passed month is after endDate then the month containing the endDate will be displayed instead.
 *
 * @param Number m The month you want the date picker to display. Optional - defaults to the currently displayed month.
 * @param Number y The year you want the date picker to display. Optional - defaults to the currently displayed year.
 * @type $
 * @name dpSetDisplayedMonth
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-picker').datePicker();
 * $('.date-picker').dpSetDisplayedMonth(10, 2008);
 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
 **/
		dpSetDisplayedMonth : function(m, y)
		{
			return _w.call(this, 'setDisplayedMonth', Number(m), Number(y), true);
		},
/**
 * Displays the date picker associated with the matched elements. Since only one date picker can be displayed at once then the date picker associated with the last matched element will be the one that is displayed.
 *
 * @param HTMLElement e An element that you want the date picker to pop up relative in position to. Optional - default behaviour is to pop up next to the element associated with this date picker.
 * @type $
 * @name dpDisplay
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpDisplay();
 * @desc Creates a date picker associated with the element with an id of date-picker and then causes it to pop up.
 **/
		dpDisplay : function(e)
		{
			return _w.call(this, 'display', e);
		},
/**
 * Sets a function or array of functions that is called when each TD of the date picker popup is rendered to the page
 *
 * @param (Function|Array) a A function or an array of functions that are called when each td is rendered. Each function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year.
 * @type $
 * @name dpSetRenderCallback
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetRenderCallback(function($td, thisDate, month, year)
 * {
 * 	// do stuff as each td is rendered dependant on the date in the td and the displayed month and year
 * });
 * @desc Creates a date picker associated with the element with an id of date-picker and then creates a function which is called as each td is rendered when this date picker is displayed.
 **/
		dpSetRenderCallback : function(a)
		{
			return _w.call(this, 'setRenderCallback', a);
		},
/**
 * Sets the position that the datePicker will pop up (relative to it's associated element)
 *
 * @param Number v The vertical alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM
 * @param Number h The horizontal alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT
 * @type $
 * @name dpSetPosition
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_RIGHT);
 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be bottom and right aligned to the #date-picker element.
 **/
		dpSetPosition : function(v, h)
		{
			return _w.call(this, 'setPosition', v, h);
		},
/**
 * Sets the offset that the popped up date picker will have from it's default position relative to it's associated element (as set by dpSetPosition)
 *
 * @param Number v The vertical offset of the created date picker.
 * @param Number h The horizontal offset of the created date picker.
 * @type $
 * @name dpSetOffset
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('#date-picker').datePicker();
 * $('#date-picker').dpSetOffset(-20, 200);
 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be 20 pixels above and 200 pixels to the right of it's default position.
 **/
		dpSetOffset : function(v, h)
		{
			return _w.call(this, 'setOffset', v, h);
		},
/**
 * Closes the open date picker associated with this element.
 *
 * @type $
 * @name dpClose
 * @cat plugins/datePicker
 * @author Kelvin Luck (http://www.kelvinluck.com/)
 *
 * @example $('.date-pick')
 *		.datePicker()
 *		.bind(
 *			'focus',
 *			function()
 *			{
 *				$(this).dpDisplay();
 *			}
 *		).bind(
 *			'blur',
 *			function()
 *			{
 *				$(this).dpClose();
 *			}
 *		);
 * @desc Creates a date picker and makes it appear when the relevant element is focused and disappear when it is blurred.
 **/
		dpClose : function()
		{
			return _w.call(this, '_closeCalendar', false, this[0]);
		},
		// private function called on unload to clean up any expandos etc and prevent memory links...
		_dpDestroy : function()
		{
			// TODO - implement this?
		}
	});
	
	// private internal function to cut down on the amount of code needed where we forward
	// dp* methods on the $ object on to the relevant DatePicker controllers...
	var _w = function(f, a1, a2, a3, a4)
	{
		return this.each(
			function()
			{
				var c = _getController(this);
				if (c) {
					c[f](a1, a2, a3, a4);
				}
			}
		);
	};
	
	function DatePicker(ele)
	{
		this.ele = ele;
		
		// initial values...
		this.displayedMonth		=	null;
		this.displayedYear		=	null;
		this.startDate			=	null;
		this.endDate			=	null;
		this.showYearNavigation	=	null;
		this.closeOnSelect		=	null;
		this.displayClose		=	null;
		this.rememberViewedMonth=	null;
		this.selectMultiple		=	null;
		this.numSelectable		=	null;
		this.numSelected		=	null;
		this.verticalPosition	=	null;
		this.horizontalPosition	=	null;
		this.verticalOffset		=	null;
		this.horizontalOffset	=	null;
		this.button				=	null;
		this.renderCallback		=	[];
		this.selectedDates		=	{};
		this.inline				=	null;
		this.context			=	'#dp-popup';
		this.settings			=	{};
	};
	$.extend(
		DatePicker.prototype,
		{	
			init : function(s)
			{
				this.setStartDate(s.startDate);
				this.setEndDate(s.endDate);
				this.setDisplayedMonth(Number(s.month), Number(s.year));
				this.setRenderCallback(s.renderCallback);
				this.showYearNavigation = s.showYearNavigation;
				this.closeOnSelect = s.closeOnSelect;
				this.displayClose = s.displayClose;
				this.rememberViewedMonth =	s.rememberViewedMonth;
				this.selectMultiple = s.selectMultiple;
				this.numSelectable = s.selectMultiple ? s.numSelectable : 1;
				this.numSelected = 0;
				this.verticalPosition = s.verticalPosition;
				this.horizontalPosition = s.horizontalPosition;
				this.hoverClass = s.hoverClass;
				this.setOffset(s.verticalOffset, s.horizontalOffset);
				this.inline = s.inline;
				this.settings = s;
				if (this.inline) {
					this.context = this.ele;
					this.display();
				}
			},
			setStartDate : function(d)
			{
				if (d) {
					this.startDate = Date.fromString(d);
				}
				if (!this.startDate) {
					this.startDate = (new Date()).zeroTime();
				}
				this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
			},
			setEndDate : function(d)
			{
				if (d) {
					this.endDate = Date.fromString(d);
				}
				if (!this.endDate) {
					this.endDate = (new Date('12/31/2999')); // using the JS Date.parse function which expects mm/dd/yyyy
				}
				if (this.endDate.getTime() < this.startDate.getTime()) {
					this.endDate = this.startDate;
				}
				this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
			},
			setPosition : function(v, h)
			{
				this.verticalPosition = v;
				this.horizontalPosition = h;
			},
			setOffset : function(v, h)
			{
				this.verticalOffset = parseInt(v) || 0;
				this.horizontalOffset = parseInt(h) || 0;
			},
			setDisabled : function(s)
			{
				$e = $(this.ele);
				$e[s ? 'addClass' : 'removeClass']('dp-disabled');
				if (this.button) {
					$but = $(this.button);
					$but[s ? 'addClass' : 'removeClass']('dp-disabled');
					$but.attr('title', s ? '' : $.dpText.TEXT_CHOOSE_DATE);
				}
				if ($e.is(':text')) {
					$e.attr('disabled', s ? 'disabled' : '');
				}
			},
			setDisplayedMonth : function(m, y, rerender)
			{
				if (this.startDate == undefined || this.endDate == undefined) {
					return;
				}
				var s = new Date(this.startDate.getTime());
				s.setDate(1);
				var e = new Date(this.endDate.getTime());
				e.setDate(1);
				
				var t;
				if ((!m && !y) || (isNaN(m) && isNaN(y))) {
					// no month or year passed - default to current month
					t = new Date().zeroTime();
					t.setDate(1);
				} else if (isNaN(m)) {
					// just year passed in - presume we want the displayedMonth
					t = new Date(y, this.displayedMonth, 1);
				} else if (isNaN(y)) {
					// just month passed in - presume we want the displayedYear
					t = new Date(this.displayedYear, m, 1);
				} else {
					// year and month passed in - that's the date we want!
					t = new Date(y, m, 1)
				}
				// check if the desired date is within the range of our defined startDate and endDate
				if (t.getTime() < s.getTime()) {
					t = s;
				} else if (t.getTime() > e.getTime()) {
					t = e;
				}
				var oldMonth = this.displayedMonth;
				var oldYear = this.displayedYear;
				this.displayedMonth = t.getMonth();
				this.displayedYear = t.getFullYear();

				if (rerender && (this.displayedMonth != oldMonth || this.displayedYear != oldYear))
				{
					this._rerenderCalendar();
					$(this.ele).trigger('dpMonthChanged', [this.displayedMonth, this.displayedYear]);
				}
			},
			setSelected : function(d, v, moveToMonth, dispatchEvents)
			{
				if (d < this.startDate || d > this.endDate) {
					// Don't allow people to select dates outside range...
					return;
				}
				var s = this.settings;
				if (s.selectWeek)
				{
					d = d.addDays(- (d.getDay() - Date.firstDayOfWeek + 7) % 7);
					if (d < this.startDate) // The first day of this week is before the start date so is unselectable...
					{
						return;
					}
				}
				if (v == this.isSelected(d)) // this date is already un/selected
				{
					return;
				}
				if (this.selectMultiple == false) {
					this.clearSelected();
				} else if (v && this.numSelected == this.numSelectable) {
					// can't select any more dates...
					return;
				}
				if (moveToMonth && (this.displayedMonth != d.getMonth() || this.displayedYear != d.getFullYear())) {
					this.setDisplayedMonth(d.getMonth(), d.getFullYear(), true);
				}
				this.selectedDates[d.toString()] = v;
				this.numSelected += v ? 1 : -1;
				var selectorString = 'td.' +( d.getMonth() == this.displayedMonth ? 'current-month' : 'other-month');
				var $td;
				$(selectorString, this.context).each(
					function()
					{
						if ($(this).data('datePickerDate') == d.asString()) {
							$td = $(this);
							if (s.selectWeek)
							{
								$td.parent()[v ? 'addClass' : 'removeClass']('selectedWeek');
							}
							$td[v ? 'addClass' : 'removeClass']('selected'); 
						}
					}
				);
				$('td', this.context).not('.selected')[this.selectMultiple &&	this.numSelected == this.numSelectable ? 'addClass' : 'removeClass']('unselectable');
				
				if (dispatchEvents)
				{
					var s = this.isSelected(d);
					$e = $(this.ele);
					var dClone = Date.fromString(d.asString());
					$e.trigger('dateSelected', [dClone, $td, s]);
					$e.trigger('change');
				}
			},
			isSelected : function(d)
			{
				return this.selectedDates[d.toString()];
			},
			getSelected : function()
			{
				var r = [];
				for(s in this.selectedDates) {
					if (this.selectedDates[s] == true) {
						r.push(Date.parse(s));
					}
				}
				return r;
			},
			clearSelected : function()
			{
				this.selectedDates = {};
				this.numSelected = 0;
				$('td.selected', this.context).removeClass('selected').parent().removeClass('selectedWeek');
			},
			display : function(eleAlignTo)
			{
				if ($(this.ele).is('.dp-disabled')) return;
				
				eleAlignTo = eleAlignTo || this.ele;
				var c = this;
				var $ele = $(eleAlignTo);
				var eleOffset = $ele.offset();
				
				var $createIn;
				var attrs;
				var attrsCalendarHolder;
				var cssRules;
				
				if (c.inline) {
					$createIn = $(this.ele);
					attrs = {
						'id'		:	'calendar-' + this.ele._dpId,
						'class'	:	'dp-popup dp-popup-inline'
					};

					$('.dp-popup', $createIn).remove();
					cssRules = {
					};
				} else {
					$createIn = $('body');
					attrs = {
						'id'		:	'dp-popup',
						'class'	:	'dp-popup'
					};
					cssRules = {
						'top'	:	eleOffset.top + c.verticalOffset,
						'left'	:	eleOffset.left + c.horizontalOffset
					};
					
					var _checkMouse = function(e)
					{
						var el = e.target;
						var cal = $('#dp-popup')[0];
						
						while (true){
							if (el == cal) {
								return true;
							} else if (el == document) {
								c._closeCalendar();
								return false;
							} else {
								el = $(el).parent()[0];
							}
						}
					};
					this._checkMouse = _checkMouse;
					
					c._closeCalendar(true);
					$(document).bind(
						'keydown.datepicker', 
						function(event)
						{
							if (event.keyCode == 27) {
								c._closeCalendar();
							}
						}
					);
				}
				
				if (!c.rememberViewedMonth)
				{
					var selectedDate = this.getSelected()[0];
					if (selectedDate) {
						selectedDate = new Date(selectedDate);
						this.setDisplayedMonth(selectedDate.getMonth(), selectedDate.getFullYear(), false);
					}
				}
				
				$createIn
					.append(
						$('<div></div>')
							.attr(attrs)
							.css(cssRules)
							.append(
//								$('<a href="#" class="selecteee">aaa</a>'),
								$('<h2></h2>'),
								$('<div class="dp-nav-prev"></div>')
									.append(
										$('<a class="dp-nav-prev-year" href="#" title="' + $.dpText.TEXT_PREV_YEAR + '">&lt;&lt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, 0, -1);
												}
											),
										$('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '">&lt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, -1, 0);
												}
											)
									),
								$('<div class="dp-nav-next"></div>')
									.append(
										$('<a class="dp-nav-next-year" href="#" title="' + $.dpText.TEXT_NEXT_YEAR + '">&gt;&gt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, 0, 1);
												}
											),
										$('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '">&gt;</a>')
											.bind(
												'click',
												function()
												{
													return c._displayNewMonth.call(c, this, 1, 0);
												}
											)
									),
								$('<div class="dp-calendar"></div>')
							)
							.bgIframe()
						);
					
				var $pop = this.inline ? $('.dp-popup', this.context) : $('#dp-popup');
				
				if (this.showYearNavigation == false) {
					$('.dp-nav-prev-year, .dp-nav-next-year', c.context).css('display', 'none');
				}
				if (this.displayClose) {
					$pop.append(
						$('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>')
							.bind(
								'click',
								function()
								{
									c._closeCalendar();
									return false;
								}
							)
					);
				}
				c._renderCalendar();

				$(this.ele).trigger('dpDisplayed', $pop);
				
				if (!c.inline) {
					if (this.verticalPosition == $.dpConst.POS_BOTTOM) {
						$pop.css('top', eleOffset.top + $ele.height() - $pop.height() + c.verticalOffset);
					}
					if (this.horizontalPosition == $.dpConst.POS_RIGHT) {
						$pop.css('left', eleOffset.left + $ele.width() - $pop.width() + c.horizontalOffset);
					}
//					$('.selectee', this.context).focus();
					$(document).bind('mousedown.datepicker', this._checkMouse);
				}
				
			},
			setRenderCallback : function(a)
			{
				if (a == null) return;
				if (a && typeof(a) == 'function') {
					a = [a];
				}
				this.renderCallback = this.renderCallback.concat(a);
			},
			cellRender : function ($td, thisDate, month, year) {
				var c = this.dpController;
				var d = new Date(thisDate.getTime());
				
				// add our click handlers to deal with it when the days are clicked...
				
				$td.bind(
					'click',
					function()
					{
						var $this = $(this);
						if (!$this.is('.disabled')) {
							c.setSelected(d, !$this.is('.selected') || !c.selectMultiple, false, true);
							if (c.closeOnSelect) {
								c._closeCalendar();
							}
							// TODO: Instead of this which doesn't work in IE anyway we should find the next focusable element in the document
							// and pass the focus onto that. That would allow the user to continue on the form as expected...
							if (!$.browser.msie)
							{
								$(c.ele).trigger('focus', [$.dpConst.DP_INTERNAL_FOCUS]);
							}
						}
					}
				);
				
				if (c.isSelected(d)) {
					$td.addClass('selected');
					if (c.settings.selectWeek)
					{
						$td.parent().addClass('selectedWeek');
					}
				} else	if (c.selectMultiple && c.numSelected == c.numSelectable) {
					$td.addClass('unselectable');
				}
				
			},
			_applyRenderCallbacks : function()
			{
				var c = this;
				$('td', this.context).each(
					function()
					{
						for (var i=0; i<c.renderCallback.length; i++) {
							$td = $(this);
							c.renderCallback[i].apply(this, [$td, Date.fromString($td.data('datePickerDate')), c.displayedMonth, c.displayedYear]);
						}
					}
				);
				return;
			},
			// ele is the clicked button - only proceed if it doesn't have the class disabled...
			// m and y are -1, 0 or 1 depending which direction we want to go in...
			_displayNewMonth : function(ele, m, y) 
			{
				if (!$(ele).is('.disabled')) {
					this.setDisplayedMonth(this.displayedMonth + m, this.displayedYear + y, true);
				}
				ele.blur();
				return false;
			},
			_rerenderCalendar : function()
			{
				this._clearCalendar();
				this._renderCalendar();
			},
			_renderCalendar : function()
			{
				// set the title...
				$('h2', this.context).html((new Date(this.displayedYear, this.displayedMonth, 1)).asString($.dpText.HEADER_FORMAT));
				
				// render the calendar...
				$('.dp-calendar', this.context).renderCalendar(
					$.extend(
						{},
						this.settings, 
						{
							month			: this.displayedMonth,
							year			: this.displayedYear,
							renderCallback	: this.cellRender,
							dpController	: this,
							hoverClass		: this.hoverClass
						})
				);
				
				// update the status of the control buttons and disable dates before startDate or after endDate...
				// TODO: When should the year buttons be disabled? When you can't go forward a whole year from where you are or is that annoying?
				if (this.displayedYear == this.startDate.getFullYear() && this.displayedMonth == this.startDate.getMonth()) {
					$('.dp-nav-prev-year', this.context).addClass('disabled');
					$('.dp-nav-prev-month', this.context).addClass('disabled');
					$('.dp-calendar td.other-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) > 20) {
								$this.addClass('disabled');
							}
						}
					);
					var d = this.startDate.getDate();
					$('.dp-calendar td.current-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) < d) {
								$this.addClass('disabled');
							}
						}
					);
				} else {
					$('.dp-nav-prev-year', this.context).removeClass('disabled');
					$('.dp-nav-prev-month', this.context).removeClass('disabled');
					var d = this.startDate.getDate();
					if (d > 20) {
						// check if the startDate is last month as we might need to add some disabled classes...
						var st = this.startDate.getTime();
						var sd = new Date(st);
						sd.addMonths(1);
						if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) {
							$('.dp-calendar td.other-month', this.context).each(
								function()
								{
									var $this = $(this);
									if (Date.fromString($this.data('datePickerDate')).getTime() < st) {
										$this.addClass('disabled');
									}
								}
							);
						}
					}
				}
				if (this.displayedYear == this.endDate.getFullYear() && this.displayedMonth == this.endDate.getMonth()) {
					$('.dp-nav-next-year', this.context).addClass('disabled');
					$('.dp-nav-next-month', this.context).addClass('disabled');
					$('.dp-calendar td.other-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) < 14) {
								$this.addClass('disabled');
							}
						}
					);
					var d = this.endDate.getDate();
					$('.dp-calendar td.current-month', this.context).each(
						function()
						{
							var $this = $(this);
							if (Number($this.text()) > d) {
								$this.addClass('disabled');
							}
						}
					);
				} else {
					$('.dp-nav-next-year', this.context).removeClass('disabled');
					$('.dp-nav-next-month', this.context).removeClass('disabled');
					var d = this.endDate.getDate();
					if (d < 13) {
						// check if the endDate is next month as we might need to add some disabled classes...
						var ed = new Date(this.endDate.getTime());
						ed.addMonths(-1);
						if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) {
							$('.dp-calendar td.other-month', this.context).each(
								function()
								{
									var $this = $(this);
									if (Number($this.text()) > d) {
										$this.addClass('disabled');
									}
								}
							);
						}
					}
				}
				this._applyRenderCallbacks();
			},
			_closeCalendar : function(programatic, ele)
			{
				if (!ele || ele == this.ele)
				{
					$(document).unbind('mousedown.datepicker');
					$(document).unbind('keydown.datepicker');
					this._clearCalendar();
					$('#dp-popup a').unbind();
					$('#dp-popup').empty().remove();
					if (!programatic) {
						$(this.ele).trigger('dpClosed', [this.getSelected()]);
					}
				}
			},
			// empties the current dp-calendar div and makes sure that all events are unbound
			// and expandos removed to avoid memory leaks...
			_clearCalendar : function()
			{
				// TODO.
				$('.dp-calendar td', this.context).unbind();
				$('.dp-calendar', this.context).empty();
			}
		}
	);
	
	// static constants
	$.dpConst = {
		SHOW_HEADER_NONE	:	0,
		SHOW_HEADER_SHORT	:	1,
		SHOW_HEADER_LONG	:	2,
		POS_TOP				:	0,
		POS_BOTTOM			:	1,
		POS_LEFT			:	0,
		POS_RIGHT			:	1,
		DP_INTERNAL_FOCUS	:	'dpInternalFocusTrigger'
	};
	// localisable text
	$.dpText = {
		TEXT_PREV_YEAR		:	'Previous year',
		TEXT_PREV_MONTH		:	'Previous month',
		TEXT_NEXT_YEAR		:	'Next year',
		TEXT_NEXT_MONTH		:	'Next month',
		TEXT_CLOSE			:	'Close',
		TEXT_CHOOSE_DATE	:	'Choose date',
		HEADER_FORMAT		:	'mmmm yyyy'
	};
	// version
	$.dpVersion = '$Id: jquery.datePicker.js 70 2009-04-05 19:25:15Z kelvin.luck $';

	$.fn.datePicker.defaults = {
		month				: undefined,
		year				: undefined,
		showHeader			: $.dpConst.SHOW_HEADER_SHORT,
		startDate			: undefined,
		endDate				: undefined,
		inline				: false,
		renderCallback		: null,
		createButton		: true,
		showYearNavigation	: true,
		closeOnSelect		: true,
		displayClose		: false,
		selectMultiple		: false,
		numSelectable		: Number.MAX_VALUE,
		clickInput			: false,
		rememberViewedMonth	: true,
		selectWeek			: false,
		verticalPosition	: $.dpConst.POS_TOP,
		horizontalPosition	: $.dpConst.POS_LEFT,
		verticalOffset		: 0,
		horizontalOffset	: 0,
		hoverClass			: 'dp-hover'
	};

	function _getController(ele)
	{
		if (ele._dpId) return $.event._dpCache[ele._dpId];
		return false;
	};
	
	// make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional
	// comments to only include bgIframe where it is needed in IE without breaking this plugin).
	if ($.fn.bgIframe == undefined) {
		$.fn.bgIframe = function() {return this; };
	};


	// clean-up
	$(window)
		.bind('unload', function() {
			var els = $.event._dpCache || [];
			for (var i in els) {
				$(els[i].ele)._dpDestroy();
			}
		});
})(jQuery);
//}}}
<<newTiddler>><<newTiddler tag:excludeTree label:"new note" title:"New Note">>{{button{[[Upload|Uploader]]}}}  <<permaview>><<closeAll>>
/*!
|''Name''|notabene|
|''Version''|0.6.4|
|''License''|BSD (http://en.wikipedia.org/wiki/BSD_licenses)|
|''Source''|https://github.com/jdlrobson/notabene/blob/master/src/notabene.js|
!*/
var APP_PATH = "/takenote";
var RESERVED_TITLES = ["takenote", "dashboard", "manifest.mf",
	"notabene.css", "jquery-ui.min.js", "jquery-json.min.js"];

var config;

// some helper functions
var notabene = {
	defaultFields: {},
	loadConfig: function() {
		config = localStorage.getItem("_takeNoteConfig") ? JSON.parse(localStorage.getItem("_takeNoteConfig")) : {};
		if(config.noGeoTiddlers) {
			if(new Date().getTime() - config.noGeoTiddlers > 1000*60*60*24) {
				// more than a day old so flush
				notabene.saveConfig("noGeoTiddlers", false);
			}
		}
	},
	saveConfig: function(name, value) {
		if(typeof(name) != "undefined" && typeof(value) != "undefined") {
			config[name] = value;
		}
		localStorage.setItem("_takeNoteConfig", JSON.stringify(config));
	},
	watchPosition: function(handler) {
		if(!!navigator.geolocation && !config.noGeoTiddlers) {
			navigator.geolocation.watchPosition(handler, function() {
				notabene.saveConfig("noGeoTiddlers", new Date().getTime());
			});
		}
	},
	supports_local_storage: function() {
		try {
			return 'localStorage' in window && window['localStorage'] !== null;
		} catch(e) {
			return false;
		}
	},
	getRecentChanges: function(bag) {
		var recentLocalStorageId = "takenote-recent-" + bag;
		var recent = localStorage.getItem(recentLocalStorageId);
		recent = recent ? $.parseJSON(recent) : [];
		return recent;
	},
	addRecentChange: function(bag, title) {
		var recent = notabene.getRecentChanges(bag);
		var newrecent = [];
		for(var i = 0; i < recent.length; i++) {
			var thisTitle = typeof(recent[i]) === "string" ? recent[i] : recent[i].title;
			if(thisTitle !== title) {
				newrecent.push(recent[i]);
			}
		}
		newrecent.push({ title: title, bag: bag });
		newrecent = newrecent.length > 5 ?
			newrecent.slice(newrecent.length - 5) : newrecent;
		localStorage.setItem("takenote-recent-" + bag, $.toJSON(newrecent));
	}
};
notabene.loadConfig();

function autoResize(el, options) {
	options = options || {};
	var resize = function(ev) {
		el = ev.target;
		var div = $('<div />').addClass($(el).attr("class")).hide().
			css({ "word-wrap": "break-word" }).insertBefore($(el)[0]);
		var value = $(el).val() || "";
		var lines = value.split("\n");
		for(var i = 0; i < lines.length; i++) {
			$("<span />").text(lines[i]).appendTo(div);
			$("<br />").appendTo(div);
		}
		var h = $(div).height();
		if(options.minHeight && h < options.minHeight) {
			h = options.minHeight;
		}
		if(options.buffer) {
			h += options.buffer;
		}
		$(ev.target).height(h);
		$(div).remove();
	};
	$(el).focus(resize).keyup(resize).blur(resize);
	$(el).focus();
}


function setup_store(options) {
	// configure notabene
	options = options || {};
	var bagname = options.bag;
	var host = options.host;
	var bag = new tiddlyweb.Bag(bagname, host);
	var store =  new tiddlyweb.Store();

	// retrieve last created note
	store.retrieveCached();
	return {
		store: store,
		bag: bag,
		host: host
	}
}

function notes(container, options) {
	backstage();

	// setup onleave event
	window.onbeforeunload = function() {
		// TODO: chrjs.store should probably provide a helper method for this situation
		if(!notabene.supports_local_storage() && store().dirty().length) {
	  	return ["There are unsynced changes. Are you sure you want to leave?\n\n",
				"Please upgrade your browser if possible to make sure you never lose a note."
				].join("");
		}
	}
	var instance = setup_store(options);
	var store = instance.store;
	var bag = instance.bag;
	var host = instance.host;
	var tiddlers = store().sort(function(a, b) {
		return a.fields._modified < b.fields._modified ? 1 : -1;
	});
	var note, tempTitle;

	// print the fields associated with the current note
	function printMetaData(tiddler) {
		// print meta information
		var fieldInfo = {
			_created: { label: "created on" },
			_modified: { label: "last modified on" }
		};
		$("#notemeta").empty();
		var container = $('<div class="paddedbox" />').appendTo("#notemeta")[0];
		var list = $("<ul />").appendTo(container)[0];
		for(var fieldname in tiddler.fields) {
			if(fieldname.indexOf("_") !== 0) {
				var val = tiddler.fields[fieldname];
				if(val) {
					var label = fieldInfo[fieldname] ? fieldInfo[fieldname].label : fieldname;
					$("<li />").text(label + ": " + val).appendTo(list);
				}
			}
		}
		var tags = tiddler.tags || [];
		if(tags.length > 0) {
			var tagArea = $("<li />").appendTo(list);
			$("<span />").text("tags : ").appendTo(tagArea);
			for(var i = 0; i < tags.length; i++) {
				$("<span />").text(tags[i]).appendTo(tagArea);
				$('<a class="removeTag">remove</a>').data("tag", tags[i]).click(function(ev) {
					var tag = $(ev.target).data("tag");
					removeTag(tag);
					storeNote();
					ev.preventDefault();
				}).appendTo(tagArea);
			}
		}
	}

	// load the current note into the display
	function loadNote() {
		$(".note_text").val(note.text);
		if(note.title != tempTitle && note.fields._title_set) {
			$(".note_title").val(note.title);
		}
		if(note.fields._title_validated) {
			$(".note_title").blur().attr("disabled", true);
			$(document.body).addClass("validatedNote");
		} else {
			$(document.body).removeClass("validatedNote");
		}

		printMetaData(note);

		notabene.watchPosition(function(data) {
			// if note has existing geo data exit to prevent overwriting
			if(note.fields['geo.lat'] && note.fields['geo.long']) {
				return;
			}
			if(data) {
				var coords = data.coords;
				note.fields['geo.lat'] = String(coords.latitude);
				note.fields['geo.long'] = String(coords.longitude);
			}
		});
	}

	function getTitle() {
		return "untitled note " + Math.random();
	}

	// creates a new note with a randomly generated title and loads it into the ui
	function newNote() {
		tempTitle = getTitle();
		note = new tiddlyweb.Tiddler(tempTitle, bag);
		note.fields = {};
		note.tags = [];
		note.fields._created = new Date();
		loadNote();
	}

	// prints a message to the user. This could be an error or a notification.
	function printMessage(html, className, fadeout) {
		var area = $(".messageArea", container);
		area = area.length > 0 ? area : $("<div class='messageArea' />").appendTo(container);
		area.attr("class", "messageArea displayed").html("<div>" + html + "</div>");
		$(".messageArea div").stop(false, false).show();
		if(fadeout) {
			$(".messageArea div").css({ opacity: 1 }).fadeOut(3000);
		}
		if(className) {
			$(area).addClass(className);
		}
	}

	// tell the user what the current state of the store is
	function syncStatus() {
		var area = $(".syncButton");
		var unsynced = store().dirty();
		$(area).text(unsynced.length);
		renderIncomplete(store, bag.name);
	}

	// this loads the note with the given title from the active bag and loads it into the display
	function loadServerNote(title, bagname) {
		note = new tiddlyweb.Tiddler(title);
		note.fields = {};
		note.bag = new tiddlyweb.Bag(bagname || bag.name, host);
		store.get(note, function(tid, msg, xhr) {
			var is404 = xhr ? xhr.status === 404 : false;
			if(tid) {
				delete tid.fields.created;
				delete tid.fields.modified;
				note = tid;
			} else if(!is404) {
				resetNote();
			}
			// TODO: replace with chrjs-store method i.e. store.isPresent(tid)
			if(!localStorage.getItem(bag.name + "/" + encodeURIComponent(note.title))) {
				if(is404 || tid) {
					note.fields._title_validated = "yes";
				}
			}
			if(is404 || tid) {
				note.fields._title_set = "yes";
			}
			$(container).addClass("ready");
			loadNote();
		});
	}

	// this initialises notabene, loading either the requested note, the last worked on note or a new note
	function init() {
		var syncButton = $(".syncButton");
		syncButton = syncButton.length > 0 ? syncButton :
			$("<div class='syncButton' />").prependTo(container);
		syncStatus();
		syncButton.click(function(ev) {
			var error, synced = 0, invalid = [];
			var dirty = store().dirty();

			printMessage("Syncing to server");
			var giveFeedback = function(tid) {
				if(tid) {
					notabene.addRecentChange(tid.bag.name, tid.title);
				}
				if(synced === 0) {
					if(dirty.length > 0) {
						printMessage("Finish your note '" + note.title + "' before syncing.", "warning");
					} else {
						printMessage("Nothing to sync.", "warning");
					}
				} else {
					if(invalid.length > 0) {
						printMessage("Sync failed. Please rename some of your notes.", "error");
					} else if(tid && !error) {
						printMessage("Sync completed.", "", true);
					} else {
						error = true;
						printMessage("Unable to fully sync at current time.", "warning");
					}
				}
				syncStatus();
			};
			var currentNote = $(".note_title").val();
			dirty.each(function(tid) {
				if(tid.title !== currentNote) {
					synced += 1;
					validateNote(tid, function(newtid, isValid) {
						if(isValid) {
							store.save(newtid, giveFeedback);
						} else {
							invalid.push(newtid);
							giveFeedback(false);
						}
					});
				} else {
					giveFeedback(false);
				}
			});
		});
		var currentUrl = decodeURIComponent(window.location.hash);
		var match = currentUrl.match(/tiddler\/([^\/]*)$/);
		if(match && match[1]) {
			var matchbag = currentUrl.match(/bags\/([^\/]*)\//);
			var noteBag = matchbag && matchbag[1] ? matchbag[1] : undefined;
			if(currentUrl.indexOf("quickedit/") > -1) {
				$("#newnote").addClass("quickedit");
			}
			loadServerNote(match[1], noteBag);
		} else {
			if(tiddlers[0]) {
				note = tiddlers[0];
				loadNote();
			} else {
				newNote();
			}
			$(container).addClass("ready");
		}
	}

	// this stores the note locally (but not on the server)
	function isEmpty(note) {
		var emptyText = !note.text ? true : false;
		var noTitle = note.fields && note.fields._title_set ? false : true;
		return noTitle && emptyText ? true: false;
	}

	function storeNote() {
		note.fields._modified = new Date();
		if(!isEmpty(note)) {
			store.add(note);
		}
		syncStatus();
	}

	function renameNote(newtitle) {
		var old = note.title;
		if(newtitle !== old && !isEmpty(note)) {
			note.title = newtitle;
			store.add(note);
			store.remove(new tiddlyweb.Tiddler(old, bag));
		}
	}

	/* the callback is passed true if the title is unique on the server,
	false if the title already exists and null if it is not known */
	function validateNote(tiddler, callback) {
		var tid = new tiddlyweb.Tiddler(tiddler.title, bag);
		if(RESERVED_TITLES.indexOf(tiddler.title) > -1) {
			callback(tiddler, false, true);
		} else if(tiddler.fields._title_validated) {
			callback(tiddler, true);
		} else {
			tid.get(function() {
				callback(tiddler, false);
			}, function(xhr) {
				if(xhr.status == 404) {
					tiddler.fields._title_validated = "yes";
					callback(tiddler, true);
				} else {
					callback(tiddler, null, null, xhr);
				}
			});
		}
	}

	var renaming;
	function validateCurrentNoteTitle(title, callback) {
		callback = callback || function() {};
		var fixTitle = function() {
			if(renaming) {
				printMessage("Note title set.", "", true);
				renaming = false;
			}
			$(".note_title").attr("disabled", true);
		};

		validateNote(note, function(tiddler, valid, reserved, xhr) {
			//note = tiddler;
			if(valid) {
				fixTitle();
			} else if(valid === false) {
				renaming = true;
				var msg = reserved ? "This name is reserved and cannot be used. Please provide another."
					: "A note with this name already exists. Please provide another name."
				printMessage(msg, "error");
			}
			callback(valid, xhr);
		});
	}

	$(document).ready(function() {
	autoResize($("textarea.note_title")[0], { buffer: 0 });
	autoResize($(".note_text")[0], { minHeight: 250 });

	// on a blur event fix the title.
	$(".note_title").blur(function(ev){
		var val = $(ev.target).val();
		var trimmed = $.trim(val);
		if(trimmed.length > 0) {
			note.fields._title_set = "yes";
			renameNote(trimmed);
			storeNote();
		} else {
			delete note.fields._title_set;
			renameNote(getTitle());
		}
	}).keydown(function(ev) {
		if(ev.keyCode === 13) {
			ev.preventDefault();
		}
	});
	});

	function removeTag(tag) {
		var tags = note.tags || [];
		var newtags = [];
		for(var i = 0; i < tags.length; i++) {
			if(tags[i] !== tag) {
				newtags.push(tags[i]);
			}
		}
		note.tags = newtags;
		printMetaData(note);
	}
	function addTagToCurrentNote(tag) {
		var tags = note.tags || [];
		tag = tag.toLowerCase();
		if(tags.indexOf(tag) === -1) {
			tags.push(tag);
		}
		note.tags = tags;
		printMetaData(note);
	}
	function findTags(note) {
		var tags = note.text.match(/#([^ \n#]+)/gi);
		var unique = [];
		for(var i = 0; i < tags.length; i++) {
			var tag = tags[i].substr(1);
			if(unique.indexOf(tag) === -1) {
				unique.push(tag);
			}
		}
		return unique;
	}
	function addTags() {
		var newtags = findTags(note);
		for(var i = 0; i < newtags.length; i++) {
			addTagToCurrentNote(newtags[i]);
		}
	}
	// every key press triggers a 'local' save
	var tag = [];
	var tagHandler = function(key) {
		if(key === 8) {
			tag.pop();
		} else if(key === 32 || key === 13) { // space or new line terminates tag
			if(tag.length > 1) {
				addTags();
			}
			tag = [];
		} else if(key === 35) { // hash symbol
			if(tag.length > 1) {
				addTags();
				tag = ["#"];
			} else {
				tag = ["#"];
			}
		} else if(tag.length > 0) {
			tag.push(String.fromCharCode(key));
		}
	};

	$(".note_text").keydown(function(ev) {
		note.text = $(ev.target).val();
		if(ev.keyCode === 8) {
			tagHandler(ev.keyCode);
		}
		storeNote();
	}).keypress(function(ev) {
		note.text = $(ev.target).val();
		tagHandler(ev.keyCode);
	}).keyup(function(ev) {
		note.text = $(ev.target).val();
		storeNote();
	}).blur(function(ev) {
		if(tag.length > 0) {
			addTags();
		}
		tag = [];
	}).click(function(ev) {
		tag = [];
	}).focus(function(ev) {
		tag = [];
	});

	function resetNote() {
		$("#note").removeClass("active");
		$(".note_title, .note_text").val("").attr("disabled", false);

		// reset url
		window.location.hash = "";
		newNote();
		syncStatus();
	}

	// on clicking the "clear" button provide a blank note
	$("#newnote").click(function(ev) {
		printMessage("Saving note...");
		var quickedit = $(ev.target).hasClass("quickedit");

		validateCurrentNoteTitle(note.title, function(valid, xhr) {
			if(valid) {
				store.save(note, function(tid, options) {
					if(tid) {
						notabene.addRecentChange(tid.bag.name, note.title);
						$("#note").addClass("active");
						if(quickedit) { // if quick edit has been signalled
							window.location = "/" + encodeURIComponent(note.title);
						} else {
							printMessage("Saved successfully.", null, true);
						}
						resetNote();
					} else {
						// TODO: give more useful error messages (currently options doesn't provide this)
						if(xhr && xhr.status === 403) {
							printMessage("You are not logged into takenote." +
								"Please <a href='/challenge'>login</a> to post notes to the web.", "warning");
						} else {
							printMessage("Saved locally. Unable to post to web at current time.", "warning");
						}
						resetNote();
					}
				});
			} else if(valid == null) {
				printMessage("Saved locally. Unable to post to web at current time.", "warning");
				resetNote();
			}
		});
	});

	//tie delete button to delete event
	$("#deletenote").click(function(ev) {
		var ok = confirm("Delete this note?");
		if(!ok) {
			return;
		}
		printMessage("Deleting note...");
		if(note) {
			var _server = note.fields._title_validated ? true : false;
			store.remove({ tiddler: note, server: _server }, function(tid, msg, xhr) {
				syncStatus();
				if(xhr && xhr.status === 0) {
					printMessage("Could not delete from server at current time.", "warning", true);
					storeNote();
					resetNote();
				} else if(tid) {
					$("#note").addClass("deleting");
					printMessage("Note deleted.", null, true);
					$("#note").removeClass("deleting");
					$(".note_title, .note_text").val("").attr("disabled", false);
					resetNote();
				} else {
					printMessage("Error deleting note. Please try again.", "error");
				}
			}); // TODO: ideally I would like to call store.removeTiddler(note) and not worry about syncing
		}
	});
	$("#cancelnote").click(function(ev) {
		var ok = confirm("Cancel editing this note and revert to previous online version?");
		if(ok) {
			store.remove(note.title);
			resetNote();
		}
	});
	init();
	return {
		init: init,
		resetNote: resetNote,
		findTags: findTags,
		tagHandler: tagHandler,
		printMessage: printMessage,
		newNote: newNote,
		loadNote: loadNote,
		addTag: addTagToCurrentNote,
		removeTag: removeTag,
		store: store,
		printMetaData: printMetaData,
		validateCurrentNoteTitle: validateCurrentNoteTitle,
		getNote: function() {
			return note;
		},
		tempTitle: tempTitle,
		loadServerNote: loadServerNote
	};
}

function backstage() {
	var internet, _checking, initialised;
	function checkConnection() {
		if(_checking) {
			return;
		} else {
			_checking = true;
			$.ajax({ url: "/status",
				success: function(status) {
					internet = true;
					_checking = false;
					$("body").addClass("online");
					if(!initialised) {
						initialised = true;
					}
				},
				error: function() {
					internet = false;
					_checking = false;
					$("body").removeClass("online");
				}
			});
		}
	}
	checkConnection();
	window.setInterval(checkConnection, 60000);
}

function renderIncomplete(store, bagname) {
	var tiddlers = store().dirty().sort(function(a, b) {
		return a.title < b.title ? -1 : 1;
	});
	var listIncomplete = $("#incomplete").empty()[0];
	if(listIncomplete) {
		for(var i = 0; i < tiddlers.length; i++) {
			var item = $("<li />").appendTo(listIncomplete)[0];
			var title = tiddlers[i].title;
			$("<a />").attr("href", APP_PATH + "#!/tiddler/" + title).
				text(title).appendTo(item);
		}
		if(tiddlers.length === 0) {
			$("<li />").text("None.").appendTo(listIncomplete)[0];
		}
	}
}

function dashboard(container, options) {
	notes(container, options);

	var list = $("#recentnotes");

	if(list.length > 0) {
		var sortRecent = function(a, b) {
			var title1 = typeof(a) === "string" ? a : a.title;
			var title2 = typeof(b) === "string" ? b : b.title;
			return title1 < title2 ? -1 : 1;
		};
		var recent = options.space ? notabene.getRecentChanges(options.space + "_private").
			concat(notabene.getRecentChanges(options.space + "_public")) :
			notabene.getRecentChanges(options.bag);
		function printRecentItems(recent) {
			if(recent.length === 0) {
				$("<li />").text("No recently created notes.").appendTo(list)[0];
			}
			for(var i = 0; i < recent.length; i++) {
				var li = $("<li />").appendTo(list)[0];
				var tid = recent[i];
				if(typeof(tid) === "string") {
					tid = { title: tid };
				}
				var bag = tid.bag || options.bag;
				$("<a />").attr("href",
					"/bags/" + bag + "/tiddlers/" + encodeURIComponent(tid.title)).
					text(tid.title).appendTo(li);
			}
		}
		printRecentItems(recent.sort(sortRecent));
	}

	var throbspeed = 500;
	var throb = window.setInterval(function() {
		var searching = $(".searching");
		if(searching.length > 0) {
			var opacity = searching.css("opacity");
			opacity = opacity ? parseFloat(opacity, 10) : 1;
			if(opacity > 0.7) {
				searching.animate({ opacity: 0.6 }, throbspeed)
			} else {
				searching.animate({ opacity: 1 }, throbspeed)
			}
		}
	}, throbspeed);

	var terms = {}, all_note_titles = [];
	// preload titles
	$.ajax({
		dataType: "text",
		url: "/bags/" + options.bag + "/tiddlers?select=tag:!excludeLists",
		success: function(r) {
			all_note_titles = r.split("\n");
		}
	});

	function matchNotes(term, exclude) {
		term = term.toLowerCase();
		var results = [];
		for(var i = 0; i < all_note_titles.length; i++) {
			var title = all_note_titles[i];
			if(title.toLowerCase().indexOf(term) > -1 && exclude.indexOf(title) === -1) {
				results.push({ value: title, label: title, bag: options.bag });
			}
		}
		return results;
	}

	// allow user to search for a tiddler
	$(".findnote").autocomplete({
		source: function(req, response) {
			var el = $(this.element);
			el.addClass("searching");
			var term = req.term;
			if(terms[term]) {
				return response(terms[term]);
			}
			response(matchNotes(term, []));
			$.ajax({
				url: "/search?q=bag:" + options.bag + " \"" + term + " \"&select=tag:!excludeLists",
				dataType: "json",
				success: function(r) {
					el.removeClass("searching").css({ opacity: 1 });
					var data = [];
					var exclude = [];
					for(var i = 0; i < r.length; i++) {
						var tiddler = r[i];
						var bag = tiddler.bag;
						var space = bag.split("_");
						var spacename = space[0];
						var spacetype = space[1];
						var type = tiddler.type;
						exclude.push(tiddler.title);
						if(!type) { // only push "tiddlers" without a type
							data.push({ value: tiddler.title, label: tiddler.title, bag: tiddler.bag })
						}
					}
					data = data.concat(matchNotes(term, exclude));
					if(data.length === 0) {
						data.push({ label: "No notes found" });
					}
					terms[term] = data;
					response(data);
				},
				error: function() {
					var data = [];
					data.concat(matchNotes(term, []));
					if(data.length === 0) {
						data.push({ label: "Unable to search at current time" });
					}
					el.removeClass("searching").css({ opacity: 1 });
					response(data);
				}
			});
		},
		select: function(event, ui) {
			if(ui.item.value && ui.item.bag) {
				window.location = "/bags/" + ui.item.bag + "/tiddlers/" + encodeURIComponent(ui.item.value);
			}
		}
	});

	// TODO: refactor - some of this code is a repeat of that in the notes function
	var instance = setup_store(options);
	renderIncomplete(instance.store, instance.bag.name);
}

// show bookmark bubble if supported
window.addEventListener('load', function() {
	window.setTimeout(function() {
		var bubble = new google.bookmarkbubble.Bubble();

		var BUBBLE_STORAGE_KEY = 'bubble';

		bubble.setHashParameter = function() {
			localStorage.setItem(BUBBLE_STORAGE_KEY, "yes");
		};

		bubble.hasHashParameter = function() {
			return localStorage.getItem(BUBBLE_STORAGE_KEY) ? true : false;
		};

		bubble.getViewportHeight = function() {
			return window.innerHeight;
		};

		bubble.getViewportScrollY = function() {
			return window.pageYOffset;
		};

		bubble.registerScrollHandler = function(handler) {
			window.addEventListener('scroll', handler, false);
		};

		bubble.deregisterScrollHandler = function(handler) {
			window.removeEventListener('scroll', handler, false);
		};

		bubble.showIfAllowed();
	}, 1000);
}, false);

addEventListener("load", function() {
	setTimeout(hideURLbar, 0);
}, false);

function hideURLbar() {
	window.scrollTo(0, 1);
}
<html>
<head>
  <title>nearby tiddlers</title>
  <link href="/bags/common/tiddlers/profile.css" type='text/css' rel='stylesheet' >
  <link href="/jquery-ui.css" type='text/css' rel='stylesheet' >
</style>
	<script type="text/javascript" src="/bags/common/tiddlers/backstage.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<h1>nearby tiddlers</h1>
</div>
<h2>Tiddlers recently created near you</h2>
Tiddlers that are geotagged and near your current location (within <span id="radius">1</span>km <button id="radius-increase">+</button>, <button id="radius-decrease">-</button>) are listed below.
<ul id="near"></ul>
</div>
<script type='text/javascript' src='/bags/common/tiddlers/jquery.js'></script>
<script type='text/javascript' src='http://htmljs.tiddlyspace.com/htmljs-prettydates'></script>
<script type='text/javascript' src='/bags/common/tiddlers/jquery-json.js'></script>
<script type='text/javascript' src='/bags/tiddlyspace/tiddlers/chrjs'></script>
<script type="text/javascript">
$("#radius-increase").click(function(ev) {
	$("#radius").text(parseInt($("#radius").text(), 10) + 1);
	check();
});
$("#radius-decrease").click(function(ev) {
	var newRadius = parseInt($("#radius").text(), 10) - 1;
	if(newRadius === 0) {
		newRadius = 1;
	}
	$("#radius").text(newRadius);
	check();
})
$.ajaxSetup({
	beforeSend: function(xhr) {
		xhr.setRequestHeader("X-ControlView", "false");
	}
});
var host = "http://tiddlyspace.com";
// TODO: what about running from homepage?
var list = $("#near");
function check() {
	navigator.geolocation.getCurrentPosition(function(a) {
		list.empty();
		var coords = a.coords;
		var lat = coords.latitude;
		var lng = coords.longitude;
		var radius = parseInt($("#radius").text(), 10) * 1000;
		var search = new tiddlyweb.Search("near:" + lat + "," + lng + "," + radius, "/");
		search.get(function(tiddlers) {
			tiddlers.sort(function(a, b) {
				return a.modified < b.modified ? 1 : -1;
			});
			for(var i = 0; i < tiddlers.length; i++) {
				var tiddler = tiddlers[i];
				var item = $("<li />").appendTo(list);
				$("<a />").attr("href",
					host + "/bags/" + encodeURIComponent(tiddler.bag.name) + "/tiddlers/" + encodeURIComponent(tiddler.title)).text(tiddler.title).appendTo(item);
				$("<span />").text(" " + simpleDate(tiddler.modified)).appendTo(item);
				$("<span />").text(" from ").appendTo(item);
				// TODO: hacky
				$("<a />").attr("href", "http://" + tiddler.modifier + ".tiddlyspace.com").appendTo(item).text(tiddler.modifier);
			}
			if(tiddlers.length === 0) {
				$("<li />").appendTo(list).text("no tiddlers nearby");
			}
		}, function() {
			$("<li />").text("Unable to retrieve tiddlers nearby").appendTo(list);
		});
	}, function() {
		$("<li />").text("Unable to get your current location").appendTo(list);
	});
}
check();
</script>
</body>
</html>
/*!
|''Name:''|NiceTaggingPlugin|
|''Description:''|Creates a nicer interface for adding and removing TiddlyWiki. Ideal for tiddly novices. |
|''Version:''|0.6.6|
|''Date:''|October 2010|
|''Source:''|http://svn.tiddlywiki.org/Trunk/contributors/JonRobson/plugins/niceTagging/plugins/NiceTaggingPlugin.js|
|''Author:''|Jon Robson|
|''License:''|[[BSD open source license]]|
|''CoreVersion:''|2.3|
|''Dependencies:''||
!Usage
{{{<<niceTagger tags>>}}} or {{{<<niceTagger field>>}}}
!!Additional Parameters
splitOn: <character>
valuesSource: <tiddler title>
textcase: <lower>
!StyleSheet
.tip {font-style:italic;font-weight:bold;}
input.dp-applied {width: 140px; float: left;}
.niceTagger input {width:200px; float:left;}
.deleter {color:red; font-weight:bold; padding:2px; cursor:pointer;}
.ac_results {padding: 0px;border: 1px solid black;background-color: white;overflow: hidden;z-index: 99999;}
.ac_results ul {width: 100%;list-style-position: outside;list-style: none;padding: 0;margin: 0;}
.ac_results li {margin: 0px;padding: 2px 5px;cursor: default;display: block;font: menu;font-size: 12px;line-height: 16px;overflow: hidden;}
.ac_loading {background: white url('indicator.gif') right center no-repeat;}
.niceTaggerAdder input {width:auto; display: inline;}
.ac_odd {background-color: #eee;}
.ac_over {background-color: #0A246A;color: white;}
*/
//{{{
(function($) {

config.shadowTiddlers.NiceTaggingStyle = store.getTiddlerText(tiddler.title + "##StyleSheet");
store.addNotification("NiceTaggingStyle", refreshStyles);

String.prototype.toJSON = function(){
	var namedprms = this.parseParams(null, null, true);
	var options ={};
	for(var i=0; i < namedprms.length;i++){ 
		var nameval = namedprms[i];
		if(nameval.name) {
			options[nameval.name] = nameval.value;
		}
	}
	return options;
};

var macro = config.macros.niceTagger = {
	lingo:{
		add: "add"
	},
	twtags: {},
	initialised:{},
	init: function(field){
		field = !field ? 'tags' : field;
		if(this.initialised[field]){
			if(field == 'tags') {
				var numTags = store.getTags();
				if(numTags.length == this.twtags[field].length) {
					return;
				}
			} else {
				return;
			}
		}
		var tiddlers= store.getTiddlers();
		macro.twtags[field] = [];
		var uniqueSuggestions = [];
		for(var i=0; i < tiddlers.length; i++){
			var tid = tiddlers[i];
			var values;
			if(field=='tags') {
				values = tid.tags;
			} else {
				values= tid.fields[field];
				values = values ? values : "";
				values = values.readBracketedList();
			}
			for(var j=0; j < values.length; j++){
				uniqueSuggestions.pushUnique(values[j]);
			}
			
		}
		macro.twtags[field] = uniqueSuggestions;
		this.initialised[field] =true;
	},
	save: function(title, field, listvalues, place, autosavechanges) {
		var tiddler = store.getTiddler(title);
		var tiddlerEl = story.getTiddler(title);
		var valueToSave;
		valueToSave = String.encodeTiddlyLinkList(listvalues);
		var el = $("[edit=%0]".format([field]), tiddlerEl);
		if(el.length === 0) {
			el = $("<input />").attr("type", "hidden").attr("edit", field).appendTo(place);
		}
		el.val(valueToSave);

		var dummy = new Tiddler(title);
		if(field == "tags") {
			dummy.tags = listvalues;
		} else {
			dummy.fields[field] = valueToSave;
		}
		return dummy;
	},
	refreshFieldDisplay: function(place, tiddler, field) {
		var container = $(".niceTagger", place);
		container.empty();
		var values;
		if(!field || field == 'tags') {
			values = tiddler.tags;
		} else {
			values = tiddler.fields[field] ? tiddler.fields[field].readBracketedList() : [];
		}
		for(var t = 0; t < values.length; t++){
			var tag = values[t];
			$("<span />").addClass("tag").text(tag).appendTo(container);
			$("<span />").addClass("deleter").text("x").attr("deletes", escape(tag)).appendTo(container);
		}

		$(".deleter", place).click(function(ev){
			var todelete = $(ev.target).attr("deletes");
			var newValues = [];
			for(var i = 0; i < values.length; i++){
				var value = values[i];
				if(escape(value) != todelete) {
					newValues.push(value);
				}
			}
			tiddler = macro.save(tiddler.title, field, newValues, place, tiddler.autosavechanges);
			macro.refreshFieldDisplay(place, tiddler, field);
		});
	},
	saveNewValue: function(tiddler, field, value, container, splitChar) {
		var tiddlerEl = story.getTiddler(tiddler.title);
		var editEl = $("[edit=%0]".format([field]), tiddlerEl);
		var adder = $(".niceTaggerAdder input[type=text]", container);
		var saveThis;
		if(editEl.length > 0) {
			saveThis = editEl.val() || "";
			saveThis = saveThis.readBracketedList();
		} else {
			if(field == 'tags') {
				saveThis = tiddler.tags;
			} else {
				var val = tiddler.fields[field];
				val = val ? val : "";
				saveThis = val.readBracketedList();
			}
		}
		value = typeof(value) == 'string' ? value.trim() : value;
		if(value.length === 0) {
			return;
		}
		var newValues;
		if(splitChar && value && value.indexOf(splitChar) != -1){
			newValues = value.split(splitChar);
		} else {
			newValues = [value];
		}
		for(var i = 0; i < newValues.length;i++){
			var svalue = newValues[i];
			saveThis.pushUnique(svalue);
		}
		tiddler = macro.save(tiddler.title, field, saveThis, container, tiddler.autosavechanges);

		macro.refreshFieldDisplay(container, tiddler, field);
		$(adder).val("");
	},
	getSuggestionsFromTiddler: function(srcTiddler, textcase){
		var suggestions = [];
		if(srcTiddler){
			var src = store.getTiddler(srcTiddler);
			var text = src.text;
			var tempdiv = document.createElement("div");
			wikify(text, tempdiv, null, src);
			var html = $(tempdiv).html();
			suggestions = html.split(/<br\/?>/gi);
		}
		var finalSuggestions = [];
		for(var i=0; i < suggestions.length; i++){
			var val = suggestions[i].trim();
			if(textcase && textcase == "lower") {
				val = val.toLowerCase();
			}
			finalSuggestions.pushUnique(val);
		}
		return finalSuggestions;
	},
	removeFromList: function(list,removeList){
		var uniqueSuggestions = [];
		for(var i=0; i < list.length; i++){
			var s =list[i];
			if(s && typeof(s) == 'string'){
				if(uniqueSuggestions.indexOf(s) ==-1 && removeList.indexOf(s) ==-1){
					uniqueSuggestions.push(s);
				}
			}
		}
		return uniqueSuggestions;
	},
	handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		var options = paramString.toJSON();
		var args = paramString.parseParams("anon")[0];
		if(options.autoSaveChanges) {
			tiddler.autosavechanges = true;
		}
		if(!options.field) {
			options.field = args.anon ? args.anon[0] : "tags";
		}
		this.init(options.field);
		var container = $("<div />").addClass("niceTaggerContainer").attr("field", options.field).
			appendTo(place)[0];
		var displayer = $("<div />").addClass("niceTagger").appendTo(container)[0];
		macro.refreshFieldDisplay(container, tiddler, options.field);
		var tagplace = $("<div />").addClass("niceTaggerAdder").appendTo(container)[0];
		var splitChar = options.splitOn;
		var adder;

		if($().autocomplete){
			params = paramString.parseParams("anon", null, true, false, false);
			var textcase = getParam(params, "case");
			var srcTiddler = getParam(params, "valuesSource");
			var suggestions;
			if(srcTiddler) {
				suggestions = macro.getSuggestionsFromTiddler(srcTiddler, textcase);
			} else {
				suggestions = [];
			}
			var tagsoff = getParam(params,"nostoretags");
			if(!tagsoff) {
				suggestions = suggestions.concat(macro.twtags[options.field]);
			}

			var ignoreList = paramString.parseParams("exclude", null, true, false, true);
			if(ignoreList && ignoreList[0] && ignoreList[0].exclude) {
				ignoreList = ignoreList[0].exclude;
			} else {
				ignoreList = ["excludeList"];
			}
			suggestions = macro.removeFromList(suggestions, ignoreList);

			var addtaghandler = function(v) {
				macro.saveNewValue(tiddler, options.field, $(v).val(), container, splitChar);
			};
			$("<input type='text' name=\""+options.field+"\" value=\"\"/>").autocomplete(suggestions,{ matchContains: true, selectFirst:false }).result(addtaghandler).appendTo(tagplace);
			adder = $("input", tagplace)[0];
		} else {
			adder = document.createElement("input");
			tagplace.appendChild(adder);
		}
		$(adder).keypress(function (ev) {
			ev.stopPropagation();
			if(ev.which == 13){
				var results = $(".ac_over",".ac_results"); //is anything highlighted in autocomplete plugin ?
				var value;
				if(results.length === 0) {
					value = $(ev.target).val();
				} else {
					value = $(results[0]).val();
				}
				macro.saveNewValue(tiddler, options.field, value, container, splitChar);
			}
		});
		var addbutton = document.createElement("input");
		addbutton.type = "button";
		addbutton.value = macro.lingo.add;
		addbutton.className = "adder";
		tagplace.appendChild(addbutton);
		$(addbutton).click(function(e){
			var val = $(adder).val() || "";
			macro.saveNewValue(tiddler, options.field, val, container, splitChar);
		});
	}	
};

_setTiddlerField = Story.prototype.setTiddlerField;
Story.prototype.setTiddlerField = function(title, value, mode, field) {
	var tiddler = store.getTiddler(title) || new Tiddler(title);
	var container = $(".niceTaggerContainer[field=%0]".format([field]), 
		story.getTiddler(title));
	if(container.length > 0) {
		macro.saveNewValue(tiddler, field, value, container[0]);
	} else {
		_setTiddlerField.apply(this, arguments);
	}
	
};
})(jQuery); //end alias
//}}}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" version="1.1" viewBox="301 225 48 52"
width="30" height="30">
<g stroke="none" stroke-opacity="1" stroke-dasharray="none" fill="none" fill-opacity="1">
	<g>
		<path d="M 333.00003 234 L 306 258.75003 L 301.5 270 L 312.75 265.50003 L 339.75 240.74998 Z M 337.5 229.50002 
		L 335.24988 231.75008 L 341.99997 238.50003 L 344.24997 236.24995 Z M 342 225.00003 L 339.74988 227.25009 
		L 346.5 234.00005 L 348.75 231.75003 Z M 301.5 273.9719 C 301.5 273.9719 309.59888 277.99927 317.70013 273.97183 
		C 325.80066 269.94437 341.99997 276.65686 341.99997 276.65686 L 341.99997 273.97195 
		C 341.99997 273.97195 325.80014 267.2594 317.70013 271.28687 C 309.6 275.31451 301.5 271.28683 301.5 271.28683 Z" 
		fill="#101010" class="glyph"/>
	</g>
</g>
</svg>
/***
|''Name''|LoadMissingExternalTiddler|
|''Version''|0.1.0|
|''Author''|Jon Robson|
***/
//{{{
var _loadMissing = Story.prototype.loadMissingTiddler;
Story.prototype.loadMissingTiddler = function(title,fields,callback) {
	var matches = title.match(/([^\*]*) \*\(@([^\)]*)\)\*/);
	if(matches && matches.length > 0) {
		var sTitle = matches[1];
		var space = matches[2];		config.extensions.tiddlyspace.displayServerTiddler(story.getTiddler(title),
			sTitle, "bags/%0_public".format(space));
	} else {
	_loadMissing.apply(this, arguments)
	}
};
//}}}
/***
https://raw.github.com/tiddlyweb/chrjs/master/main.js
***/
//{{{
// TiddlyWeb adaptor
// v0.14.3

/*jslint vars: true, unparam: true, nomen: true, white: true */
/*global jQuery */

var tiddlyweb = (function($) {

"use strict";

var tw = {
	routes: {
		// host is the TiddlyWeb instance's URI (including server_prefix)
		// placeholders "_type" & "name" refer to the respective bag/recipe
		root     : "{host}/",
		bags     : "{host}/bags",
		bag      : "{host}/bags/{name}",
		recipes  : "{host}/recipes",
		recipe   : "{host}/recipes/{name}",
		tiddlers : "{host}/{_type}s/{name}/tiddlers",
		tiddler  : "{host}/{_type}s/{name}/tiddlers/{title}",
		revisions: "{host}/{_type}s/{name}/tiddlers/{title}/revisions",
		revision : "{host}/{_type}s/{name}/tiddlers/{title}/revisions/{revision}",
		search   : "{host}/search?q={query}"
	}
};

var convertTimestamp, supplant;

// host (optional) is the URI of the originating TiddlyWeb instance