<!--{{{-->
<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml' />
<!--}}}-->
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
/*{{{*/
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]];}

.sparkline {background:[[ColorPalette::PrimaryPale]]; border:0;}
.sparktick {background:[[ColorPalette::PrimaryDark]];}

.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]];}

#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:0px; top:0px;}

.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:0px 3px 0px 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:0px; padding-bottom:0px;}

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

.sparkline {line-height:1em;}
.sparktick {outline:0;}

.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='header' 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' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
<!--{{{-->
<div class='toolbar' 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>
<!--}}}-->
<!--{{{-->
<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>>
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]]
<<importTiddlers>>
Tanner and Yeoman.
	Adamin granted 1779.
	Date of death is burial date.
	Inherited Woodbrow estate and share in Bakestone pit from father 14 July 1731.
Clothier.
	Birth date = baptism, death date= burial.
DOB = baptism




Baptised in 27 March 1754.
	Married 1775-01-02 to Henry Whitehead.
Wife of John Scholefield of Grange.
DOB = baptism, DOD=burial.
	Maried James Mills of Wood - 20 Aug 1786
	He died 26 July 1832 in 72 year.

Baptised 2 Aug 1818 at St. Thomas, Friarmere.
Married William Clark a packer for pottery Rawmarsh.
	Had 3 children: unknown, James and Mary.

Daughter of Francis Scholefield of Castleshaw.
	Yeoman.
	Died aged 88 years. Buried 21 Sept 1796.





DOB = baptism.
Baptised 3 July 1831 at St. Thomas, Friarmere. Died in Oldham.
DOB = baptism, DOD=burial
DOB = baptism, DOD=burial
DOB = baptism, DOD= burial.
DOB = baptism, DOD= burial.


DOB = baptism, DOD=burial.
	Married John Shaw of Hollinbank.





Charles Henry Brew was born 10 October 1854 in the Timber Yard (His father was a Sawyer at the time), in Chepstow, Monmouthshire, Wales, and died 4 March 1921 in Pontypridd, Glamorgan, Wales. He married Mary Ann Smith on 10 May 1873 in Swindon, Wiltshire, England.





Possible christening..
	Christened 25 FEB 1883   	St Nicholas, Newcastle Upon Tyne, Northumberland, England
	mother: Dorothy Ann Colson father: John Robson
Married Thomas before 1881.





Sister of Edmund Buckley of Shelderslow.

Wife of James Taylor of Ogden. Marriage settlement 7 Nov 1694.

Source: http://www.british-history.ac.uk/report.asp?compid=42621

	Married Will John Spearman Wasey [http://genuki.cs.ncl.ac.uk/Transcriptions/DUR/BMI.html]



Housekeeper in 1881 census to William Bellwood. Upon the death of Margaret Robson she was living in the house at the time in mechanic yard, East Thickley, Durham, England.



She married 18 October 1854

	Emma Brew was born a "base child" (illegitimate) to Elizabeth Brew, John and Rachel"s oldest daughter, in Caldicot, Monmouthshire, Wales, on 26 February 1835. On the birth certificate, Elizabeth"s occupation is stated as a "Charwoman". When Emma married on 18 October 1854, she is described as daughter of John Brew, which would apply Elizabeth"s parents took in her daughter as if she were their own child. Perhaps they adopted her or perhaps it was a well-kept family secret. Interestingly, however, like her older "brother" (actually uncle), her mother"s brother Thomas, Emma was also deaf. When Elizabeth married in 1838 (Emma was three years old), it appears she didn"t take her daughter with her into the family, but rather left her in the care of her own parents, where she stayed until Emma herself married in 1854. Perhaps Emma grew up thinking her grandparents were her real parents, and never really knew the truth? We will never know.
	Source: Brew Family tree
17th February 1960 he received a settled quarter share of residue £117 from the deceased "Helen Euphemia Robson". At the time he was living at 80 Victoria Avenue, Porthcawl, Glamorgan. Miss Connie Howells, John F. Darroch and Dr. Malcolm H Darroch also received equal amounts.

	He died in Porthcawl.






Died at Woolen Sizer.
Baptised 14 Mar 1824 at St. Thomas, Friarmere.

Died Ashton-u-Lyme. Buried 14 April 1896 at St Thomas Ashton-u-Lyme.
He married Elizabeth Billingham, who was born ca. 1859 in Swansea, Glamorgan, Wales, the daughter of Eli Billingham, on 31 October 1880 in Christchurch Parish, Swansea, Glamorgan, Wales.
Supposedly married an East Indian Woman. Had 3 children?
	Gilbert was an officer killed at Teinco Males.
Daughter of Henry Phillips, married on 7 June 1930 in Port Talbot, Glamorganshire, Wales.

Baptised 31 Mar 1839 at St. Thomas, Friarmere.
The I.G.I. indicates John and Rachel also had other children, namely Mary, born 1821, Jane, born 1826, and Hannah, born 1831, but is most likely an error as John"s brother Thomas had children by these names.


Possibly born in September 1883.
In her will she lists the following relatives:
	John Mathie Darroch (nephew)
	James Darroch (nephew)
	Jennie Lewis (neice - sister"s daughter)
	Jeanie Thorburn (neice - daughter of her late brother)
	Margaret Fife (daughter of her late brother)
	Nance Graham (daughter of her late brother)
	Nellie Spears (daughter of her late brother)
	Alexander Spears (son of late brother)
	Robert Spears (nephew)
	Connie/Eric Howells (neice/nephew - daughter/son of late husband"s sister)
	John Robson (brother in law)

	She appears to have lived in Swansea as she donates money to Swansea Orphan Home for Girls,Swansea and Brecon Diocesan Trust, money for the upkeep of New Recreation Hall of St. Albans Church among many others.She donates £1000 for Swansea General and Eye Hospital in connection with a bed to be called the "Adam Lyall Robson" bed
Baptised 2 Apr 1826 at St. Thomas, Friarmere.
DOB = baptism, DOD=burial
DOB = baptism, DOD=burial







DOB = baptism, DOD=burial
Child out of wedlock.
Possibly christened 15 OCT 1831   	Newcastle Upon Tyne, Northumberland, England. Parents John and Jane at All Saints.

	In 1851, she cannot be found with the family. Possibly having married or died or gone to stay with relatives.
married Reginald Mackworth Cotton in December 1919 in Neath, Glamorganshire, Wales 
Spinster.
Baptised 20 April 1834 at St. Thomas, Friarmere.
Yeoman.
	Buried 23 Sep 1748.
	Will proved 1748.
	Inherited Brimmycroft and Coatmans from father.

Sold half share in Brimmycroft c. 1760.
	Tame Croft, Tanner.


The I.G.I. indicates John and Rachel also had other children, namely Mary, born 1821, Jane, born 1826, and Hannah, born 1831, but is most likely an error as John"s brother Thomas had children by these names.



Possibly christened 01 AUG 1829 Newcastle Upon Tyne, Northumberland, England. On familysearch there is an entry for christening with parents John and Jane at All Saints.
Possible marriage:  	
	03 DEC 1860   	All Saints, Newcastle Upon Tyne, Northumberland, England




Died in World War. Memorial in Chelmsford / Stock area.







Died 27 December 1914 in Aberavon, Glamorgan, Wales. He became a Police Constable, and married Sarah Short
Gent.
	Will proved 30 Nov 1850.
Will proved 10 Sept 1812. Inherited Ocknell Lee. Later lived in Hough Yeoman.
Baptised 5th March 1777.
Later of Castlehill Cote.
	Yeoman.
	Buried 2 Feb 1788.
	Sold a half share in Brimmy CVroft c. 1760.
	Inherits Coatman"s from father.

Life insurance agent.


By 31st December 1938 he appears to be living in Ontario Canada
In the 1881 census he is living at 4 Coxon St with his wife.
	 John Thos. ROBSON  	 M  	 Male  	 22  	 Blythe, Northumberland, England  	 Timber Merchant (Manager) 
	 Dorothy ROBSON  	 M  	 Female  	 23  	 Sunderland, Durham, England  	  

	In 1891 census:
	1891 census
	View Record Dorothy Robson abt 1859 Sunderland, Durham, England Wife Bishop Wearmouth Durham
	View Record Dorothy Robson abt 1882 Sunderland, Durham, England Daughter Bishop Wearmouth Durham
	View Record Harold Robson abt 1884 Sunderland, Durham, England Son Bishop Wearmouth Durham
	View Record Jennie Robson abt 1886 Sunderland, Durham, England Daughter Bishop Wearmouth Durham
	View Record John Thomas Robson abt 1859 Blyth, Northumberland, England Head Bishop Wearmouth Durham
	View Record Kathleen Robson abt 1890 Sunderland, Durham, England Daughter Bishop Wearmouth Durham 

	In the 1901 census he is alive and living in the Sunderland parish
	 Arthur Robson abt 1900 Sunderland, Durham, England Son Sunderland Durham
	Dorothy Robson abt 1859 Sunderland, Durham, England Wife Sunderland Durham
	Dorothy Robson abt 1882 Sunderland, Durham, England Daughter Sunderland Durham
	Harold Robson abt 1884 Sunderland, Durham, England Son Sunderland Durham
	Jennie Robson abt 1886 Sunderland, Durham, England Daughter Sunderland Durham
	John S Robson abt 1859 Blyth, Northumberland, England Head Sunderland Durham
	John W Robson abt 1892 Sunderland, Durham, England Son Sunderland Durham
	Kathleen Robson abt 1890 Sunderland, Durham, England Daughter Sunderland Durham
	Martha Robson abt 1897 Sunderland, Durham, England Daughter Sunderland Durham
	Winnie Robson abt 1895 Sunderland, Durham, England Daughter Sunderland Durham 
	???
	Possible Marriage: Dorothy Coulson 04 OCT 1875  	All Saints, Newcastle Upon Tyne, Northumberland, England ?!?!


Baptised 20 Oct 1820 at St. Thomas, Friarmere.
Baptised 1 Jan 1828 at St. Thomas, Friarmere.
Died a minor (fell backwards down a pit)


DOD=burial

Possibly born in September 1889










Died during child birth.


Funeral service was held on Wednesday 24th May 2006  at Bethlehem Evangelical Church. She was buried at Goytre Cemetery. The officiating minister was Reverend Jeremy Bailey.

The I.G.I. indicates John and Rachel also had other children, namely Mary, born 1821, Jane, born 1826, and Hannah, born 1831, but is most likely an error as John"s brother Thomas had children by these names.

who was christened in Chepstow on 26 October 1817, and married William Niblett in 1847 

Eldest daughter of William Reed Esq.
	Married at Tynemouth.
	Shipowner of Tynemouth, Northumberland.









In 1901 census:
	View Record Maud Lloyd abt 1877 Shelton, Staffordshire, England Servant Aberavon Glamorgan
	View Record John G Robson abt 1843 Middlesbrough, Yorkshire, England Head Aberavon Glamorgan
	View Record Martha J Robson abt 1843 Cockfield, Durham, England Wife Aberavon Glamorgan
	View Record Mary J Robson abt 1876 Darlington, Durham, England Daughter Aberavon Glamorgan 

	Therefore Mary married after 1901.
Mary Ellen Parton, who was born ca. 1893 in Glamorgan, Wales, the daughter of William Henry Parton, on 27 July 1920 in Neath, Glamorganshire, Wales. Mary Ellen died 27 September 1962 in Swansea, Glamorgan, Wales
Baptised 28 May 1822 at St. Thomas, Friarmere.
Married Jame Shaw of Hollin Bank Yeoman (1749-1817)
Baptised 11 Jun 1775.
DOB = baptism
	Married William Waring.






















A Jillot printer and draper. Married twice.

Wrote a series of letters.
	Dec 27th 1820 he writes from Shadwell, London and is having trouble getting a ship and requesting money.
	Jan 8th 1821 he writes from London requesting money.
	Oct 17th 1822 he writes from Marunhorm on board a shooner (a ship)
	St Jago de Cuba March 24 1824 he talks of being in the Columbian service and had been taken prisoner for 4 months. He mentions a cousin Bella and Uncle James Atchison and Uncle William Silkson/Nicholson (the surnames aren"t clear) and Aunt Jane as well as brothers William and Adam. He say he plans to live in Cuba for only 3/4 years.
	Sept 1824 he writes about how he has been in prison but is no longer, he also mentions his brother has married a French woman, and it seems this combined with him being in prison has upset the family.
	My 10th 1830 he writes from Cuba reporting that money is scarce.
	In 1831 he writes saying a war may be imminent. He also talks of negroe slaves being paid nothing for their labour.
	A letter received in UK Aug 21st 1833 (so probably sent 6 months before in Feb) he writes about how he is not yet married. He mentions his parents have moved and asks to know the day of the month in which he was born. HE has heard his sister Isabella has married which backs up that Isabella Lyall nee Jackson was his sister as she married Adam in 1831.
	17th Jan 1834 he is still not married and is asking to talk to his brother. It hints at a dispute in the family to do with him. He has however had a child Isabella.
	16th Dec 1836 he is still not married 
	In a damaged letter lots of which is missing (segments have just fallen off due to its age) with dates 11th May 1844/June 10th 1844 written on the envelope (maybe postmarks?) he is still working for Messrs Wright Brooks & Co of St Jago de Cuba. We can assume it is Robert he seems to be well and happy and enquires about his father.


	In a later letter dated April 15th 1849 addressed to Messrs. Wright, Brooks & Co (who he worked for in Cuba) asking if they know of whether he is living or dead. This letter is written by his nephew Robert Jackson (however it is unknown who"s son he is - I however expect Adam).

	
A Robert Jackson did exist and he was a nephew of Robert Jackson (1800-).

	Census from 1841 and 1861 suggest he was the son of Adam.
Died in Highworth, Swindon, Wiltshire.

The 1901 census shows him living with brother Matthew as boarders to the owners David Llond (born 1853 Pembrey, Carmathenshire Wales) and Mary Jane Llond (born 1858 Pembrey, Carmarthenshire, Wales). His profession is Roll Turner in the steel industry.





Married James Kershaw.
	DOB = baptism.




Baptised St. Thomas, Friarmere on 20 April 1799
Baptised 8 April 1759.
	Married Rev James Mashister, Curate of Shaw (-1795)
Married Charles Padfield, born 1878 in Monmouthshire, Wales, the son of Thomas Padfield, on 16 July 1901 in Newport, Monmouthshire, Wales


Daughter of Thomas Shepley of Stalybridge.
	Living 1779.
Daughter of Caleb Short. Died in Port Talbot, Glamorgan, Wales.



Magistrate of Elvit Durham.
	had 2 children. One of which lived at Newton Hall, the other at Scrunton as a solicitor.



DOB = baptism.


Baptised April 1779.
	Captain of Royal Lancashire Militia,
	Lieutenant of the 11th Light Dragoons.
	Woollen printer and cotton spinner.



Potter of Rawmarsh.
	Married in Rotherham.
	Married Elizabeth who had a 2nd husband Thomas Sharp (also a potter of Rawmarsh)
DOB = baptism, DOD= burial.
married Edward John Walsingham, born ca. 1897 in Glamorgan, Wales, son of Frank Walsingham, on 8 September 1924 in Port Talbot, Glamorgan, Wales.





The 1881 census shows him as a painter living at a mechanics yard, East Thickley, Durham, England.

	At the time his wife Margaret Robson has recently passed away and he is living with his future wife Elizabeth Vipond (26) who is currently the housekeeper. He lives with his 2 children Joseph William (7) and Mary Ann (6). 



Baptised 13 Aug 1830 at St. Thomas, Friarmere.
UNCONFIRMED:

	In 1851 census:
	Jane Robson abt 1832 Heaton, Northumberland, England Wife Bishopwearmouth
	Durham
	View Record John Thos Robson abt 1859 Blyth, Northumberland, England Son
	Bishopwearmouth Durham
	View Record Margaret Robson abt 1860 Blyth, Northumberland, England Daughter
	Bishopwearmouth Durham
	View Record William Robson abt 1835 Walker, Northumberland, England Head
	Bishopwearmouth Durham

	In 1861 census:
	Jane Robson abt 1832 Heaton, Northumberland, England Wife Bishopwearmouth Durham
	View Record John Thos Robson abt 1859 Blyth, Northumberland, England Son Bishopwearmouth Durham
	View Record Margaret Robson abt 1860 Blyth, Northumberland, England Daughter Bishopwearmouth Durham
	View Record William Robson abt 1835 Walker, Northumberland, England Head Bishopwearmouth Durham 

	In 1881 census living at 6 Harold Street (Bishopwearmouth, Durham, England census returns):
	William ROBSON  	 Head  	 M  	 Male  	 46  	 Walker, Northumberland, England  Timber Merchant (8 Men 1 Boy)  	  
	Jane ROBSON  	 Wife  	 M  	 Female  	 49  	 Heaton, Northumberland, England  	   	

	Margt. ROBSON  	 Daur  	 U  	 Female  	 21  	 Blythe, Northumberland, England  	     

	Jane A. ROBSON  	 Daur  	 U  	 Female  	 18  	 Sunderland, Durham, England  	   	

	 Isabella ROBSON  	 Daur  	 U  	 Female  	 16  	 Sunderland, Durham, England  	 Scholar  	  
	Barbara ROBSON  	 Daur  	 U  	 Female  	 14  	 Sunderland, Durham, England  	 Scholar  	  
	Mary A. ROBSON  	 Daur  	 U  	 Female  	 12  	 Sunderland, Durham, England  	 Scholar  	  
	Emily ROBSON  	 Daur  	 U  	 Female  	 9  	 Sunderland, Durham, England  	 Scholar
	  	William ROBSON  	 Son  	 U  	 Male  	 2  	 Sunderland, Durham, England  	  


Vismo Tree 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/Family%20Trees%20for%20TiddlyWiki]]
If you want your own copy simply right click [[this link and select save target as|http://www.jonrobson.me.uk/development/familytree/index.html]]

!Instructions
!!Example
See [[Jon Robson's Family Tree|http://www.jonrobson.me.uk/FamilyTree]]
!!Tagging
Tagging a tiddler with rootTree will make them appear on startup.
Tagging a tiddler with excludeTree will stop it from appearing in the family tree visualisation.

!Feedback
I would love to hear your feedback - please post it [[here|http://groups.google.com/group/TiddlyWiki/topics]] or contact me through [[one of these mediums|http://www.jonrobson.me.uk/posts/AboutMe%20and%20Contact%20Me]]
Soldier in Oxford Blues in 1771. Brothers inherited his estates.
In Sept 1824 brother Robert writes "The stone mason business is better in this country than any other mechanical business. I hope that my brother Adam will continue at his trade and that you will send him to some place where he will learn his business to perfection which if he does not wish to continue in his own country after he is free, the West Indies are far better wages given for men that follow that business than either Europe or America," - it"s a bit unclear but it was possible that Adam was a stone mason apprentice.

	In 1834 a letter from Robert mentions that his brother Adam has said a married life is good", this hints that he has married.
	The way Robert talks about his brothers Matthew and Adam suggests he is looking out for them much like an older brother.

	This is the only Adam Jackson listed for Durham in 1841 and he IS a stone mason. He also has a son Robert Jackson, who could be the nephew of Robert that writes a letter asking for information on his uncle.

	Name: Adam Jackson
	Age: 35
	Estimated Birth Year: abt 1806
	Household:Mary 35, Robert 11,Thomas 9,James 7,Margaret 4, Adam 1
	Gender: Male
	Where born: Durham, England
	Civil parish: Gateshead
	Hundred: Chester (East Division)
	County/Island: Durham
	Country: England
	Street address:Hillgate
	Occupation: Mason
	Source information: HO107/296/14
	Registration district: Gateshead
	Sub-registration district: Gateshead
	ED, institution, or vessel: 13
	Folio: 5
	Page: 4 (click to see others on page)
	Line number: 9
	GSU Number: 241345 

	In 1861 the same Adam can be found, however his place of birth is more specific - Jarrow - just like his sister Isabella.
	Name: Adam Jackson
	Age: 55
	Estimated Birth Year: abt 1806
	Relation: Head
	Spouses"s Name: Mary
	Gender: Male
	Where born: Jarrow, Durham, England
	Civil parish: Gateshead
	Ecclesiastical parish: St Mary
	Town: Gateshead
	County/Island: Durham
	Country: England
	Street address:
	Occupation: Stone Mason
	Registration district: Gateshead
	Sub-registration district: Gateshead
	ED, institution, or vessel: 2
	Neighbors: View others on page
	Household schedule number: 110
	Household Members: Name Age
	Adam Jackson 55
	Mary Jackson 56
	Robert Jackson 31 

Possible baptism (but unconfirmed):
	1. Baptised 18/12/1808 Child"s name Adam LYAL Father Adam Mother Martha Mother"s Maiden name NISBET Place Gosford Occupation – Other info – Father --- Mother --- Notes John BROWNLEE John ANDERSON Birth date 18/11/1808 Parish Newcastle, High Bridge Meeting, Nbl Checked Checked
	Note Gosforth (possible mispelling is about 3 miles from Killingworth where he is said to be born.
	A Martha Nisbett and Adam "Lyle" married on 09 SEP 1798 at Warkworth, Northumberland, England/

	He is likely to be related to a THOMAS LYALL. In one of the letters sent from America to England from the JACKSONs the sender mentions him.

	1851
	Adam Lyall abt 1808 Northumberland, England Head Wingate Durham
	View Record Elizabeth Lyall abt 1846 Durham, England Daughter Wingate Durham
	View Record Isabell Lyall abt 1808 Durham, England Wife Wingate Durham
	View Record Margaret Lyall abt 1841 Durham, England Daughter Wingate Durham
	View Record Martha Lyall abt 1843 Durham, England Daughter Wingate Durham
	View Record Matthew Lyall abt 1833 Durham, England Son Wingate Durham 

	1861 he is living at Richardson Street and is a Blacksmith
	Adam Lyall abt 1809 Kellingworth, Nottinghamshire, England Head Middlesbrough Yorkshire
	View Record Isabella Lyall abt 1809 Jarrow, Durham, England Wife Middlesbrough Yorkshire
	View Record Margaret Lyall abt 1841 Butterkaowle, Durham, England Daughter Middlesbrough Yorkshire
	View Record Martha Lyall abt 1843 Butterkaowle, Durham, England Daughter Middlesbrough Yorkshire
	View Record Matthew Lyall abt 1833 Jarrow, Durham, England Son Middlesbrough Yorkshire 

	1871 he is living at lower East street and is an Inn keeper
	Adam Lyall abt 1809 Northumberland, England Head Middlesborough Durham
	View Record Elizabeth A Lyall abt 1846 Durham, England Daughter Middlesborough Durham
	View Record Isabell Lyall abt 1809 Durham, England Wife Middlesborough Durham
	View Record Margaret E Lyall abt 1841 Durham, England Daughter Middlesborough Durham 

	Source mispells his name as "Lyill" (familysearch.org).
	The 1881 census shows that his wife Isabella is widowed.

	Due to the fact Jackson is taken by Adam and Isabella"s sons and then later by her grandson Matthew Jackson Robson it is likely Isabella"s original name was Jackson. There are also letters in the family written by ancestors from the Jackson family. A marriage is recorded for Adam Lyall and Isabella Jackson at ST JOHN"S CHURCH situated on the west side of Westgate-street, Durham. The marriage took place on 31 Dec 1831.

/***
|''Name:''|AdvancedEditTemplatePlugin based on ValueSwitcherPlugin|
|''Description:''|Gather values from a definition tiddler, and present the user with a UI for setting a value from those available options as an extende field |
|''Version:''|0.4|
|''Date:''|02 March 2009|
|''Source:''|http://www.jonrobson.me.uk|
|''Author:''|Jon Robson : based on the work by PhilHawksworth (phawksworth (at) gmail (dot) com)|
|''License:''|[[BSD open source license]]|
|''CoreVersion:''|2.3|

Allows the adding of multiple level drop down menus and checkboxes to the edit template.
***/

//{{{
// Ensure that this Plugin is only installed once.

// create macro object
(function($) { // set up alias

if(store){
  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;}\n"+
  ".jCalendar .selected {background-color:gray;}\n"+
  "/*}}}*/"
store.addNotification("AdvancedEditTemplateStyle", refreshStyles);
}

config.macros.viewimage ={    
     handler: function(place,macroName,params,wikifier,paramString,tiddler){

        var params = paramString.parseParams("anon",null,true,false,false);

    	var classname = getParam(params,"class");
        if(!classname) classname = "";

        var src = getParam(params,"src");
        //alert("here");
        var fieldname = getParam(params,"field");
        if(fieldname) src= tiddler.fields[fieldname];

        var maxw = getParam(params,"maxwidth");
        var maxh = getParam(params,"maxheight");
        
        var imagew,imageh;
        
        var html = "<img";
        if(classname)html+=" class='"+ classname+"' ";
        
        html += " src='"+src+"'";
        
        if(maxw || maxh){
           
            var image = new Image();

            image.onload = function(){
           
                var ratio =   image.height/image.width;
                
                var largerW, largerH;
                
                if(image.height > image.width){
                    largerH = true;
                }
                else {
                    largerW = true;
                }
                //console.log("maxw,maxh",maxw,maxh);
                if(largerW && image.width > maxw){
                    imagew = maxw;
                    imageh = parseInt(imagew * ratio);
                }
                else if(image.height > maxh){
                    imageh = maxh;
                    imagew = parseInt(imageh / ratio);
                }
                	if(imagew) html += " width='"+imagew+"'";
                	if(imageh) html += " height='"+imageh+"'";
                
                html += "/>";
                //alert(html)\
               
                jQuery(place).append(html);
                	
            };
            image.src = src; //this must come after defining the onload event
        }
        else{
            html += "/>";
            //alert(html)
            jQuery(place).append(html);
        }

    
    	
   
	
    }
};




if(config.macros.view){
    if(!config.macros.view.views)config.macros.view.views={};
    config.macros.view.views.image = function(value,place,params,wikifier,paramString,tiddler) {
    var classname="";
    var params = paramString.parseParams("anon",null,true,false,false);
	
    if(params[2]) classname = getParam(params,"class");
			jQuery(place).append("<img class='"+ classname+"' src='"+value+"'/>");
    
    
    
    };
    

    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("[["+values[i]+"]]\n",place);
        }
        
    };
        
    config.macros.view.views.hiddeninput = function(value,place,params,wikifier,paramString,tiddler) {
        var classname="";
        if(params[2]) classname = params[2];
	    jQuery(place).append("<input type='hidden' value='"+value+"'/>");
    };
}

if(!version.extensions.AdvancedEditTemplatePlugin) 
{
  jQuery("#storeArea").append("<iframe id='aet_iframe' name='aet_post_to' src='' style='display:none;'></iframe>"); 
  
	version.extensions.AdvancedEditTemplatePlugin = {installed:true};
	config.macros.aet_setcolor = {
	    	handler: function(place,macroName,params,wikifier,paramString,tiddler) {
	    	    var color =config.macros.AdvancedEditTemplate.getMetaData(tiddler.title,params[0]);
	    	    place.style.backgroundColor = color;
    	    }
	};
	
	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(!config.macros.aet.lingo[id]) return id;
	        return config.macros.aet.lingo[id];
	    }
		,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;

		}
		,setupRadioboxes: function(place,source,selected,handler){
	
		    var lines = source.split("\n");
		    var radiogroupname = "radiogroup"+Math.random();
		    var radioHtml = "";
		     var currentValue = selected;
		    var selected;
		    for(var i=0; i < lines.length; i++){
		        var val = lines[i];
		        if(val != ""){
    		        if(val == currentValue){
    		            selected = "checked=true";
    		        }
    		        else{
    		            selected = "";
    		        }
    		        var label;
    		        var spl = val.split(":");
    		        if(spl[0] && spl[1]){
    		            label = spl[0];
    		            val = spl[1];
    		        }
    		        else{
    		            label = val;
    		        }
    		        radioHtml += "<input class='aet_radiobutton' "+selected+" type='radio' value=\""+val+"\" name='"+radiogroupname+"'/><label>"+label+"</label>";
		        }
		    }
		    jQuery(place).append("<div class='aet_radioboxes'>"+radioHtml+"</div><div class='clearboth'></div>");
		    jQuery(".aet_radiobutton",place).click(handler);
		}
		,setupSearchbox: function(place,tiddlerobj,metaDataName,valueSource,handler,needsWikify){
		    if(!valueSource) {
				displayMessage("Please provide a parameter valuesSource telling me the name of the tiddler where your drop down is defined.");
				return;
			}
			var selected = store.getValue(tiddlerobj,metaDataName);
			if(!selected){
				var qsvalue =this.getVariableFromQueryString(metaDataName);
				if(qsvalue) selected = qsvalue;
			}
			var tiddlerobj =store.getTiddler(valueSource);
			
			var contents;
			if(needsWikify){
			    var div = document.createElement("div");
			    var source = tiddlerobj.text;
			    wikify(source,div,false,tiddlerobj);
			    var contents = div.innerHTML;
		
			    contents = contents.replace(/\<br\/?\>/gi,"\n");
		    }
		    else{
		        contents = tiddlerobj.text;
		    }
		    
			if(tiddlerobj){
				var values = contents.split('\n');

				this.createSearchBox(place,metaDataName,values,selected,handler);
				jQuery("input",place).keypress(function (e) {
				    
        			if(e.which == 13){
        				var results = jQuery(".ac_over",".ac_results"); //is anything highlighted in autocomplete plugin
        				if(results.length ==0)

        					handler(this.value);
        			}
        		});
        		jQuery("input",place).blur(function(e){
        		    handler(this.value);
        		});
			
			}
		}
		,setupDropdown: function(place,tiddlerobj,metaDataName,valueSource){
				if(!valueSource) {
					displayMessage("Please provide a parameter valuesSource telling me the name of the tiddler where your drop down is defined.");
					return;
				}
				
				if(metaDataName.indexOf(",") > -1){
					fields = metaDataName.split(",");
					for(var j=0; j < fields.length; j++){
						fields[j] = jQuery.trim(fields[j]);
					}
				}
				else{
					fields = [metaDataName];
				}
				
				var selected = store.getValue(tiddlerobj,fields[fields.length -1]);
				if(!selected){
					var qsvalue =this.getVariableFromQueryString(fields[fields.length-1]);
					if(qsvalue) selected = qsvalue;
				}
				var tiddlerobj =store.getTiddler(valueSource);
				
				if(tiddlerobj){
					var values = tiddlerobj.text.split('\n');
					var sorted = tiddlerobj.tags.contains("sorted");
					this.createDropDownMenu(place,fields,values,false,this.setDropDownMetaData,selected,sorted);
				}
		}
		
		,_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)];
                        //console.log("cool");
                        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;
                    }//console.log(arg,evaluatesTo,finalEval);

                }
                return finalEval;
		}
		,doifstatement: function(place,stmt,tiddler){
		    var or = false;
		    if(stmt.indexOf("|") > -1){
		        or= true;
		    }
		    var finalEval = config.macros.aet._doStatement(stmt,tiddler,or);
            
            if(!finalEval){
                place.innerHTML = "";
             }
		    
		}
		,handler: function(place,macroName,p,wikifier,paramString,tiddler) {
			var tiddlerDom = story.findContainingTiddler(place);
			var params = paramString.parseParams("anon",null,true,false,false);
			var ifstmt = getParam(params,"if",null);
			if(ifstmt){
                config.macros.aet.doifstatement(place,ifstmt,tiddler);
			    //place.appendChild(newdiv);
			    return;
			}
			var ctrlType = getParam(params,"type",null);

			var title = tiddlerDom.getAttribute("tiddler");
			var tiddlerobj = store.getTiddler(title);
			var metaDataName = getParam(params,"metaDataName", null);
			var needsWikify = getParam(params,"wikify", null);
			// build a drop down control
			var valueSource = getParam(params,"valuesSource", null);
			if(!valueSource) valueSource = metaDataName + "Definition";
			
			if(ctrlType == 'dropdown') {
			    this.setupDropdown(place,tiddlerobj,metaDataName,valueSource);
			}
			else if(ctrlType == 'embedvideo'){
			    this.setupEmbeddedVideo(place,tiddlerobj,metaDataName,valueSource);
			}
			else if(ctrlType == 'search'){
			    var handler= function(value){
				
					config.macros.AdvancedEditTemplate.setMetaData(title,metaDataName,value);
				};
				this.setupSearchbox(place,tiddlerobj,metaDataName,valueSource,handler,needsWikify);
			}
			else if(ctrlType == 'checkbox'){      					
				this.createCheckBox(place,title,metaDataName);
				
			}
			else if(ctrlType == 'radio'){
			    var source = store.getTiddler(valueSource);
			    if(!source) source = "";
			    else source = source.text;
			    
	    	    var aet = this;
                var handler = function(e){
		            var newval = this.value;
		            console.log(title,metaDataName,newval);
    		        aet.setMetaData(title,metaDataName,newval);
		        }
		        
            	var selected;
            	if(tiddlerobj)selected= tiddlerobj.fields[metaDataName];
			    this.setupRadioboxes(place,source,selected,handler);
			}
			else if(ctrlType == 'date'){
			        this.createDatePicker(place,title,metaDataName);
			}
			else if(ctrlType == 'color'){
				this.createColorBar(place,title,metaDataName);
			}
			else if(ctrlType == 'image'){
				var that = this;
				var handler = function(value){
					that.setMetaData(title,metaDataName,value);
				};
				var initialValue = "";
				initialValue = this.getMetaData(title,metaDataName);
				var image = new config.macros.AdvancedEditTemplate.EditTemplateFile(place, paramString,initialValue,handler,true);
			}
			else if(ctrlType == 'text'){
			    var maxlength = getParam(params,"maxlength", null);
			    var rows = getParam(params,"rows", null);
			    params = [metaDataName];
			    if(rows) params.push(rows);
			    paramString ="";
			    var e = config.macros.edit.handler(place,macroName,params,wikifier,paramString,tiddler);
			    if(maxlength) e.setAttribute("maxlength",maxlength); 
			}
			else if(ctrlType == 'file'){
				var that = this;
				var handler = function(value){
					that.setMetaData(title,metaDataName,value);
				};
				var initialValue = "";
				initialValue = this.getMetaData(title,metaDataName);
				var image = new config.macros.AdvancedEditTemplate.EditTemplateFile(place, paramString,initialValue,handler,false);
			}
		}
		,createColorBar: function(place,tiddlerTitle,metaDataName){

			var aet = this;
			var curValue = this.getMetaData(tiddlerTitle,metaDataName);
			var changefunction = function(newcolor){
				aet.setMetaData(tiddlerTitle,metaDataName,newcolor)
			};
			
			var container = document.createElement("span");
			place.appendChild(container);
			var slider = new VismoColorSlider(container,200,15,changefunction);
			slider.setColor(curValue);
		}
		,createSearchBox: function(place,fieldName,values,initialValue,action){
		    var whatyousee=[];
			var whatyousave = {};
			for(var i=0; i < values.length; i ++){
			    if(values[i] != ""){
    			    var name_value = values[i].split(":");
    			    var name = name_value[0];
    			    var value = name_value[1];
    			    if(!value) value = name;
			    
    			    name = name.replace(/[\>|\<]/ig, "");
    			    value = value.replace(/[\>|\<]/ig, "");
    			    whatyousee.push(decodeURI(name));
    			    whatyousave[name] = value;
    			    if(initialValue == value) initialValue = name;
			    }
			}
			var handler = function(event,targets){
			    
			    if(targets.length == 0) return;
			    var name = targets[0]
			    var save_this = whatyousave[name];
			    if(action)action(save_this);
			};
			
			if(!initialValue) initialValue = "";
			var options = {matchContains: true,selectFirst:false};
		    jQuery("<input type='text' value=\""+initialValue +"\"/>").autocomplete(whatyousee,options).result(handler).appendTo(place);
		
		}

		,_createMenus: function(menutextrepresentation){
			var chain = [0];
			var menus = [];
			var values = menutextrepresentation;
			var myparents = [];
			var depth = 0;
			for (var i=0; i < values.length; i++) {
				
				var value;
				var caption = values[i];
				if(caption.indexOf("##") > -1){ //remove any commenting
					caption = caption.substring(0,caption.indexOf("##"));
				}
				value = caption;

				if(caption.indexOf(":") > -1){
					var splitstr= caption.split(":");
					caption = splitstr[0];
					value = splitstr[1];
				}
				caption = caption.replace("<","");
				caption = caption.replace(">","");
		
				var chainid = chain.length -1;
				if(!menus[chain[chainid]]){
					menus[chain[chainid]] = {depth: depth};
					menus[chain[chainid]].options= [];
				}
	

				if(value.indexOf(">") != -1){
					value = value.replace(">","");
					var newmenuid = menus.length;
					menus[chain[chainid]].options.push({'caption': caption, 'value': value,'childMenu': newmenuid});
					chain.push(newmenuid);
					myparents.push(value+">");
					depth += 1;	
			
				}
				else if(value.indexOf("<") != -1){			
					value = value.replace("<","");

					menus[chain[chainid]].options.push({'caption': caption,'value': value});
					myparents.pop();
					chain.pop();
					depth -= 1;	
				}
				else{
					menus[chain[chainid]].options.push({'caption': caption, 'value':value});
				}
			
						

								
			}
	
			return menus;
		}
		,createDropDownMenu: function(place,fieldName,values,initialValue,handler,selected,sort){
				if(typeof fieldName == 'object'){
					fields = fieldName;
				}
				else{
					fields = [fieldName];
				}
				
				
				if(!selected) selected = "";
				if(!initialValue){
					initialValue = "aet_select";
				}
				var menus = this._createMenus(values);
				
				var lastMenu, fieldid;
				var allMenus = [];
				var selectedItem = false;
				var nowtselected = true;
			
				
				
				for(var j=menus.length-1; j >-1; j--){
					var newMenu = document.createElement("select");
					
					if(j > 0){
						newMenu.style.display = "none";
					}
					if(fields.length == 1){
						fieldid = 0;
					}
					else{
						fieldid = menus[j].depth;
					}
			
					newMenu.name = fields[fieldid];
					newMenu.associatedFields = fields;
					var menuoptions = menus[j].options;
    				for(var k=0; k<menus[j].options.length;k++){
					    var translation = config.macros.aet.translate(menus[j].options[k].caption);
					    if(translation) menus[j].options[k].caption=translation;
					}
					
					if(sort){		 
						var sorter = function(a,b){if(a.caption < b.caption){ return -1; }else return 1;};
						sorter =menuoptions.sort(sorter);
					}
					var firstCaption= config.macros.aet.translate(initialValue);
					if(!firstCaption)firstCaption = initialValue;
					var topitem = [{'caption': firstCaption, 'value': 'null', 'name': null}];
					menuoptions = topitem.concat(menuoptions);
					
					for(var k=0; k <menuoptions.length; k++){
						var opt =menuoptions[k];
						
						if(opt.caption.replace(" ","") != ""){
							var optionEl = document.createElement("option");
							if(opt.childMenu) {
								optionEl.childMenu = allMenus[opt.childMenu];
								optionEl.childMenu.parentOption = optionEl;
							}
						
							if(opt.value){
								optionEl.value = opt.value;
							}
			
							if(nowtselected && optionEl.value ==selected){
								optionEl.selected = true;
								newMenu.style.display = "";
								selectedItem = optionEl;
								nowtselected = false;
							}
							optionEl.appendChild(document.createTextNode(opt.caption));
							newMenu.appendChild(optionEl);
						}
					}
					newMenu.onchange = function(e){
						

						/*toggle menu*/
						var opt =this[this.selectedIndex];
			
						if(opt.childMenu){
							opt.childMenu.style.display=""
							if(this.expandedMenu) this.expandedMenu.style.display = "none";
							this.expandedMenu = opt.childMenu;
						}
						else{
							if(this.expandedMenu) this.expandedMenu.style.display = "none";
							this.expandedMenu = null;
						}
						
						handler(e,this);
					};
					
					allMenus[j] = newMenu;

					if(lastMenu){
						lastMenu.childMenu = newMenu;
					}
					
					lastMenu = newMenu;
					
				}
				for(var k=0; k < allMenus.length; k++){
					place.appendChild(allMenus[k]);
				}
				
				if(nowtselected){
					selectedItem = allMenus[0].firstChild;
				}
				if(selectedItem){
					this._revealSelectMenus(selectedItem);
				}
		}

		,_revealSelectMenus: function(selecteditem){
			if(!selecteditem.selected) selecteditem.selected = true;
			
			var containingmenu = selecteditem.parentNode;
			
			
			if(selecteditem.childMenu){
				selecteditem.childMenu.style.display = "";
				containingmenu.expandedMenu = selecteditem.childMenu;
			}
			if(containingmenu.style.display == "none"){
				containingmenu.style.display = "";
			}
			while(containingmenu){
				var parentoption = containingmenu.parentOption;
				if(parentoption) {
					parentoption.selected = true;
					var parentmenu = parentoption.parentNode;
					if(parentmenu){ 
						parentmenu.style.display = "";
						parentmenu.expandedMenu = containingmenu;
						containingmenu = parentmenu;
					}
					else{
						containingmenu = false;
					}
				}
				else{
					containingmenu = false;
				}

				
				
			}
			
			//containingmenu.parentMenu.style.display = "";
		}



		// Ensure that changes to a dropdown field are stored as an extended field.
		,setDropDownMetaData: function(ev,el) {
      
			var e = ev ? ev : window.event;
			var taskTiddler = story.findContainingTiddler(el);
			
			if(taskTiddler && taskTiddler != undefined) {
				var title = taskTiddler.getAttribute('tiddler');

				
				var selected = el[el.selectedIndex];
				var aet = config.macros.AdvancedEditTemplate;

				
				var fieldname = selected.parentNode.name;
				var fieldvalue = selected.value;
				for(var i=0; i < el.associatedFields.length; i++){
					var fieldname =el.associatedFields[i];
					aet.setMetaData(title,fieldname,fieldvalue);
				}	
				var parent = selected.parentNode.parentOption;
				
				if(selected.value == 'null'){
					if(parent){
						selected = parent;
						fieldvalue = selected.value;	
					}
				}
				
				if(parent){
					aet.setDropDownMetaData(ev,parent.parentNode);
				}
				
				aet.setMetaData(title,fieldname,fieldvalue);
			}
		},
		
		getMetaData: function(title,extField){ 
			extField = extField.toLowerCase();
			var tiddler =  store.getTiddler(title);
			if(!tiddler) {
				return false;
			}
			else{
				if(!tiddler.fields[extField]){
					return false;
				}
				else{
					return tiddler.fields[extField];
				}
			}
		}
		
		,setMetaData: function(title,extField,extFieldVal){
		   
		    console.log("saving",title,extField,extFieldVal);
			extField = extField.toLowerCase();
			if(extFieldVal == "null") {
				extFieldVal = "";
			}
			var tiddler =  store.getTiddler(title);
			if(!tiddler) {
				store.saveTiddler(title,title,null,true,null,[],config.defaultCustomFields,null);
				tiddler =  store.getTiddler(title);
			}
			store.setValue(tiddler,extField,extFieldVal);	
			
		
		}
		,createDatePicker: function(place,title,metaDataName){
		        
		        var tiddler = store.getTiddler(title);
		        var params = [metaDataName];
		        
                        var div = document.createElement("div");
                        div.className  = "datePicker";
                        var input = document.createElement("input");
                        input.className = "date-pick";
                        jQuery(div).append(input);
                        jQuery(div).append("<div class='clearboth'></div>");
                        jQuery(place).append(div);
                        $(function()
                        {
                          var start =config.macros.AdvancedEditTemplate.getMetaData(title,metaDataName);
                          if(!start)start="";
                          else {
                            var y =start.substr(0,4);
                            var m = start.substr(4,2);
                            var d = start.substr(6,2)
                            start = d+"/"+m+"/"+y;
                          }
                          
                        	$(input).datePicker({startDate: '01/01/1600'}).val(start).trigger('change');
                        	$(input).change(function(e){
                        	    console.log(this.value,"before");
                        	    var dmy = this.value.split("/");
                        	    console.log(dmy,"after");
                        	    var d = dmy[0];
                        	    var m = dmy[1];
                        	    var y = dmy[2];
                        	    if(d.length == 1) d= "0"+d;
                        	    if(m.length == 1) m= "0"+m;
                        	    console.log(y,m,d,"togo");
                        	    config.macros.AdvancedEditTemplate.setMetaData(title,metaDataName,y+m+d+"0000");
                        	
                        	});
                        });
              
		        //config.macros.edit.handler(place,false,params,false,false,tiddler)
                        
		}
		,setupEmbeddedVideo: function(place){
		    place.append("video url:<input type='text' class='videoinput'/>");
		    jQuery(".videoinput",place).change(function(){
		        alert("cool");
		    });
		    
		}
		,createCheckBox: function(place,title,metaDataName){
		         
		        		var c = document.createElement("input");
		        		
					c.setAttribute("type","checkbox");
					c.value = "false";
					   //    alert("!");
	                               place.appendChild(c);
					var selected =this.getMetaData(title,metaDataName);
				
					if(!selected){
						var qsvalue =this.getVariableFromQueryString(metaDataName);
						if(qsvalue) selected = qsvalue;
					}
				
					if(selected){
					        c.value = selected;
					        c.checked = true;
					  
					        
					}
			
					var that = this;
					
					jQuery(c).click(function(e){
					     
						var taskTiddler = story.findContainingTiddler(place);
						var title = taskTiddler.getAttribute("tiddler");
						
						if(this.checked){
							that.setMetaData(title,metaDataName,"true");
						}
						else{
						  
							that.setMetaData(title,metaDataName,null);
						}
					});
						
					
		}
	};
	
	
	config.macros.AdvancedEditTemplate.EditTemplateFile = function(place,paramString,initial,handler,preview){
		this.init(place,paramString,initial,handler,preview);
	};
	config.macros.AdvancedEditTemplate.EditTemplateFile.prototype = {
		init: function(place,paramString,initial,handler,preview){
			var holder = document.createElement("div");
			holder.className = "AdvancedEditTemplateImage";
			//JON
			
			var imageholder = document.createElement("div");
			imageholder.className = "aet_ImageHolder";

			//image.src = initial;
			//image.alt = config.macros.aet.translate("aet_imgpreview");

			var params = paramString.parseParams("anon",null,true,false,false);
                	
			var root = getParam(params,"root", null);
			var connector = getParam(params,"browser", null);
			var uploader =getParam(params,"uploader",null);
			var home = "";
			place.appendChild(holder);
			if(preview){
			    holder.appendChild(imageholder);			
			    config.macros.viewimage.handler(imageholder,false,false,false,"maxwidth:200 maxheight:200 src:"+initial,tiddler);
			}

			

			
			var form = document.createElement("div");
			holder.appendChild(form);
			var filenameid = "filename_"+ Math.random();
            form.innerHTML = "<form target='aet_post_to' action='"+uploader+"?postbackto="+ filenameid +"' id='submitter' enctype='multipart/form-data' name='mysexyform' action='/ilga/upload/image' method='POST'>"+config.macros.aet.translate("aet_upload")+"url:<input type='text' id='"+filenameid+"' name='NewFilename' class='filename' value=''/><input type='file' class='file' id='NewFile' name='NewFile'/><input type='submit' value='Send'></form>";
         
            
            var jqFile = jQuery(".file",form);
			jqFile.change(function(e){
			    var newvalue = jQuery(e.target).val();
			    
			   jQuery(".filename",form).val(newvalue); 
			});
			  
                
			jQuery(holder).append("<div class='leftcol'></div><div class='rightcol'></div>");

			var filename = jQuery(".filename",form)[0];		
			filename.onchange = function(e){
				var newsrc = this.value;
				//image.src=  "";
				//image.src = newsrc;
				jQuery(imageholder).html("");
				config.macros.viewimage.handler(imageholder,false,false,false,"maxwidth:200 maxheight:200 src:"+newsrc,tiddler);
				if(handler)handler(newsrc);
			};
			if(initial)filename.value = initial;	
			jQuery(".rightcol",holder).append("<div class='browserarea' style='position:relative;'><input type='button' class='browsebutton' value='browse'><div class='filebrowser' style='position:absolute;display:none;z-index:200'></div></div>");
			var bb = jQuery(".browsebutton",holder);
			bb.click(function(e){
			    var browser =$(".filebrowser",$(this).parent());
			    browser.toggle();
		
			    browser.css({left:$(this).position().left});    
			})
			
			
			var browser = jQuery(".filebrowser");

			var r;
			if(!home) home = "";
			if(root) r =root; else r ="";
			/*browser.fileTree({ root: r, script: connector }, function(file) { 
						filename.value = file;
						filename.onchange();
			});*/
			
		}
	};
};
config.macros.aet = config.macros.AdvancedEditTemplate;

//}}}
document.styleSheets['vismoColorSlider'] = {cssText: ".vismoColorSliderMixBox {border:solid 1px black;}"};

var VismoColorSlider = function(wrapper,width,height,changefunction){	
	wrapper.style.position = "absolute";
	if(!changefunction){
		changefunction = function(newcolor){
			alert(newcolor + "is the new color. Please define a change function to replace this default function.");
		}
		this.setChangeFunction(changefunction);
	}
	
	//wrapper.style.position = "absolute";
	var sliderheight = height / 3;
	
	this.sliders = {};
	this.bar = {};
	this.sliders.red = this._createSlider(wrapper,width,sliderheight,"red");
	this.sliders.green =this._createSlider(wrapper,width,sliderheight,"green");
	this.sliders.blue = this._createSlider(wrapper,width,sliderheight,"blue");
	this.sliders.width = width;
	
	this.mixbox =this._createMixBox(wrapper,height,height);
	this.mixbox.style.left = parseInt(width + 5) + "px";
	
	this.inputfield = this._createInputField(wrapper,width,height);
	this.inputfield.style.top = parseInt((sliderheight * 3) + 5) + "px";
	this.rgb= {'red':0,'green':0,'blue':0};
	
};

VismoColorSlider.prototype = {
	setChangeFunction:function(change){
		this.changefunction = change;
	}
	,_createInputField: function(wrapper,width,height){
		var input= document.createElement("input");
		input.style.width = width + "px";
		input.style.height = height + "px";
		var ecs = this;
		input.onblur = function(e){
			ecs.setColor(this.value);
		}
		input.style.position = "absolute";
		wrapper.appendChild(input);
		return input;
	}
	/* thank you http://www.javascripter.net/faq/hextorgb.htm*/
	,_cutHex: function(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
	,_hexToR:function(h){return parseInt((this._cutHex(h)).substring(0,2),16)}
	,_hexToG: function (h) {return parseInt((this._cutHex(h)).substring(2,4),16)}
	,_hexToB:function(h) {return parseInt((this._cutHex(h)).substring(4,6),16)}
	
	
	,setColor: function(rgb){
		if(rgb.indexOf("#") == 0 && rgb.indexOf(",") == -1){ //hex code argument
			var hexcode = rgb.substring(1);
			this.rgb.red = this._hexToR(hexcode);
			this.rgb.blue = this._hexToB(hexcode);
			this.rgb.green = this._hexToG(hexcode);
		}
		else if(rgb.indexOf("rgb(") == 0){ //rgb argument
			var rgbstring = rgb.substring(4,rgb.length - 1);
			rgbstring = rgbstring.split(",");
			this.rgb.red = rgbstring[0];
			this.rgb.green = rgbstring[1];
			this.rgb.blue = rgbstring[2];
			
		}
		else{
			return false;
		}
	
		var redleft = parseFloat(this.rgb.red /255) * parseInt(this.sliders.width);
		var greenleft =  parseFloat(this.rgb.green /255) * parseInt(this.sliders.width);
		var blueleft = parseFloat(this.rgb.blue /255) * parseInt(this.sliders.width);
		//console.log(this.sliders.width,redleft,greenleft,blueleft,this.rgb,rgb);
		this.bar.red.style.left =  redleft + "px";
		this.bar.green.style.left = greenleft + "px";
		this.bar.blue.style.left =  blueleft  + "px";
		this.mixColors();
		
	}
	,getColor: function(){
		this.mixColors();
		return this.currentColor;
	}
	,mixColors: function(){
		var rgb  = "rgb("+this.rgb.red+","+ this.rgb.green+","+this.rgb.blue+")";
		this.currentColor = rgb;
		this.mixbox.style.background = rgb;
		this.inputfield.value = rgb;
		if(this.changefunction)this.changefunction(rgb);
	}
	,_createMixBox: function(wrapper,width,height){
		var s = document.createElement("div");
		s.className = "vismoColorSliderMixBox";
		s.style.position = "absolute";
		s.style.width = width + "px";
		s.style.height = height + "px";	
		wrapper.appendChild(s);
		return s;
				
	}
	,_createSlider: function(wrapper,width,height,color){
		var slidebar = document.createElement("div");
		slidebar.style.position = "absolute";
		slidebar.style.height = parseInt(height/2) + "px";
		slidebar.style.width = "2px";
		slidebar.style.background = "black";
		slidebar.style.border = "solid 1px black";
		var s = document.createElement("div");
		//s.innerHTML = color;
		s.style.position = "absolute";
		s.style.width = width + "px";
		s.style.height = height + "px";	
		s.style.background = color;
		s.className = "vismoColorSlider";
		var vismocolorslider = this;
		s.onmousedown = function(e){
			var pos =VismoClickingUtils.getMouseFromEventRelativeToTarget(e,this);
			var newleft =pos.x + this.style.left;
			slidebar.style.left = newleft + "px";
			var percentage = (pos.x / width)
			vismocolorslider.rgb[color] = parseInt(percentage * 255);		
			vismocolorslider.mixColors();	
		}
		wrapper.appendChild(s);
		wrapper.appendChild(slidebar);
		
		var top = 0;
		if(color =='red'){
			top = "0px";
			slidebar.style.top = top;
			s.style.top = top;
			this.bar.red = slidebar;
		}
		else if(color =='blue'){
			top =height * 2;
			slidebar.style.top = top+"px";
			s.style.top = top+"px";
			this.bar.blue = slidebar;
		}
		else if(color = 'green'){
			top =height +"px";
			slidebar.style.top = top;
			s.style.top = top;
			this.bar.green = slidebar;
		}
		return s;
	}
	
};var VismoClickingUtils = {
        //to be implemented..
        inVisibleArea: function(vismoCanvas,vismoShape){
                var bb = vismoShape.getBoundingBox();
                return true;
        }
        ,scrollXY: function(){
          var scrOfX = 0, scrOfY = 0;
          if( typeof( window.pageYOffset ) == 'number' ) {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
          } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
          } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
          }
          return {x: scrOfX,y: scrOfY};
        }
	,getRealXYFromMouse: function(e,t){
		var newpos =VismoClickingUtils.getMouseFromEvent(e);
		newpos = VismoClickingUtils.undotransformation(newpos.x,newpos.y,t);
		return newpos;
	}
	
	,undotransformation: function(x,y,transformation){ //porting to VismoTransformations?
		return VismoTransformations.undoTransformation(x,y,transformation);
	}	
	,resolveTarget:function(e)
	{
		if(!e) e = window.event;
		var obj;
		
		if(e && e.srcElement){
			obj = e.srcElement;
		}
	        else if(e.target)
        	        obj = e.target;
        	else{
	                obj = false;
	        }
	        try{
                        var x = obj.parentNode;
                }catch(e){return false;}
                /*
		if(obj && obj.nodeType && obj.nodeType == 3) // defeat Safari bug
			obj = obj.parentNode;
			*/
			
			/*try{
                                var x = obj.parentNode;
                        }
                        catch(e){return false;};*/
	        return obj;

		//return obj;
	}
	
	
	,getMouseFromEvent : function(e,target){
			if(!e) e = window.event;
			
			if(!target){
			       
			        var target = this.resolveTargetWithVismo(e);
			        if(!target)return false;
                        }
                        
			var offset = jQuery(target).offset();
               
                        var i;
          
			if(typeof(offset.left) != 'number') return false;
		
		        var scroll = this.scrollXY(e);
			x = e.clientX + scroll.x;
			y = e.clientY + scroll.y;
			//alert(x +"/"+y);
			x -= offset.left;
			y-=  offset.top;
			
			return {'x':x, 'y':y};		
			
	}
	,getMouseFromEventRelativeToTarget : function(e,target){
			if(!e) e = window.event;
			if(!target)return false;

			var offset = jQuery(target).offset();

			
			if(!offset.left) return false;
			var scroll = this.scrollXY();
			x = e.clientX + scroll.x - offset.left;
			y = e.clientY + scroll.y - offset.top;
			return {'x':x, 'y':y};		
			
	}

	,resolveTargetWithVismo: function(e)
	{
		var node = VismoClickingUtils.resolveTarget(e);
                

                
		if(!node)return false;
		var hasVismo = false;
     
                
		while(!hasVismo && node != document && node.parentNode && node.parentNode != document){
		        
		        if(node.vismoCanvas || node.vismoController || node.vismoClicking){
		                hasVismo = true;
			}
			else{
			        node= node.parentNode;
			}
		}
		
		if(!node) return false;
		return node;
	}
	,getMouseFromEventRelativeToElement: function (e,x,y,target){
		if(!e) e = window.event;

		var offset = jQuery(target).offset();
		if(!offset.left) return false;
		
		var scroll = this.scrollXY();
		oldx = e.clientX + scroll.x - offset.left;
		oldy = e.clientY + scroll.y - offset.top;
		var pos = {'x':oldx, 'y':oldy};

		if(!pos) return false;
		pos.x -= x;
		pos.y -= y;
		

		return pos;
		
	}

	,getMouseFromEventRelativeTo: function (e,x,y){
	
		var pos = this.getMouseFromEvent(e);
		if(!pos) return false;
		pos.x -= x;
		pos.y -= y;

		return pos;
	
	}
	,getMouseFromEventRelativeToElementCenter: function(e){ /*redundant?? */
		var w,h;
		var target = this.resolveTargetWithVismo(e);
		if(!target)return;
		if(target.style.width)
			w = parseInt(target.style.width);
		else if(target.width)
			w =parseInt(target.width);

		if(target.style.height)
			h = parseInt(target.style.height);
		else if(target.height)
			h = parseInt(target.height);
	
		if(!w || !h) throw "target has no width or height (vismomaputils)";
	
		return this.getMouseFromEventRelativeTo(e,w/2,h/2);
	}	
	

};

/* JQUERY PLUGINS GO HERE! */

/*
 * 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 jQuery
 * @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(
						jQuery(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 = jQuery(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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery
 * @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 jQuery 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);


// jQuery File Tree Plugin
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 24 March 2008
//
// Visit http://abeautifulsite.net/notebook.php?article=58 for more information
//
// Usage: $('.fileTreeDemo').fileTree( options, callback )
//
// Options:  root           - root folder to display; default = /
//           script         - location of the serverside AJAX file to use; default = jqueryFileTree.php
//           folderEvent    - event to trigger expand/collapse; default = click
//           expandSpeed    - default = 500 (ms); use -1 for no animation
//           collapseSpeed  - default = 500 (ms); use -1 for no animation
//           expandEasing   - easing function to use on expand (optional)
//           collapseEasing - easing function to use on collapse (optional)
//           multiFolder    - whether or not to limit the browser to one subfolder at a time
//           loadMessage    - Message to display while initial tree loads (can be HTML)
//
// History:
//
// 1.01 - updated to work with foreign characters in directory/file names (12 April 2008)
// 1.00 - released (24 March 2008)
//
// TERMS OF USE
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
if(jQuery) (function($){
	
	$.extend($.fn, {
		fileTree: function(o, h) {
			// Defaults
			if( !o ) var o = {};
			if( o.root == undefined ) o.root = '/';
			if( o.script == undefined ) o.script = 'jqueryFileTree.php';
			if( o.folderEvent == undefined ) o.folderEvent = 'click';
			if( o.expandSpeed == undefined ) o.expandSpeed= 500;
			if( o.collapseSpeed == undefined ) o.collapseSpeed= 500;
			if( o.expandEasing == undefined ) o.expandEasing = null;
			if( o.collapseEasing == undefined ) o.collapseEasing = null;
			if( o.multiFolder == undefined ) o.multiFolder = true;
			if( o.loadMessage == undefined ) o.loadMessage = 'Loading...';
			
			$(this).each( function() {
				
				function showTree(c, t) {
					$(c).addClass('wait');
					$(".jqueryFileTree.start").remove();
					
					if(window.Components && window.netscape && window.netscape.security && document.location.protocol.indexOf("http") == -1)
						window.netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
					
					//changed from post to get
					$.post(o.script, { dir: t }, function(data) {
						$(c).find('.start').html('');
						$(c).removeClass('wait').append(data);
						if( o.root == t ) $(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
						bindTree(c);
					});
				}
				
				function bindTree(t) {
					$(t).find('LI A').bind(o.folderEvent, function() {
						if( $(this).parent().hasClass('directory') ) {
							if( $(this).parent().hasClass('collapsed') ) {
								// Expand
								if( !o.multiFolder ) {
									$(this).parent().parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
									$(this).parent().parent().find('LI.directory').removeClass('expanded').addClass('collapsed');
								}
								$(this).parent().find('UL').remove(); // cleanup
								showTree( $(this).parent(), escape($(this).attr('rel').match( /.*\// )) );
								$(this).parent().removeClass('collapsed').addClass('expanded');
							} else {
								// Collapse
								$(this).parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
								$(this).parent().removeClass('expanded').addClass('collapsed');
							}
						} else {
							h($(this).attr('rel'));
						}
						return false;
					});
					// Prevent A from triggering the # on non-click events
					if( o.folderEvent.toLowerCase != 'click' ) $(t).find('LI A').bind('click', function() { return false; });
				}
				// Loading message
				$(this).html('<ul class="jqueryFileTree start"><li class="wait">' + o.loadMessage + '<li></ul>');
				// Get the initial file list
				showTree( $(this), escape(o.root) );
			});
		}
	});
	
})(jQuery);


/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
 *
 */
 /* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
  * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
  * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
  *
  * $LastChangedDate: 2007-07-22 01:45:56 +0200 (Son, 22 Jul 2007) $
  * $Rev: 2447 $
  *
  * Version 2.1.1
  */
 (function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);
 
 
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(3($){$.31.1o({12:3(b,d){5 c=Y b=="1w";d=$.1o({},$.D.1L,{11:c?b:14,w:c?14:b,1D:c?$.D.1L.1D:10,Z:d&&!d.1x?10:3U},d);d.1t=d.1t||3(a){6 a};d.1q=d.1q||d.1K;6 I.K(3(){1E $.D(I,d)})},M:3(a){6 I.X("M",a)},1y:3(a){6 I.15("1y",[a])},20:3(){6 I.15("20")},1Y:3(a){6 I.15("1Y",[a])},1X:3(){6 I.15("1X")}});$.D=3(o,r){5 t={2N:38,2I:40,2D:46,2x:9,2v:13,2q:27,2d:3x,2j:33,2o:34,2e:8};5 u=$(o).3f("12","3c").P(r.24);5 p;5 m="";5 n=$.D.2W(r);5 s=0;5 k;5 h={1z:B};5 l=$.D.2Q(r,o,1U,h);5 j;$.1T.2L&&$(o.2K).X("3S.12",3(){4(j){j=B;6 B}});u.X(($.1T.2L?"3Q":"3N")+".12",3(a){k=a.2F;3L(a.2F){Q t.2N:a.1d();4(l.L()){l.2y()}A{W(0,C)}N;Q t.2I:a.1d();4(l.L()){l.2u()}A{W(0,C)}N;Q t.2j:a.1d();4(l.L()){l.2t()}A{W(0,C)}N;Q t.2o:a.1d();4(l.L()){l.2s()}A{W(0,C)}N;Q r.19&&$.1p(r.R)==","&&t.2d:Q t.2x:Q t.2v:4(1U()){a.1d();j=C;6 B}N;Q t.2q:l.U();N;3A:1I(p);p=1H(W,r.1D);N}}).1G(3(){s++}).3v(3(){s=0;4(!h.1z){2k()}}).2i(3(){4(s++>1&&!l.L()){W(0,C)}}).X("1y",3(){5 c=(1n.7>1)?1n[1]:14;3 23(q,a){5 b;4(a&&a.7){16(5 i=0;i<a.7;i++){4(a[i].M.O()==q.O()){b=a[i];N}}}4(Y c=="3")c(b);A u.15("M",b&&[b.w,b.H])}$.K(1g(u.J()),3(i,a){1R(a,23,23)})}).X("20",3(){n.18()}).X("1Y",3(){$.1o(r,1n[1]);4("w"2G 1n[1])n.1f()}).X("1X",3(){l.1u();u.1u();$(o.2K).1u(".12")});3 1U(){5 b=l.26();4(!b)6 B;5 v=b.M;m=v;4(r.19){5 a=1g(u.J());4(a.7>1){v=a.17(0,a.7-1).2Z(r.R)+r.R+v}v+=r.R}u.J(v);1l();u.15("M",[b.w,b.H]);6 C}3 W(b,c){4(k==t.2D){l.U();6}5 a=u.J();4(!c&&a==m)6;m=a;a=1k(a);4(a.7>=r.22){u.P(r.21);4(!r.1C)a=a.O();1R(a,2V,1l)}A{1B();l.U()}};3 1g(b){4(!b){6[""]}5 d=b.1Z(r.R);5 c=[];$.K(d,3(i,a){4($.1p(a))c[i]=$.1p(a)});6 c}3 1k(a){4(!r.19)6 a;5 b=1g(a);6 b[b.7-1]}3 1A(q,a){4(r.1A&&(1k(u.J()).O()==q.O())&&k!=t.2e){u.J(u.J()+a.48(1k(m).7));$.D.1N(o,m.7,m.7+a.7)}};3 2k(){1I(p);p=1H(1l,47)};3 1l(){5 c=l.L();l.U();1I(p);1B();4(r.2U){u.1y(3(a){4(!a){4(r.19){5 b=1g(u.J()).17(0,-1);u.J(b.2Z(r.R)+(b.7?r.R:""))}A u.J("")}})}4(c)$.D.1N(o,o.H.7,o.H.7)};3 2V(q,a){4(a&&a.7&&s){1B();l.2T(a,q);1A(q,a[0].H);l.1W()}A{1l()}};3 1R(f,d,g){4(!r.1C)f=f.O();5 e=n.2S(f);4(e&&e.7){d(f,e)}A 4((Y r.11=="1w")&&(r.11.7>0)){5 c={45:+1E 44()};$.K(r.2R,3(a,b){c[a]=Y b=="3"?b():b});$.43({42:"41",3Z:"12"+o.3Y,2M:r.2M,11:r.11,w:$.1o({q:1k(f),3X:r.Z},c),3W:3(a){5 b=r.1r&&r.1r(a)||1r(a);n.1h(f,b);d(f,b)}})}A{l.2J();g(f)}};3 1r(c){5 d=[];5 b=c.1Z("\\n");16(5 i=0;i<b.7;i++){5 a=$.1p(b[i]);4(a){a=a.1Z("|");d[d.7]={w:a,H:a[0],M:r.1v&&r.1v(a,a[0])||a[0]}}}6 d};3 1B(){u.1e(r.21)}};$.D.1L={24:"3R",2H:"3P",21:"3O",22:1,1D:3M,1C:B,1a:C,1V:B,1j:10,Z:3K,2U:B,2R:{},1S:C,1K:3(a){6 a[0]},1q:14,1A:B,E:0,19:B,R:", ",1t:3(b,a){6 b.2C(1E 3J("(?![^&;]+;)(?!<[^<>]*)("+a.2C(/([\\^\\$\\(\\)\\[\\]\\{\\}\\*\\.\\+\\?\\|\\\\])/2A,"\\\\$1")+")(?![^<>]*>)(?![^&;]+;)","2A"),"<2z>$1</2z>")},1x:C,1s:3I};$.D.2W=3(g){5 h={};5 j=0;3 1a(s,a){4(!g.1C)s=s.O();5 i=s.3H(a);4(i==-1)6 B;6 i==0||g.1V};3 1h(q,a){4(j>g.1j){18()}4(!h[q]){j++}h[q]=a}3 1f(){4(!g.w)6 B;5 f={},2w=0;4(!g.11)g.1j=1;f[""]=[];16(5 i=0,30=g.w.7;i<30;i++){5 c=g.w[i];c=(Y c=="1w")?[c]:c;5 d=g.1q(c,i+1,g.w.7);4(d===B)1P;5 e=d.3G(0).O();4(!f[e])f[e]=[];5 b={H:d,w:c,M:g.1v&&g.1v(c)||d};f[e].1O(b);4(2w++<g.Z){f[""].1O(b)}};$.K(f,3(i,a){g.1j++;1h(i,a)})}1H(1f,25);3 18(){h={};j=0}6{18:18,1h:1h,1f:1f,2S:3(q){4(!g.1j||!j)6 14;4(!g.11&&g.1V){5 a=[];16(5 k 2G h){4(k.7>0){5 c=h[k];$.K(c,3(i,x){4(1a(x.H,q)){a.1O(x)}})}}6 a}A 4(h[q]){6 h[q]}A 4(g.1a){16(5 i=q.7-1;i>=g.22;i--){5 c=h[q.3F(0,i)];4(c){5 a=[];$.K(c,3(i,x){4(1a(x.H,q)){a[a.7]=x}});6 a}}}6 14}}};$.D.2Q=3(e,g,f,k){5 h={G:"3E"};5 j,y=-1,w,1m="",1M=C,F,z;3 2r(){4(!1M)6;F=$("<3D/>").U().P(e.2H).T("3C","3B").1J(2p.2n);z=$("<3z/>").1J(F).3y(3(a){4(V(a).2m&&V(a).2m.3w()==\'2l\'){y=$("1F",z).1e(h.G).3u(V(a));$(V(a)).P(h.G)}}).2i(3(a){$(V(a)).P(h.G);f();g.1G();6 B}).3t(3(){k.1z=C}).3s(3(){k.1z=B});4(e.E>0)F.T("E",e.E);1M=B}3 V(a){5 b=a.V;3r(b&&b.3q!="2l")b=b.3p;4(!b)6[];6 b}3 S(b){j.17(y,y+1).1e(h.G);2h(b);5 a=j.17(y,y+1).P(h.G);4(e.1x){5 c=0;j.17(0,y).K(3(){c+=I.1i});4((c+a[0].1i-z.1c())>z[0].3o){z.1c(c+a[0].1i-z.3n())}A 4(c<z.1c()){z.1c(c)}}};3 2h(a){y+=a;4(y<0){y=j.1b()-1}A 4(y>=j.1b()){y=0}}3 2g(a){6 e.Z&&e.Z<a?e.Z:a}3 2f(){z.2B();5 b=2g(w.7);16(5 i=0;i<b;i++){4(!w[i])1P;5 a=e.1K(w[i].w,i+1,b,w[i].H,1m);4(a===B)1P;5 c=$("<1F/>").3m(e.1t(a,1m)).P(i%2==0?"3l":"3k").1J(z)[0];$.w(c,"2c",w[i])}j=z.3j("1F");4(e.1S){j.17(0,1).P(h.G);y=0}4($.31.2b)z.2b()}6{2T:3(d,q){2r();w=d;1m=q;2f()},2u:3(){S(1)},2y:3(){S(-1)},2t:3(){4(y!=0&&y-8<0){S(-y)}A{S(-8)}},2s:3(){4(y!=j.1b()-1&&y+8>j.1b()){S(j.1b()-1-y)}A{S(8)}},U:3(){F&&F.U();j&&j.1e(h.G);y=-1},L:3(){6 F&&F.3i(":L")},3h:3(){6 I.L()&&(j.2a("."+h.G)[0]||e.1S&&j[0])},1W:3(){5 a=$(g).3g();F.T({E:Y e.E=="1w"||e.E>0?e.E:$(g).E(),2E:a.2E+g.1i,1Q:a.1Q}).1W();4(e.1x){z.1c(0);z.T({29:e.1s,3e:\'3d\'});4($.1T.3b&&Y 2p.2n.3T.29==="3a"){5 c=0;j.K(3(){c+=I.1i});5 b=c>e.1s;z.T(\'3V\',b?e.1s:c);4(!b){j.E(z.E()-28(j.T("32-1Q"))-28(j.T("32-39")))}}}},26:3(){5 a=j&&j.2a("."+h.G).1e(h.G);6 a&&a.7&&$.w(a[0],"2c")},2J:3(){z&&z.2B()},1u:3(){F&&F.37()}}};$.D.1N=3(b,a,c){4(b.2O){5 d=b.2O();d.36(C);d.35("2P",a);d.4c("2P",c);d.4b()}A 4(b.2Y){b.2Y(a,c)}A{4(b.2X){b.2X=a;b.4a=c}}b.1G()}})(49);',62,261,'|||function|if|var|return|length|||||||||||||||||||||||||data||active|list|else|false|true|Autocompleter|width|element|ACTIVE|value|this|val|each|visible|result|break|toLowerCase|addClass|case|multipleSeparator|moveSelect|css|hide|target|onChange|bind|typeof|max||url|autocomplete||null|trigger|for|slice|flush|multiple|matchSubset|size|scrollTop|preventDefault|removeClass|populate|trimWords|add|offsetHeight|cacheLength|lastWord|hideResultsNow|term|arguments|extend|trim|formatMatch|parse|scrollHeight|highlight|unbind|formatResult|string|scroll|search|mouseDownOnSelect|autoFill|stopLoading|matchCase|delay|new|li|focus|setTimeout|clearTimeout|appendTo|formatItem|defaults|needsInit|Selection|push|continue|left|request|selectFirst|browser|selectCurrent|matchContains|show|unautocomplete|setOptions|split|flushCache|loadingClass|minChars|findValueCallback|inputClass||selected||parseInt|maxHeight|filter|bgiframe|ac_data|COMMA|BACKSPACE|fillList|limitNumberOfItems|movePosition|click|PAGEUP|hideResults|LI|nodeName|body|PAGEDOWN|document|ESC|init|pageDown|pageUp|next|RETURN|nullData|TAB|prev|strong|gi|empty|replace|DEL|top|keyCode|in|resultsClass|DOWN|emptyList|form|opera|dataType|UP|createTextRange|character|Select|extraParams|load|display|mustMatch|receiveData|Cache|selectionStart|setSelectionRange|join|ol|fn|padding|||moveStart|collapse|remove||right|undefined|msie|off|auto|overflow|attr|offset|current|is|find|ac_odd|ac_even|html|innerHeight|clientHeight|parentNode|tagName|while|mouseup|mousedown|index|blur|toUpperCase|188|mouseover|ul|default|absolute|position|div|ac_over|substr|charAt|indexOf|180|RegExp|100|switch|400|keydown|ac_loading|ac_results|keypress|ac_input|submit|style|150|height|success|limit|name|port||abort|mode|ajax|Date|timestamp||200|substring|jQuery|selectionEnd|select|moveEnd'.split('|'),0,{}))

})(jQuery); //end alias






Marriage is license.
	Widow of William Buckley of New Tame. Date of death is burial date.




Married Scholefield.
Died aged 62 years.





Married Thomas Murphy in 1851




m. Michael J WILFORD 1960

	(5 children: Karenna, Carl Adrian, Paul Newton, Jane Anne, Anna Patricia)


Possible surnames:
	Forster /Foster (middle name passed down)
	Shearer (married Joseph Robson Jun 1841 Durham area)
	Bell

	If surname = Foster then Daughter of Robert Foster.
Wife of James Buckley of Heys in Crompton. Married 8 Jun 1738,
	His will proved 1759.
m. William CLARK
Three children: James Mary and ?





Lecturer. Married at Harrow Register Office.
Could be James Banks as this person is referred to in one letter? However Joseph Jackson writes in a letter to Adam Lyall (uncle) " Father is working with brother Bankes and I is working with brother Henry"

Died aged 67. Will proved 1 Oct 1813. Inherited Ocknell Lee and purchased Bowhouse from Jonah Buckley in 1876. Married at St Chad, Rochdale.
Baptised 15 Oct 1715.
	Inherited one sixteenth part of Bakestone pit from father and purchased another sixteenth from brother James 8 Nov 1781.
	Purchased Heyhouse in Denshaw from Timothy Buckley in 1792.
	Will proved 11 May 1795.


[img[files/brianboru.jpg]]
This King is the oldest member of my family tree. I will show you how you get from him to Robson at a later date. I'm still in progress of updating the information here.

Reigned 66 years, 12 as Monarch. He was 88 when slain at Clontarf. After his death in 1014, Malachi II was restored to the Monarchy and he ruled till his death in 1023.

Brian Bórúma mac Cennetig, known popularly as Brian Bórú, is undoubtedly the most well known ard-rí (ARD-ree) or High King of Ireland of Ireland and arguably the only ard-rí who, like Ælfred the Great of England, actually controlled the entire country.

Brian Bórú was born circa 941 at Béal Bórú (from which he received his name), near Killaloe, County Clare, at a time when the Norse had secured many seaports and frequently plundered and harried the neighbouring countryside. In 976 he succeeded his brother Mathúin as king of Dál gCais and claimant to the kingship of Munster. By 999, after a series of wars, he was acknowledged as High King of Ireland.

Brian Boruma mac Cennetig, known popularly as Brian Boru, is undoubtedly the most well known high king of Ireland. He held the title ard-ri Gaidel Erenn, Gall, Bretan, August iarthair tuaiscirt Eorpa uile (high king of the Irish of Ireland and of the Foreigners and the Welsh, the Augustus of the whole north-west Europe) from the year 1002 until his death at the battle of Clontorf in 1014 (Byrne 257). Boru's reputation as an innovative, disciplined warrior or chieftain confirmed by his many successes in battle, may have ultimately transformed him into an arrogant, selfish tyrant in his later years.

In the 900's the government of Munster was to be shared, with alternating rule between the southern Eoghanist clan and the northern Delcassian clan. The south had control for some time and were attempting to keep the rights of succession from the southern Delcassian. It was Brian Boru's grandfather, Lorcan mac Lachtna, king of Thomond and of historic O'Brien lineage, who would strive to bring the government of Munster back to the Delcassian clan. Lachtna's son, Cennetig, succeeded his father and attained kingship of Munster. Brian Boru, born during the 930's, was one of many sons of Cennetig. Cennetig taught his sons to live by the pledge of valor of the Delcassian tribe: first to the battlefield and the last to leave. 

In 960 Mahoun, the oldest son of Cennetig, obtained the crown of Munster (Cusack 121). Brian was given rule over Thomond, Northern Munster. During his reign, Mahoun sought to secure peace with the Vikings that had invaded Ireland in 793 and who were still living among the Irish (Foster 30). Small guerrilla activities against Mahoun's province were becoming a nuisance, but rather than countering their attacks, Mahoun preferred to amicably settle with the Viking rulers. Brian disagreed with his brother, urging armed violent retaliation.

Brian reproached Mahoun with cowardice; Mahoun reproached Brian with imprudence. Brian hints broadly that Mahoun had interested motives in making this truce, and declares that neither Cennetig their father, nor Lorcan their grandfather, would have been quite so quiescent towards the foreigners for the sake of wealth, nor would they have given them as much time as would have sufficed to play a game of chess on the green of Mogadare. Mahoun kept his temper, and contented himself with reproaching Brian for his recklessness, in sacrificing the lives of so many of his faithful followers to no purpose. Brian replied that he would never abandon his inheritance, without a contest to "such foreigners as Black Grim Gentiles." (Cusack 122)

Mahoun agreed to hold a conference among his followers and they all agreed with Brian that they should declare war on their enemies. Brian consulted the nobles of the Delcassian and Eoghanist clans concerning strategies and logistics. He held musters to assemble and asses the strength of the forces and he designated the most worthy soldiers as unit leaders (Flanagan 53). United, the two clans defeated the Danes of Limerick and collected a remarkable amount of loot, which included young girls and women. This great victory was one of the first indications of Brian's true military genius. Brian's supporters, who had placed faith in his reputation as a determined and disciplined warrior, now had proof that he was capable of great feats. Perhaps he could unite Ireland under one kingdom.

Mahoun's armies, under Brian's direction, had many victories. Mahoun now had complete control over Munster and he made it clear to everyone in his province that he would never relinquish his position. The brothers' rule seemed invulnerable, their confidence made them arrogant. The Eoghanists withdrew their support and merged with their recent enemies, the Danes, in the assassination of Mahoun. Mahoun was invited to the house of Donovan, an Eoghanist prince that shared his own ancestors, and "in violation of the rights of hospitality" he was brutally murdered by Donovan and Moalmua, another prince of the region (Cusack 123). The assassins had forgotten Brian's ruthless nature and were not prepared for what was to come.

Brian assumed the crown and moved the kingship to Kincora, now known as Killaloe. In his first act as King of Munster he would avenge his brother's death. Driving straight into their territories, Brian's forces were able to destroy the majority of the princes' armies. Donovan was killed during the battle, but significantly, it was Brian's son, Morrough, who encountered Moalmua and had the glory of sacrificing him on the same spot as his murdered uncle (Moore 196). While still engaged in retribution against the Eoghanists, Brian committed armies to the isle of Iniscathy to retake possession of the land from the Danes who had been struggling without the aid of the Danes of Limerick. With another success in Iniscathy, he decided to push onto the remaining islands of the Shannon, plundering and devastating the remains of the Danes. Land and naval forces were summoned as part of the coordinated strategy of attacks successfully used by Brian (Flanagan 54).

In 984, Brian was given title as ruler of Leth Mogha, the southern half of Ireland. His reputation had preceded him throughout Ireland. Brian fought battles against the Danes at Tara, homeland to the ancient kings of Ireland, and besieges Dublin in 999. Brian was able to maintain a military presence in Dublin during the winter months after blocking all passages into the city and demolishing all foreign fortresses. Brian sought hostages and all the spoils of the city as tribute that would prevent further devastation. Brian's forces prove that a successful campaign is not dependent only on victories on the battlefield, but also on the their ability to maintain all strategic positions.

Brian expanded his authority into northern Ireland and to secure his position there he gave his daughter away in marriage to Sitric Silkbeard, King of Viking Dublin. Brian completed the family alliance by marrying Sitric's mother, Gormflaith, who had been divorced from her second husband, Malachy. Malachy and Brian had been in constant conflict with one another over the past years, each defeating the other in successive battles for control. Malachy was Brian's only obstacle to obtaining the crown of all of Ireland, and with Brian's new ally in the Vikings of Ireland, this obstacle would be easily overcome. Malachy, tired of the bloody battles, finally yielded to Brian, becoming one of his vassals.

In 1102, Brian marches into Tara again, this time not to fight but to be acknowledged as the High King (Ard-Righ) of all Ireland (Moore 202). Though he is known as a tyrant for his violent methods of persuasion, Brian had done more than any other person in the early history of Ireland to unite the people of the land. In his first years as the supreme sovereign of Ireland, he was credited with the rebuilding of schools and monasteries , which improved communication throughout the country.

Brian still required tributes, in any form, from the smaller kings and nobles in his domain, and for this he would provide them with protection from outside forces. During a visit by which Gormflaith's brother, Maelmurra (King of Leinster), was bringing his tributes to Brian in the form of pine to be used as masts for naval ships, Maelmurra was said to be deeply insulted by Brian's son Morrough. He left Kincora in a rage, and soon had his clan "roused to avenge the insults offered to their chief" (Cusack 129). With the help of the O'Rourkes, O'Niels, O'Flahertys and the Kearys, Maelmurra attacked homes throughout Brian's realm. The O'Rourkes attacked Malachy and killed his grandson Drumale, the heir-apparent. After his few good deeds in the reparation of Ireland, Brian easily returned to his vengeful, bloody battles against those who did not bow to his authority. Brian's armies stockaded Dublin for three months, and during Brian's absence Gormflaith grew angry at him for leaving her alone. She left Kincora and joined her brother Maelmurra and her son Sitric. Gormflaith and Maelmurra persuaded Sitric to rally his Viking allies from Scandinavia, to aid them in seizing the crown of Ireland from Brian. Sitric offered the treasure of his mother, Gormflaith, in marriage to anyone who could kill Brian.

The battle for the crown was to take place in Clontarf, four miles north of modern Dublin. Brian's forces plundered and destroyed every foreign town as they traveled to the site of the battle. The Battle of Clontarf began at sunrise on Good Friday, the 23rd of April, 1014. The 21,000 men of Brian's enemy was made up of Danes, Norwegians, Leinster men and other foreign auxiliaries. Brian's forces consisted of Dalcassians and the troops and nobles from Munster and Connaught. Brian, now an old man in his 80's, stayed in his tent praying as the battle ensued.

The battle was said to be "so fierce that in places the trees wept blood and the nearby River Tolka turned red" (O'Kelly). Brian, while sitting in his tent, foresaw his death even though the battle was in his favor, and he gave his attendant his will to be conveyed to his son, Donnough.

The security of the tent by Brian's forces was not maintained and a group of Danes retreating from the battle came upon Brian, kneeling in prayer, and their leader Brodir "opened his head with his battle axe" (Cusack 136). Brodir was slain immediately by the guards who had neglected their post outside the tent. The battle was ultimately won by Brian's forces. His wake ( ecnaire ) lasted 12 nights.

The Irish believe that no one deserves a place in history until the "durability of his achievements has been attested by the success of his great-grandchildren" (Byrne 70). Brian Boru has earned his place in history books because the O'Briens were able to maintain the kingship in Kincora for two centuries after the battle of Clontarf. He is remembered even today with his name being used for Irish pubs, beers, music bands and in their songs, and probably most amusing as the name of a champion Labrador.

The Battle of Clontarf

Brian Boru's reign was marked by continuous opposition. This came to a head in the early eleventh century. Máel Mórda, the king of Leinster, made an alliance with the Dublin Norse under Sigurd, Earl of Orkney and their overseas allies. Brian's forces defeated this union at Clontarf, about four miles north of modern Dublin, on Good Friday, April 23, 1014.  Brian, too aged to fight, was awaiting news of the battle when he was slain in his tent by a Viking intruder. The battle of Clontarf marked the end of any major Viking involvement in Irish wars.

From this point on, the role of the Norsemen in Ireland was largely peaceful, and they intermarried with the Irish and concentrated on developing trade.  However, with the death of Brian Bórú in 1014, Ireland once again became an island of conflicting dynasties, with the High King unable to enforce acceptance by all the provinces.




Unconfirmed.





Charles was created Viscount Cullen in 1642.
	From: "Parishes: Bishop Middleham", A History of the County of Durham: Volume 3 (1928), pp. 204-12. URL: http://www.british-history.ac.uk/report.asp?compid=42621. Date accessed: 07 August 2006.

Date of marriage is unconfirmed and could be wrong. Place of suspected marriage was Llanelli.

	In 1901 census he is living at Holden Road, Wednesbury, Staffordshire:
	Civil parish: Wednesbury
	Ecclesiastical parish: St John
	County/Island: Staffordshire
	Country: England 

	Charles H Newton abt 1866 Cradley, Worcestershire, England Head Wednesbury Staffordshire
	Gladys Newton abt 1900 Trimsaran, Carmarthenshire, Wales Daughter Wednesbury Staffordshire
	Isabel Newton abt 1867 Middlesborough, Yorkshire, England Wife Wednesbury Staffordshire
	John R Newton abt 1899 Trimsaran, Carmarthenshire, Wales Son Wednesbury Staffordshire
	Maria Newton abt 1864 Crudley, Worcestershire, England Sister Wednesbury Staffordshire
	John G Robson abt 1885 Workington, Cumberland, England Cousin-in-law Wednesbury Staffordshire
	Sarah Sudler abt 1884 Trimsaran, Carmarthenshire, Wales Servant Wednesbury

	Interesting John G is incorrectly stated as a cousin-in-law. He should be a brother in law.
Charles Robson Bellwood
b. 1880 (7 months old at time of 1881 census) Middlesbro
	Christine Lyall THOMAS (1945-)
m. David Edward BLACKMAN (1944-) 24/05/69
m. Robert John Anderson (1938-) 24/07/92 

Possibly also married Eveleen MacCarthy










<<bootUpFamilyTree>>






<!--{{{-->
<div class='tiddlerContainer'>
<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='tagsection'>
tags:<span class='editor' macro='niceTagger'></span>
</div>
<h1>Family Tree Specific</h1>
sex (M or F): <div class='editor' macro='AdvancedEditTemplate metaDataName:sex type:radio valuesSource:sexDefinition'></div>
date of birth:<div class='editor' macro='edit dob'></div>
place of birth:<div class='editor' macro='edit placeofbirth'></div>
mother:<div class='editor' macro='aet type:search metaDataName:mother valuesSource:ListOfWomen wikify:yes'></div>
father:<div class='editor' macro='aet type:search metaDataName:father valuesSource:ListOfMen wikify:yes'></div>
spouse:<div class='editor' macro='edit spouse'></div>
date of marriage: <div class='editor' macro='aet type:date metaDataName:dom'></div>
where did they get married: <div class='editor' macro='edit placeofmarriage'></div>

occupation:<div class='editor' macro='edit occupation'></div>
date of death:<div class='editor' macro='edit dod'></div>
What did he/she die of?<div class='editor' macro='edit causeofdeath'></div>
where did they die?<div class='editor' macro='edit placeofdeath'></div>
</div>
<!--}}}-->





A letter is in possession of the family from an Edward Robson writing from Sydney Mines,Cape Breton (an Island off Canada not to be confused with Australia). It is unknown who he is writing to or how he is related. He addresses the recipitent as "Sir". He writes about Canada and a murder trial.

	It is unknown how he is connected to the family, but one would guess he could possibly be a brother or cousin to [[Robert Robson]].

Christened 1822-09-29

Christened 12 APR 1846 Wingate, Durham, England according to an IGI Individual Record on familysearch.org. In the IGI Individual Record the name is spelt "Elizabeth Anne Lyill" - a mistake?
	It states her mother as Isabella and her father as Adam.

	In 1881 she can be found living with her mother, sister and her niece. She is unlikely to have married.
Married 7 January 1838
was christened in Chepstow on 27 November 1836, and died on 1 January 1838 


Buried 20 July 1729. 
	Admin 1730.
	Wife of John Lees of Hilltop, Yeoman.
	Wife of James Hohnson of Worsley, tanner. Married 9 Jan 1739.


Daughter of Robert Rees.
Married in Hartlepool 
















{{{
var tiddlers =store.getTiddlers();for(var i=0; i < tiddlers.length; i++){var tid=tiddlers[i]; if(tid.fields.father== '612') tid.fields.father ="Adam Jackson";}
var tiddlers =store.getTiddlers();for(var i=0; i < tiddlers.length; i++){var tid=tiddlers[i]; if(tid.fields.mother== '620') tid.fields.mother ="Mary UNKNOWN";}

}}}

!My trees

[[John David Bagg]]
[[Edmund Bentley]]
[[Brian Boru King of Ireland]]
[[Thomas Bellwood]]
[[John Brew (1765)]]
[[James Bulmer]]
[[John Cokayne]]
[[Frieda Gartside]]
[[Herbert Hunter]]
[[Matthew Jackson]]
[[Adam Lyall]]
[[Turlogh (Prince of Thomond, Ireland) O BRIEN]]
[[John Oxe]]
[[John Robson]]
[[Gilbert SPEARMAN]]
[[Robert PEARSON]]

!To do
rename tiddler updates fields in children and there children etc.. owch!
/***
|''Name:''|FamilyTreePlugin|
|''Description:''|Creates basic graphical representation of a family tree in TiddlyWiki |
|''Version:''|0.1|
|''Date:''|October 09|
|''Source:''|http://www.jonrobson.me.uk|
|''Author:''|Jon Robson |
|''Contributors:''|uses code from ECO Tree http://www.codeproject.com/KB/scripting/graphic_javascript_tree.aspx#quick|
|''License:''|[[BSD open source license]]|
|''CoreVersion:''|2.3|

Allows the adding of multiple level drop down menus and checkboxes to the edit template.
***/

var FamilyTreeInstance;
config.macros.FamilyTree = {
    tooltip:function(){
    
    }
    ,handler: function(place,macroName,params,wikifier,paramString,tiddler){
        var namedprms = paramString.parseParams(null, null, true);
        var nodes = store.getTiddlers();
        var n = [];
        var edges = [];
        var tempnodes = {};
        var femaleNodeColor ="rgb(255,105,180)";
        var maleNodeColor = "#71B4FF";
        
        for(var i=0; i< nodes.length; i++){
            var node = nodes[i];
            var id1 = node.title;

            var tags = node.tags;
            if(tags.indexOf("systemConfig") == -1 && tags.indexOf("excludeTree") == -1 && tags.indexOf("excludeLists") == -1){ 
              var json={id:nodes[i].title,properties:{}};
              var properties = json.properties;
              if(node.fields.sex){
                  if(node.fields.sex == 'M'){
                      properties.sex= "M";
                      properties.fill = maleNodeColor;
                  }
                  else if(node.fields.sex =='F'){
                      properties.sex = "F";
                      properties.fill = femaleNodeColor;
                  }
              }
              properties.name = id1;
              if(!tempnodes[json.id])tempnodes[json.id] = json;
              
              if(node.fields.father) edges.push([node.fields.father,id1]);
              if(node.fields.mother) edges.push([node.fields.mother,id1]);
            }

        }
        
        for(var i in tempnodes){
            n.push(tempnodes[i]);
        }
        var graph = new VismoGraph({nodes:n,edges:edges});
        var div = document.createElement("div");
        place.className = "FamilyTree"
        place.appendChild(div);
        
        var w = jQuery(place).width();
        var h = jQuery(place).height();
        if(!w) w = 700;
        if(!h) h= 300;
        jQuery(div).css({width:w,height:h,"position":"relative"});
        var rootid;
        if(getParam(namedprms,"root")){
            rootid = getParam(namedprms,"root");
        }
         else{
                var tiddlers = store.getTaggedTiddlers("rootTree");
                if(tiddlers.length >0){
                    rootid = tiddlers[0].title;
                }

            }
    
        var root = store.getTiddler(rootid);
        var tooltip = document.createElement("div");
        tooltip.className = "ft_tooltip";
        place.appendChild(tooltip);
        jQuery(tooltip).css({position:"relative",border:"red"});

        var orphans = graph.getOrphans().sort();
        var str = "<select class='changeroot' style=''><option value='-1'>select a root</option>";
        for(var i=0; i < orphans.length;i++){
            var p=orphans[i];
            var node = graph.getNode(p);
            if(node.properties.sex != "F"){
                       str +="<option value='"+p+"'";
                        if(p == rootid)  str += " selected";
                        str += ">"+p+"</option>";  
           }
            
     
        }
        str += "</select>";
        jQuery(div).append(str);
        jQuery(".changeroot",div).change(function(e){
            if(this.value == "-1") return;
           that.vgr.clear();
           that.vgr.compute(this.value);
        });
        
        var options = {graph:graph,algorithm:FT_algorithm,nodeWidth:20,nodeHeight:10,defaultNodeColor:"rgb(200,200,200)",lineColor:"rgb(255,255,255)",lineWidth:"4"};
        
        if(rootid) options.root=rootid;
        var that = this;
        jQuery(tooltip).css({position:"absolute",display:"none"});
        options.vismoController = {controlFill:"rgb(255,255,255)",controlShape: "circle",controlStroke:"#39AC1B"};
        options.move = function(e,s){ jQuery(tooltip).css({display:"none"});if(s){var bb = s.getBoundingBox();jQuery(tooltip).text(s.getProperty("name"));jQuery(tooltip).css({top:e.screenY - e.clientY,left:0,display:""});}};
        options.dblclick = function(e,s){story.displayTiddler(null,s.properties.name);};
        this.vgr = new VismoGraphRenderer(div,options);
        config.activeTree = this.vgr;
    }

};

/*
Algorithm hacked together from 
http://www.codeproject.com/KB/scripting/graphic_javascript_tree.aspx
*/
var FT_algorithm={   
    _MaxDepth: 100,
    reset: function(graph){
       var nodes = graph.getNodes();
       for(var i=0; i < nodes.length; i++){
           var node = nodes[i];
           node.XPosition = false;
           node.YPosition = false;
           node.leftNeighbor = false;
           node.rightNeighbor = false;
           node.prelim = false;
           node.modifier = false;
       }
    }
    ,compute: function (graph,options) {	
        var root = options.root;
        this.nodeWidth = options.nodeWidth | 10;
        this.nodeHeight = options.nodeHeight | 10;
        ////////////console.log(" lets _positiongraph (magic here)");
        this.nodeWidth +=5;
        this.nodeHeight += 5;
        this.reset(graph);
    	this.maxLevelHeight = [];
    	this.maxLevelWidth = [];			
    	this.previousLevelNode = [];
    	////////////console.log(root);
    	var rootnode = graph.getNode(root);		
    	this._firstWalk(graph,rootnode, 0);
	    this.rootXOffset = 0 + rootnode.XPosition;
    	this.rootYOffset = 0 + rootnode.YPosition;

    	this._secondWalk(graph, rootnode, 0, 0, 0);	
    },
    _setLevelHeight: function (node, level) {	
    	if (this.maxLevelHeight[level] == null) 
    		this.maxLevelHeight[level] = 0;
        if(this.maxLevelHeight[level] < node.h)
            this.maxLevelHeight[level] = node.h;	
    },
    _setLevelWidth: function (node, level) {
    	if (this.maxLevelWidth[level] == null) 
    		this.maxLevelWidth[level] = 0;
        if(this.maxLevelWidth[level] < this.nodeWidth)
            this.maxLevelWidth[level] =  this.nodeWidth;		
    },
    _setNeighbors: function(node, level) {
        node.leftNeighbor = this.previousLevelNode[level];
        if(node.leftNeighbor != null)
            node.leftNeighbor.rightNeighbor = node;
        this.previousLevelNode[level] = node;	
    },

    _getLeftSibling : function (node) {
        if(node.leftNeighbor != null && node.leftNeighbor.nodeParent == node.nodeParent)
            return node.leftNeighbor;
        else
            return null;	
    },

    _getRightSibling: function (node) {
        if(node.rightNeighbor != null && node.rightNeighbor.nodeParent == node.nodeParent)
            return node.rightNeighbor;
        else
            return null;	
    },
    _getChildrenCenter: function (graph,node) {
        ////////////console.log("getChildrenCenter",node.id);
        var children = graph.getChildren(node.id);
        ////////////console.log("children are ",children,graph);
      
        var firstchild = graph.getNode(children[0]);
        var lastchild = graph.getNode(children[children.length-1]);
        ////////////console.log("kids are",firstchild,lastchild);
        return firstchild.prelim + ((lastchild.prelim - firstchild.prelim) + this.nodeWidth) / 2;	
    },
    

    _firstWalk: function (graph, node, level) {
    		////console.log("walking",node);
    		var leftSibling = null;
		
            node.XPosition = 0;
            node.YPosition = 0;
            
            node.prelim = 0;
            node.modifier = 0;
            node.leftNeighbor = null;
            node.rightNeighbor = null;
            this._setLevelHeight(node, level);
            this._setLevelWidth(node, level);
            this._setNeighbors(node, level);
            var children= graph.getChildren(node.id);
            var parents = graph.getParents(node.id);
            var parents_children=graph.getChildren(parents);
            var siblingid = parents_children.indexOf(node.id);
            //////////console.log("has children",children);
            if(children.length == 0 || level == this._MaxDepth)
            {
     
                leftSibling = this._getLeftSibling(node);
                if(leftSibling != null){
                     ////////console.log("left sibling prelim",leftSibling.prelim,"size",this.nodeWidth(leftSibling));
                    
                    node.prelim = leftSibling.prelim + this.nodeWidth + 40;
                }
                else
                    node.prelim = 0;
            } 
            else
            {
                
                var n = graph.getChildren(node.id);
                for(var i = 0; i < n.length; i++)
                {
                    var iChild = graph.getNode(n[i]);
                    iChild.nodeParent = node;
                    this._firstWalk(graph, iChild, level + 1);
                }
                var midPoint = this._getChildrenCenter(graph,node);
                midPoint -= this.nodeWidth / 2;
                leftSibling = this._getLeftSibling(node);
                ////////////console.log("have leftSibling",leftSibling,"of ",node);
                if(leftSibling != null)
                {
                    ////////console.log("prelim",leftSibling.prelim,"size",this.nodeWidth(leftSibling));
                    node.prelim = leftSibling.prelim + this.nodeWidth + 40;
                    node.modifier = node.prelim - midPoint;
                    //////console.log("y",node.YPosition);
                    if(node.YPosition.toString() =='NaN') throw "bad modifier";
                    this._apportion(graph, node, level);
                } 
                else
                {            	
                    node.prelim = midPoint;
                }
            }	
            //////////console.log("finished first walk");
    },
    _apportion: function (graph, node, level) {
        //////////console.log("in apportion");
        var children = graph.getChildren(node.id);
            var firstChild = graph.getNode(children[0]);
            var firstChildLeftNeighbor = firstChild.leftNeighbor;
            var j = 1;
            for(var k = this._MaxDepth - level; firstChild != null && firstChildLeftNeighbor != null && j <= k;)
            {
              
                var modifierSumRight = 0;
                var modifierSumLeft = 0;
                var rightAncestor = firstChild;
                var leftAncestor = firstChildLeftNeighbor;
                for(var l = 0; l < j; l++)
                {
                    
                    rightAncestor = rightAncestor.nodeParent;
                    leftAncestor = leftAncestor.nodeParent;
                    modifierSumRight += rightAncestor.modifier;
                    modifierSumLeft += leftAncestor.modifier;
  
                }
                ////console.log("the node is",node,"left ancestor is",leftAncestor,"right is ",rightAncestor);
                var totalGap = (firstChildLeftNeighbor.prelim + modifierSumLeft + this.nodeWidth + 30) - (firstChild.prelim + modifierSumRight);
                if(totalGap > 0)
                {
                    var subtreeAux = node;
                    var numSubtrees = 0;
                    for(; subtreeAux != null && subtreeAux != leftAncestor; subtreeAux = this._getLeftSibling(subtreeAux))
                        numSubtrees++;

                    if(subtreeAux != null)
                    {
                        
                        var subtreeMoveAux = node;
                        ////console.log("subtree is",subtreeMoveAux);
                        var singleGap = totalGap / numSubtrees;
                        for(; subtreeMoveAux != leftAncestor; subtreeMoveAux = this._getLeftSibling(subtreeMoveAux))
                        {
                            ////console.log("left sibling is ",subtreeMoveAux,"looking for ",leftAncestor," to stop");
                            subtreeMoveAux.prelim += totalGap;
                            subtreeMoveAux.modifier += totalGap;
                            totalGap -= singleGap;
                        }

                    }
                }
                j++;
                var firstChildChildren = graph.getChildren(firstChild.id);
                if(firstChildChildren.length == 0){
            
                    firstChild = this._getLeftmost(graph,node, 0, j);
                    }
                else
                    firstChild = graph.getNode(firstChildChildren[0]);
                if(firstChild != null)
                    firstChildLeftNeighbor = firstChild.leftNeighbor;
            }
    },
    _getLeftmost:function (graph,node, level, maxlevel) {
       
        if(level >= maxlevel) return node;
        var children = graph.getChildren(node.id);
        
     
        if(children.length == 0) return null;

    
        for(var i = 0; i < children.length; i++)
        {
            var iChild = graph.getNode(children[i]);
            var leftmostDescendant = this._getLeftmost(graph,iChild, level + 1, maxlevel);
            if(leftmostDescendant != null)
                return leftmostDescendant;
        }

        return null;	
    },
    _secondWalk: function (graph, node, level, X, Y) {
        ////console.log("doing _secondWalk",level,node,node.id,node.leftNeighbor,node.rightNeighbor);
            if(level <= this._MaxDepth)
            {
                var xTmp = 0 + node.prelim + X;
                var yTmp = 0 + Y;
                var maxsizeTmp = 0;
                var nodesizeTmp = 0;
                var flag = false;
            
                 	            	    	
    	                maxsizeTmp = this.maxLevelHeight[level];
    	                nodesizeTmp = this.nodeHeight;	                
    	                node.XPosition = xTmp;
    	                node.YPosition = yTmp;
    	         
                if(flag)
                {
                    var swapTmp = node.XPosition;
                    node.XPosition = node.YPosition;
                    node.YPosition = swapTmp;
                    //////console.log("swapTmp",swapTmp,node.XPosition);
                    
                }
         
    	    node.YPosition = -node.YPosition - nodesizeTmp;
    	       //////console.log("nodesizeTmp",nodesizeTmp);
            
    	    ////////////console.log("getting Children",node);
    	     var Children = graph.getChildren(node.id);
    	     ////////////console.log(Children);
                if(Children.length != 0)
                    this._secondWalk(graph, graph.getNode(Children[0]), level + 1, X + node.modifier, Y + maxsizeTmp + 40);
                var rightSibling = this._getRightSibling(node);
                if(rightSibling != null)
                    this._secondWalk(graph, rightSibling, level, X, Y);
            }	
    ////////console.log("now",node.XPosition,node.YPosition);
    }
};TiddlyWiki.prototype.familytree_saveTiddler = TiddlyWiki.prototype.saveTiddler;
TiddlyWiki.prototype.saveTiddler = function(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created)
{
    if(!newTitle) newTitle = title;
    //clean up children    
    if(newTitle &&newTitle != title){
        var tiddlers = store.getTiddlers();
        for(var i=0; i < tiddlers.length; i++){
            var tid = tiddlers[i];
            if(tid.fields.mother ==title){
                tid.fields.mother = newTitle;
            }
            if(tid.fields.father ==title){
                tid.fields.father = newTitle;
            }
            if(tid.fields.spouse){
            var spouses = tid.fields.spouse.split(",");
            
            var update = spouses.indexOf(title);
            if(update !=-1){
                spouses[update]= newTitle;
                tid.fields.spouse = spouses.join(",");
            }
}
        }
        //do spouses

    }
    var newSpouseField, tiddlerSpouses;
    if(fields){
        newSpouseField =fields.spouse;
        if(newSpouseField && newSpouseField.length > 0){
            tiddlerSpouses = newSpouseField.split(",");
        }
        else{
            tiddlerSpouses = [];
        }
    }
    else{
        tiddlerSpouses = [];
    }

    
    
    //add the new spouses
       
        for(var i=0; i < tiddlerSpouses.length; i++){
            var spouse = tiddlerSpouses[i];
            //console.log("spouse",i,spouse);
            var spouseTiddler = store.getTiddler(spouse);
            if(spouseTiddler){
            if(!spouseTiddler.fields.spouse)spouseTiddler.fields.spouse = "";
            var spouseSpouses = spouseTiddler.fields.spouse.split(",");
            //console.log(spouseSpouses,newTitle);
            if(spouseSpouses.indexOf(newTitle) == -1){
                spouseSpouses.push(newTitle);
                spouseTiddler.fields.spouse = spouseSpouses.join(",");
                //console.log("save");
            }
            }
        }
    
    this.familytree_saveTiddler(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created);

};
config.macros.familytreelist = {
    handler: function(place, macroName, params, wikifier, paramString, tiddler){
        var param = paramString.parseParams();
    	var sex= getParam(param,"sex");
    	
    	var print ="";
    	var tiddlers = store.getTiddlers();
    	for(var i=0; i < tiddlers.length;i++){
    	    var tid = tiddlers[i];
    	    var good = false;
    	    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);
    }
};
config.macros.makeRootLink = {
    handler: function(place, macroName, params, wikifier, paramString, tiddler){
        jQuery(place).html("<a class='button makeRoot' href=\"#[["+tiddler.title+"]]\" name=\""+escape(tiddler.title)+"\">make root</a>");
        jQuery(".makeRoot",place).click(function(e){
            config.activeTree.compute(unescape(jQuery(this).attr("name")));
        })
    }
    
};
config.macros.listchildren ={
  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);}
    }

    if(children.length ==0){
      var div = document.createElement("div");
      div.innerHTML = "No children.";
      place.appendChild(div);
    }
    else{
    var ul = document.createElement("ul");
    place.appendChild(ul);
    for(var i=0; i < children.length; i++){
       var child = document.createElement("a");
       child.className="child";
       var name =children[i].title;
       child.innerHTML = name;
       child.title = name;
       var li = document.createElement("li");
       li.appendChild(child);
       ul.appendChild(li);
       
       jQuery(child).click(function(e){story.displayTiddler(e,this.title);});
    }
    }
  }

};
config.macros.tiddlerGender ={
  handler: function(place, macroName, params, wikifier, paramString, tiddler){
      var jqplace = jQuery(place);
      if(tiddler.fields["sex"] == 'M'){
          jqplace.addClass("sexMale");
      }
      else if(tiddler.fields["sex"] == 'F'){
          jqplace.addClass("sexFemale");
      }
      
  }

};

config.macros.ftview = {
    handler: function(place, macroName, params, wikifier, paramString, tiddler){
        var field = params[0];
        if(!tiddler.fields[field]) return;
        if(field == 'spouse'){
            var sp = tiddler.fields["spouse"].split(",");
            var str = "";
            
            for(var i=0; i < sp.length;i++){
                var thisSpouse = sp[i];
                if(thisSpouse){
                    str += "[["+thisSpouse + "]]";
                    if(i < sp.length-1) str += " and ";
                }
            }
            
            wikify(str,place);
        }

    }
    
};

config.commands.addMother = {
        text: "Add Mother",
        tooltip: "add a mother",
        
        handler:function(event,src,title){
                var motherName = prompt("Who is their mother?");
                if(motherName){
                        var tiddler = store.getTiddler(title);
                        tiddler.fields.mother = motherName;
                        if(!store.getTiddler(motherName))story.displayTiddler(null,motherName,DEFAULT_EDIT_TEMPLATE);        
                }
             
        }
};
config.commands.addSpouse = {
        text: "Add Spouse",
        tooltip: "add a spouse",
        
        handler:function(event,src,title){
                var spouse = prompt("What is the name of the spouse?");
                if(spouse){
                        var tiddler = store.getTiddler(title);
                        tiddler.fields.spouse = spouse;
                        
                        
                        var tiddler = store.getTiddler(spouse);
                        if(tiddler){
                                 tiddler.fields.spouse = title;
                                 store.saveTiddler(tiddler.title,tiddler.title,tiddler.text,tiddler.modifier,tiddler.modified,tiddler.tags,tiddler.fields,true,tiddler.created);
                               
                        }
                        else{
                                store.saveTiddler(spouse,spouse,"","",new Date(),[],{spouse: title},true,new Date());
		                story.displayTiddler(null,spouse,DEFAULT_EDIT_TEMPLATE);
		        }
		        
                }
             
        }
};

config.commands.addChild = {
        text: "Add Child",
        tooltip: "add a child",
        
        handler: function(event,src,title){
                
                var parent = store.getTiddler(title);
                var sex = false;
                var spouse = "";
                if(parent && parent.fields.spouse)spouse = parent.fields.spouse;
                if(!parent) {
                        //try and work out the sex..
                        var tiddlers = store.getTiddlers();
                        
                        for(var i=0; i < tiddlers.length; i++){
                                if(!sex && tiddlers[i].fields.mother == title) sex = "F";
                                if(!sex && tiddlers[i].fields.father == title) sex = "M";
                        }
                }
                else{
                        if(parent.fields.sex) sex =parent.fields.sex;
                }
                if(sex){

                        var childName = prompt("What is the name of the child?");
                        if(childName){
                                

                                
                               
                               var tiddler = store.getTiddler(childName);
                               if(!tiddler){
                                       
                                       var fields = {};
                                       if(sex == "F") {
                                               fields.mother = title;
                                                fields.father = spouse;
                                       }
                                       else if(sex == "M") {
                                               fields.father = title;
                                                fields.mother = spouse;
                                        }
                                       store.saveTiddler(childName,childName,"",false,new Date(),[],fields,true,new Date());
                                       //childName,childName,"",false,false,[],fields,true,new Date());
                                    
                                }
                                else{
                                        
                                                                    if(sex == "F") {
                                                                               tiddler.fields.mother = title;
                                                                                tiddler.fields.father = spouse;
                                                                       }
                                                                       else if(sex == "M") {
                                                                               tiddler.fields.father = title;
                                                                                tiddler.fields.mother = spouse;
                                                                        }
                                }
   
                        }
           
                       if(childName) story.displayTiddler(null,childName,DEFAULT_EDIT_TEMPLATE);
                }
                else{
                        alert("I can't do this until I know the sex of this person..");
                }
                
        }
};
config.commands.addFather = {
        text: "Add Father",
        tooltip: "add a father",
        
        handler: function(event,src,title){
                var fatherName = prompt("Who is their father?");
                if(fatherName){
                        var tiddler = store.getTiddler(title);
                        tiddler.fields.father = fatherName;
                        if(!store.getTiddler(fatherName))story.displayTiddler(null,fatherName,DEFAULT_EDIT_TEMPLATE);        
                }
        }
};merge(config.macros.newTiddler,{
	label: "new person",
	prompt: "Create a new person in your family tree",
	title: "New Person",
	accessKey: "N"});

config.macros.bootUpFamilyTree = {
    handler: function(place,macroName,params,wikifier,paramString,tiddler){
        story.closeAllTiddlers();
          var tiddlers = store.getTaggedTiddlers("rootTree");
         for(var i=0; i < tiddlers.length; i++){
             story.displayTiddler(null,tiddlers[i].title);
         }
        
        
    }
};



Born "Emma Isabella" with registered address Rostock Terrace Middlesbrough. Baptised "Frances Isabella Woodhouse" .

[img[files/frances.jpg]]
5 Siblings: John George (Senior), William Isaac, Harriett Jane, Robert Amos and Hannah Mary Augustus

Married Thomas Bellwood, an Iron Merchant Clerk, (born in Heigington Durham on 1st March 1877) at Bondgate Wesleyan Chapel, Darlington.

The Robson name like "Lyall" in the Robson family has been carried down the generations ever since. With Charles' son Norman Robson, and his grandson Thomas Robson

The 1881 census has Frances living at 73 Westward Street, Middlesbrough, Yorkshire, England

Frances died at 30 Woodlands Road, Middlesbrough on 14th December 1943 aged 89.
(Source: Robin Bellwood, 1881 census) 

Possibly born on 24th June?
	Married at Bondgate Wesleyan Chapel, Darlington.

	In 1877 living at 43 Guerney St, Darlington.

Mentioned as son of Henry Gartside (but apparently not his heir) in license of 1597. Possibly an illegitimate son. Probably purchased half of his father"s estate from relative John Gartside.




He married Elizabeth Rees in All Saints Church, Llanelly, Carmarthenshire. They had one daughter: Elizabeth V. Brew, who was born December 1911 in Newport, Monmouthshire, Wales 



Was French and this appears to have caused much upset to the family.



Died 2nd February 1908 in Cardiff, Glamorgan, Wales. Son of Thomas Brew and Honor Perry.

	Christened 8th January 1826 in Chepstow.

	Married Jane Margaret Morgan in Chepstow 8th November 1847.
	George worked as a Sawyer/Railwayman

	[Bellwood Family Tree]

Christened 11th June 1851 in Saint Mark, Kennington, London, England.
08 FEB 1824   	Allendale, Northumberland, England ?

	Possible marriage to Frances Turnbull:
	21 NOV 1857  	All Saints, Newcastle Upon Tyne, Northumberland, England
	Needs chasing up.
Married Sarah.

Christened: 1760-06-29?
	Buried at the Ballast Hills Cemetry Newcastle alongside Mr. Doeggs tablestone.
Gentlemen of Bishop Middleham.

Two known children:
1. Angela Spearman OXX (1938-)
m. Michael J WILFORD 1960
(whom had 5 children: Karenna, Carl Adrian, Paul Newton, Jane Anne, Anna Patricia)							
2. Sonia Spearman OXX (1938-)
m. Robert H Broome 1961
(whom had 4 children: Sonia, Richard, Nicola, Sara)

Possibly had a third child.
Christening: 01 SEP 1807 at Quay Meeting House-Independent, Woodbridge, Suffolk, England

Died in Carmarthenshire, Wales. He married Mary Jane Thomas, born ca. 1880 in Carmarthen, Carmarthenshire, Wales, daughter of John Thomas, on 21 September 1901 in the Registry Office, Carmarthen, Carmarthenshire.

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>>

[[SideBarOptions]] and [[SideBarTabs]]

Coal viewer for brandlings of Wakefield.
	Baptised 16th April 1734 and again on 16th April 1735 at Church Merrington.
	Lived at Rotherham.
Gilbert Spearman was born somewhere around 1675. Died around 1738.

Married Margaret Pearson/Pierson at Parish Durham, Cathedral alternatively Durham, Christ Church & BVM in county Durham 01/09/1701.
One known child: George

Was involved in a law suit against William Wilkinson and Edward Birkebeck concerning the estate of his wife Margaret's deceased father Robert which he appeared to have won (See below).

LAW SUIT
{{{
486/1-41.      29 October 1703 - 8 November 1705
File of documents relating to a suit in Chancery brought by Gilbert Spearman and his wife Margaret against William Wilkinson, Esq., Catterick Birkebeck, Esq., and Edward Birkebeck, concerning the estate of Robert Peirson, deceased, father of Spearman's wife, Margaret; and to a cross suit brought by the said William Wilkinson against Gilbert Spearman and his wife Margaret.
(The file has been re-arranged chronologically.)

486/1.      29 October 2 Anne (1703)
Spearman, plaintiff, v Wilkinson, defendant:
Affidavit of Robert Bell of the city of Durham, gent., that on 26 October the defendant, William Wilkinson, was served with a subpoena to rejoin to the plaintiffs' Replication on 28 October, and that at the request of the plaintiff, Gilbert Spearman, the said defendant consented to the establishment of a commission, waiving any rights to delay the same.
Paper     2ff.

486/2.      31 December 1703
Spearman, plaintiff v Wilkinson, defendant:
Copy of Catherick Birkbeck's consent, for himself and his son Edward Birkebeck, to make their defence to the charge of Gilbert Spearman and his wife Margaret "without being served with usuail process of this Court."
Paper     2ff.
 
486/3.      22 January 2 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of certificate of Michael Mickleton and John Crosby the Elder, commissioners to examine witnesses on behalf of the plaintiff, Gilbert Spearman, and in the cross case brought by the defendant, William Wilkinson, concerning the conduct of the commission and the refusal of the commissioners on the part of the defendant to produce witnesses other than two sons of the said William Wilkinson: Thomas and John Wilkinson.
Paper     2ff.
 
486/4.      25 January 2 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Affidavit of John Anderson of the city of Durham, gent., concerning Catterick Birkebeck's consent to defend his case in court and in commission without the service of subpoenas.
(See No. 486/2, originally attached).
Paper     1f.
 
86/5.      25 January 2 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Affidavit of the plaintiff Gilbert Spearman concerning declarations by the defendant of his intention to delay and prolong the case until his death, and the effect this death would have on the plaintiff's case.
Paper     2ff.
 
486/6.      7 February 2 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Affidavit of the defendant William Wilkinson that certain witnesses could not be procured for examination on his behalf in the plaintiff's commission, returnable 20 January last.
Paper     2ff.
 
486/7.      12 February 2 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order permitting the establishment of a commission to examine witnesses on behalf of the defendant, William Wilkinson, unless good cause against such a commission can be shown by the plaintiff at "ye first general Seal after this Terme".
Underneath:
17 February 1703 [1704]
Note from Mr. Edwards, clerk to Mr. Close, informing him that the above order, to be dealt with the following day, was served on him after 8 o'clock that evening.
Endorsement: Note of Mr. Close that more time should be obtained for making an objection to the above order.
Paper     1f.
 
486/8.      12 February 2 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order as above (No. 486/7) except that the plaintiff's objection should be made "at ye Second Generale Seale after this Terme."
Paper     1f.
 
486/9.      25 February 2 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order referring the case to Sir Robert Legard, master of the court, to appoint a time and place for the execution of a Commission to examine witnesses on the part of the defendant, the plaintiff to have a duplicate of the said Commission; and laying down future procedure.
Paper     2ff.
 
486/10.      7 March 1703/1704
Spearman, plaintiff v Wilkinson, defendant:
Copy of Notification by Robert Legard that, in pursuance of the above Order of Reference (No. 486/9), a meeting of all parties in the case will take place the following Thursday.
Paper     ½f.
 
486/11.      14 (sic.) March 1703/1704
Spearman, plaintiff v Wilkinson, defendant:
Copy of Notification by Robert Legard as above.
Paper     ½f.
 
486/12.      7 March 1703/1704
Draft by William Lee, solicitor for the defendant, of the following agreement (No. 486/14).
Paper     1f.
 
486/13.      7 March 1703/1704
The same, by James Close, solicitor for the plaintiff, with amendments.
Paper     1f.
 
486/14.      9 March 1703/1704
Spearman, plaintiff v Wilkinson, defendant:
Agreement relating to the times and places for the execution of the commission for the examination of witnesses, with safeguards for the continuation of the commission should the defendant's commissioners refuse to attend or adjourn as agreed.
Signed: James Close (solicitor for the plaintiff), William Lee (solicitor for the defendant).
Paper     1f.
 
486/15.      9 March 1703/1704
Note from James Close to Mr. Edwards requesting him to make a duplicate of the above Agreement.
Paper     ½f.
 
486/16.      23 March 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Affidavit of Follansby Walton of the city of Durham that the plaintiff's proposal to change Mr. Mickleton, one of his commissioners for the examination of witnesses, was refused by the defendant; and that the said Mr. Mickleton is too ill to leave his house for at least two months.
Paper     2ff.
 
486/17.
Spearman, plaintiff v Wilkinson, defendant:
Draft Petition of the Plaintiff Gilbert Spearman to have the case heard at the beginning of the Easter Term.
Paper     1f.
 
486/18.
Spearman, plaintiff v Wilkinson, defendant:
Copy Petition of the defendant Gilbert Spearman, in the cross case brought by William Wilkinson laying claim to the estate of Robert Pearson, deceased, father of the defendant's wife Margaret, to have the case heard "the first day of Causes after this Terme".
Paper     2ff.
 
486/19.
Draft of the above Petition.
Paper     1f.
 
486/20.      24 March 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order for the case of Gilbert Spearman, plaintiff, against William Wilkinson, defendant, to be heard on 9 May next.
Underneath:
19 April 1704
Notification of the above order by James Close to Mr. Consett.
Paper     1f.
 
486/21.      28 March 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order permitting the plaintiff Gilbert Spearman to change one of his commissioners for the examination of witnesses.
Paper     2ff.
 
486/22.      6 May 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order, on the petition of the plaintiff William Wilkinson, that the original cross causes should both be heard on 15 May and that depositions taken in one cause might be used for the other.
Paper     2ff. pinned together.
 
486/23.      11 May 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order permitting the defendant to use depositions taken in one case at the hearing of the other as the two cases are to be heard together.
Paper     2ff.
 
486/24.      16 May 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order, permitting the defendant Gilbert Spearman to examine witnesses viva voce to prove a deed, dated 27 May 4 Wm. and Mary (1692) between:
(1) Robert Pearson and Caterick Birkbeck,
(2) the said William Wilkinson and Martin Wilkinson.
Endorsement: Note that the above Order was amended.
Paper     2ff.
 
486/25.      16 May 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of amended version of the above Order allowing the defendant Gilbert Spearman to prove also and in the same way a letter, dated 10 July 1683,from the plaintiff Wilkinson to Robert Pearson.
Paper     2ff.
 
486/26 (i) and (ii).
Spearman, plaintiff v Wilkinson, defendant:
Copies of two documents sealed together and sent to Gilbert Spearman at London:
(i). 10 June 3 Anne (1704)
Affidavit of John Anderson of the city of Durham, gent., that the defendant William Wilkinson was served with a copy of the attached order.
(ii) 27 May 3 Anne (1704)
Court Order that, at the hearing of the above case, the defendant should produce a deed of settlement relating to the rectory of Bishopp Middleham dated 8 June 22 Chas. II (1670), between:
(1) Lord Cullen:
(2) Robert Pearson and his wife Mary (Cokayne):
(3) Nicholas Shuttleworth and George Iresham:
(4) George Blount (possibly a son of 2nd husband of Mary O'Brien) and John Vavasour.
Paper     1f. and 2ff.
 
486/27.      15 July 1704
Spearman, plaintiff v Wilkinson, defendant:
Minutes of the decree in favour of the plaintiff Gilbert Spearman.
Paper     2ff.
 
486/28.      9 November 1704
Spearman, plaintiff v Wilkinson, defendant:
Copy Petition of the plaintiff Gilbert Spearman to have a day appointed for the pronouncement of judgment; with note authorising order that judgment will be given 14 November.
Paper     2ff.
 
486/29.
Draft of the above petition.
Paper     2ff.
 
486/30.      11 November 1704
Spearman, plaintiff v Wilkinson, defendant:
Copy Petition of the defendant William Wilkinson that judgment should be postponed until, in pursuance of a decision of 15 July, the cases of both sides and the settlement deeds have been referred to judges.
f.2: Note of court decisions of 9, 11 and 18 November.
Paper     2ff.
 
486/31.      13 November 1704
Spearman, plaintiff v Wilkinson, defendant:
Affidavit of Theodore Johnson that copies of the plaintiff's petition (No. 486/28) and court order of 9 November were delivered to the defendant's clerk of court.
Paper     1f.
 
486/32.      18 November 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order for judgment to be given on Wednesday next (22 November) and for the defendant's petition of 11 November (No. 486/30) to be heard at the same time.
Paper     2ff.
 
486/33.      18 November 1704
Spearman, plaintiff v Wilkinson, defendant:
Copy of Affidavit of William Lee, solicitor for the defendant, that he was not consulted by the plaintiff's solicitor Mr. Close about drawing up an order of Reference to the judges pursuant to the direction of the court, and that the judges were attended and their decision given in favour of the plaintiff without his knowledge.
Paper     2ff.
 
486/34.      18 November 1704
Spearman, plaintiff v Wilkinson, defendant:
Copy of Affidavit of William Midford, clerk to Mr. Lee, solicitor for the defendant, that he was informed by the plaintiff's solicitor Mr. Close on 27 September and on other occasions that there was no haste to prepare a case for reference to the judges pursuant to the direction of the court, and that a memorandum was made of this answer.
Paper     2ff.
 
486/35.      27 November 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order dismissing a petition of the defendant William Wilkinson.
Paper     2ff.
 
486/36.      13 December (1704)
Spearman, plaintiff v Wilkinson, defendant:
Draft Petition on behalf of the plaintiff Gilbert Spearman to have judgment pronounced without further delays caused by the defendant.
Paper     1f. [Damaged.]
 
486/37.      13 December 3 Anne (1704)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order for judgment to be given the following Monday (18 December).
Paper     2ff.
 
486/38.      16 December 1704
Spearman, plaintiff v Wilkinson, defendant:
Affidavit of Theodore Johnson that the Order of 13 December (No. 486/37) was served on the defendant's clerk in court on 15 December.
Paper     2ff.
 
486/39.
Spearman, plaintiff v Wilkinson, defendant:
Draft Petition of the plaintiff Gilbert Spearman for the enrolment of the decree pronounced 18 December 1704.
Paper.     1f.
 
486/40.      26 October 4 Anne (1705)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order for the enrolment of the decree pronounced 18 December 1704.
Paper     2ff.
 
486/41.      8 November 4 Anne (1705)
Spearman, plaintiff v Wilkinson, defendant:
Copy of Court Order for the signing and enrolment of the decree (pronounced 18 December 1704).
Paper     1f.
}}}

Died young.

Christened in Chepstow on 29 April 1827, and married William Jones in 1848 
Christened: 1810-10-21
Born 1849 in Darlington, Durham. Daughter of  Robert Robson and Mary Holder Oxx.

5 Siblings: John George (Senior), William Isaac, Harriett Jane, Robert Amos and Frances Isabell Woodhouse.

Married James Bulmer March 1876 in Darlington.
2 known children: 

Ethel Mary Bulmer
BORN 23 JAN 1877 Darlington, Durham, England 
DIED about 1906

Emma Isabel Bulmer
Born 24 FEB 1881 Darlington, Durham, England / (B S), Germany
DIED 22 JUN 1956

The 1881 Census has her aged 32, dwelling at 40 Henry St, Darlington, Durham with husband James Bulmer, a 32 year old Bricklayer, born also in Darlington, Durham with 2 children Ethel M (4) and Emma J (1 month). She is also living with Robert Robson, her widowed father now aged 61.
	For 1891 see her husband James Bulmer.

	In 1901 she is widowed and living at 1 Close Street with her children Ethel M, Emma, May, Harriet H, Albert J and Charles H. They are living near to a Newton family (next door?)

	She died in 1908 according to a death certificate in possession of her great granddaughter [[Elizabeth Bulmer]].
It is not known when she died.


Died at 7.50pm aged nearly 80.
	Buried at the Ballast Hills Cemetry, Newcastle near the headstone of James Smith in the New Ground not far from the rails.
Died 31 March 1963 in Swansea, Glamorgan, Wales. Harold saw service in World War I as a 2nd Lieutenant in the South Wales Borderers. 

She married Thomas Hunter.

	In the 1881 census she is living at 8 Hanover St in Stranton, Durham, England:
	Thomas C. HUNTER   Head   M   Male   31   Scotland   Draper Employing 1 Boy     
	 Harriet J. HUNTER   Wife   M   Female   34   Middlesbro, York, England        
	 Alfred WILLIAMSON   Boarder   M   Male   29   Stokesley, York, England   Drapers Assistant     

	In 1891 she is a widow and a boarder at a Milleners shop:
	Household Members: Name Age 
	Harriet Jane Hunter 40 
	Sarah Saunders 49 
	Shown as a Drapers Assisant at Poplar Grove (a Milleners shop)

	In 1901 she is a widow living with nieces Florence Bellwood and Emma Bulmer:
	Harriet J Hunter 
	Age: 50 
	Estimated Birth Year: abt 1851 
	Relation: Head 
	Gender: Female 
	Where born: Middlesborough, Yorkshire, England 
	Civil parish: West Hartlepool 
	Ecclesiastical parish: St Paul 
	County/Island: Durham 
	Country: England 
	Registration district: Hartlepool 
	Sub-registration district: Hartlepool 
	ED, institution, or vessel: 48 
	Neighbors: View others on page 
	Household schedule number: 8 
	Household Members: Name Age 
	Florence M Bellwood 23 
	Emma Bulmer 20 
	Harriet J Hunter 50 

	Florence & Emma are nieces & Harriets occupation is shown as Ladies underclothing & baby linens living at York Road.
	She was buried in West Hartlepool, Durham.
Christened  20 JAN 1821   	Saint Mary, Woodbridge, Suffolk, England
390 Groby Road, Leicester. Worked as a Foundry Worker and lived 15 Bradbury Street, Ashton-u-Lyme.







Inquisition Post Mortem held 6 May 1597.
	Probably a different Henry Gartside, possibly the son of the one who purchased his farm in 1554/5.
	Estate described as in 1554/5 and held of the Queen by one thousandth part of a knights fee.
Senior in 1628 when by fine he conveyed to Henry Gartside, Junior, one messuage and garden, ten acres of land, ten acres of meadow, six acres of pasture, one acre of furze and an eight part of four acres of land with rights of pasture and turbary in Denshaw.
	Buried in Oldham 6 Sept 1634.
With son William Gartside also Richard Gartside and John Gartside leased farm called Denshaw (A half of Denshaw) together with a half of Bakestone Delph, from Roche Abbey by deed dated 23rd August 1526.
	Purchased the freehold of his farm at Denshaw (described as one messuage with outbuildings, 16 acres of land, 8 acres of meadow, 8 acres of pasture with rights of common and turbary etc together with one eighth of the bakestone mine at Delph, from Roger Gartside of Rochdale for £46 by deed dated 15 March 1554/5
Party to fine of 1628 when he was described as Junior.
	Will proved 11 Aug 1663.
	With son purchased Coatmans or Over HevBarn.
Unconfirmed child.




Died in Chepstow, aged ca. 85, on 16 April 1875. 


Two conflicting christenings:
	Christened: 20 JAN 1821    	Saint Mary, Woodbridge, Suffolk, England
	Christened: 26 NOV 1823    	All Saints, Newcastle Upon Tyne, Northumberland, England
Married Joan Bagg 20th February 1954.
Two children: Andrew Lyall and Sharman Louise

In his career has taught teaching apprenticeships in the steel industry in Port Talbot before moving to Swindon where he became manager of Bunce (Ashbury) Ltd making Snow Ploughs, gritting machines, snow blowers and mechanical sweepers.



Born 20th March 1865 in Darlington, Durham. Daughter of John George Robson and Martha Isabell Lyall. Christened 11th April 1865 in St John, Middlesbrough, Yorkshire England.

6 siblings: Robert William, Adam Lyall Margaret Elizabeth (died young aged 5),  Matthew Jackson, Mary Elizabeth and John George Robson (Junior).

Christened at St John, Middlesbrough, Yorkshire, England [familysearch.org]

The 1881 Census has shows she no longer lives with her parents. aged just 16. The 1881 census also shows an Isabella Robson (aged 16), a scholar, born in Middlesbrough, living at 11 Teresa Ter, Kirkleatham, Yorkshire, England. She is granddaughter to the head of the household Isabella LYALL and also living with her two aunts Margaret And Elizabeth. It seems coincidence that these are not the same people.

	Married after 1881 census - in which she was 16 and living with her grandmother.

	Living at Holden Road in 1901 census with Charles H Newton and 2 sons, cousin John G Robson and servant.

Isabella Bulmer (born 1834) came from Darlington to Auckland NZ arriving on 4 nov 1877 on the ship "Otaki".
See husband for early life.

	The 1881 census shows Isabella Lyall living at 11 Teresa Ter, Kirkleatham, Yorkshire, England. She is living with her two daughters Margaret And Elizabeth and her granddaughter Isabella Robson (aged 16). She is widowed.



The 1881 Census has him aged 32, dwelling at 40 Henry St, Darlington, Durham with wife Hannah, born also in Darlington, Durham with 2 children Ethel M (4) and Emma J (1 month). He is also living with Robert Robson, his widowed father-in-law now aged 61.

	In 1891 he is living at 3 Close Street - not too far from Henry St. with wife and children Ethel, Emma, May, Harriet, Albert and Charles H.

	In 1901 his wife Hannah is widowed.
Marriage is approximate and took place in Darlington.
Yeoman.
	Will proved 24 Oct 1785. Buried in Marsden.
Died before 25 Dec 1596 mentioned in Inquisition Post Morterm of 1597 as deceased and as blood relative and next heir of Henry Gartside.




Possibly Edmunds if son John is John George and is born 10 DEC 1821    	Sunderland, Durham, England

	I have found a marriage for John ROBSON and Jane TODD, All Saints, Newcastle upon Tyne 1 Feb 1808, it may be worth following up.
	1841 census (Walker, Long Benton, Newcastle):
	George Robson abt 1825 Northumberland, England Long Benton Northumberland
	View Record Isabella Robson abt 1832 Northumberland, England Long Benton Northumberland
	View Record Jane Robson abt 1798 Northumberland, England Long Benton Northumberland
	View Record Jane Robson abt 1830 Northumberland, England Long Benton Northumberland
	View Record John Robson abt 1822 Northumberland, England Long Benton Northumberland
	View Record Robert Robson abt 1820 Northumberland, England Long Benton Northumberland
	View Record William Robson abt 1835 Northumberland, England Long Benton Northumberland
	It states that Jane is a pauper, possibly due to being widowed?

	1851 census (Wincomblee, Longbenton):
	June Robson abt 1787 Hacey, Northumberland, England Head Longbenton Northumberland
	William Robson abt 1835 Walker, Northumberland, England Son Longbenton Northumberland 
	A few mistakes here but it could be the same one..

	Her maiden name is NOT Stephenson.
Lecturer at Old Church House Stanmore.
I wonder if Elizabeth Rees is Jessica"s sister and her father is Robert Rees as these names crop up in the Brew family tree.








Born 1763/1765 and died before 1805. Son of an unknown father and unknown mother (first name Elizabeth).

	According to the Parish Register, their wedding banns were published on three consecutive Sundays, the 2 November, 9 November and 16 November 1788. John is listed as a bachelor and Mary a spinster. They were married by the minister, with Thomas and Hannah Ashburner as witnesses. Interesting to note is that both John and Mary were most probably illiterate as they both undersigned their names with an "X". 

	vidence shows that John and Thomas" father, John, was dead by 1805. A draft apprenticeship indenture for Thomas as a Ropemaker, from October 1809, shows that he was already in an apprenticeship agreement since 1805, for which he obtained the consent of his mother, Mary. "...wh"as by Ind"re bearing Date the 2d Day of July 1805...it is witnessed that the sd. Ths. Brew with the Consent of his mother Mary Brew of Chepstow afsd. widow did put himself apprentice to Saml. Brookman of Chepstow afsd. Ropemaker....". There are no records of his death in the parish registers, this is the only clue.

	We believe that John (ca.1765-ca.1805) also had a brother called Thomas, as a Thomas Brew, also married to a Mary, is recorded as having christened a son, James, in Chepstow, on 8 June 1794. James would therefore have been a cousin to John and Thomas, born in 1790 and 1791. We find no further trace of James or his parents after this reference.

	SOURCES
	<a href="http://brew.clients.ch/family.htm">Brew family tree</a>
Read more here: [[http://brew.clients.ch/john1790.htm#John%20Brew,%201790-1843]]




Chief Baron of Exchequer 1401
Married Agnes Vernon.




id:493 
Yeoman.
	Marriage license 1697.
	Marriage settlement 20 Sept 1697.
	Buried 29 April 1745.
	Will proved 11 May 1745.
Yeoman.
	Admin granted 26 May 1724.
	Commemorative plaque in Old Saddleworth Church.
id:501
Yeoman.
	Will proved to be 9 May 1702.
	With father purchased Coatmans.
Aged 28 years on 25 Dec 1596.
	Mentioned in Inquisition Post Morterm of Henry Gartside as son of James Gartside deceased and blood relative and heir of Henry Gartside. Inherited Henry"s estate at Denshaw.
	Granted license to sell a half of the estate (Excluding Broadmeadow House, Broadmeadow, a quarter of the Hey and one eighth of the bakestone mine) to Francis Gartside 8 Nov 1597.
	Granted license to sell a house called Broadmeadow and 6/7 acres of land in Denshaw to Robert Gartside 2 Mar 1597/8.
	Admin granted 27 April 1627.
Baptised 13th March 1817 at St. Thomas, Friarmere. Was an overseer in Woolen factory.
	Lived in Green Ash?
Born 1884 in Workington, Cumbria. Son of John George Robson and Martha Isabell Lyall.

John was the youngest of 7 children, his 6 siblings were: Isabell, Robert William, Adam Lyall, Margaret Elizabeth, Matthew Jackson and Mary Elizabeth.

Attended Lewis' School Pengam. (possibly: http://www.caerphilly.org.uk/lewisschoolpengam/homepage.htm)

Lived in Middlesborough, Scunthorpe and Trimsaran Wales.

One known address he lived at was:
Culla House,
Culla Rd,
Trimsaran,
Kidwelly Wales
Interestingly this is now a restaurant (in 2004) called Burdies.

Married 18th March 1908 in Neaf at English Baptist Church in Port Talbot.
Four children :Ian Lyall Robson, Alan Lyall, Marjorie Isabel, Margaret Valerie Millett

Took an engineering apprenticeship in Kilmarnock, Scotland.

Worked for a company called "Andrew Barkley" making steam engines.

Died 1964.
The 1881 Census has him dwelling in Mossby Cottage, Workington, Cumberland, aged 38 with wife Martha Isabell (formerly Lyall), also 38 and children Robert William (13), Adam Lyall (10), Mary Elizabeth (5) and Mathew Jackson (3). Daughter Isabell would have been 16 and it is interesting to note that she is no longer registered to be living in the house. John George would not be due for 3 years, and Margaret Elizabeth would have sadly passed away only 3 years before.

	The 1881 census has him working as a Roll Turner in Steel Works. He is known to have worked at Rise Car Rolling Mills in the steel industry as he was presented with a clock upon leaving on 26th February 1876. Rise Car being a suburb in Darlington. The Rolling Mills were involved in the production of puddled iron, the re-rolling of steel bars and the manufacture of special sections. Along with other firms in town, it made Darlington important enough to attract foreign visitors. The Chinese Imperial commissioners visited in April 1906.

	The 1901 census shows him living with daughter Mary, wife and a servant Maud Lloyd. Interestingly, sons Robert and Matthew are living at Culla House, Pembrey, Llanelly, East Carmarthen as boarders in a house owned by LLOND. Probably not related, but I wondered if this was any relation to the servant.
	View Record Maud Lloyd abt 1877 Shelton, Staffordshire, England Servant Aberavon Glamorgan
	View Record John G Robson abt 1843 Middlesbrough, Yorkshire, England Head Aberavon Glamorgan
	View Record Martha J Robson abt 1843 Cockfield, Durham, England Wife Aberavon Glamorgan
	View Record Mary J Robson abt 1876 Darlington, Durham, England Daughter Aberavon Glamorgan 
	
http://en.wikipedia.org/wiki/John_Oxx
There is a christening for John Oxe on: 20 JAN 1782 Saint Mary, Woodbridge, Suffolk, England. Likely to be the same one.
	Parents are John Oxe and Frances.

	There was a school for seafarers in Woodbridge which John may have attended. 

	John was awarded a silver cup which is still in the family for being the first to bring coal from Newcastle to Woodbridge in 1811. The cup bears the inscription "The gift of the owners of Fandon Colliery to Captn. John Oxx of the Commerce of Woodbridge, for introducing the first cargo of Newcastle Wallsend Coals into that Port in August 1811." The Commerce of Woodbridge is the name of the ship.

	A John Oxx married Mary Harris in St. Mary, Warwick on 4 November 1828 which would have been 2 years after Woodhouse"s death in 1826. If it is the same John how did he get to Warwick? Was he a widower on marriage? Did he have any further children? A Mary Oxx, widow, later married William Hull, widower Feb 8 1857 in the district of Newport.

	At time of marriage of Robert Robson and his daughter Mary Oxx and his death his occupation is stated as "Master Mariner".

	Spelling of the Oxx surname seems to have been standardised around 1800. Hence the change of surname from Oxe.

	He died of inflammation of the brain.

[[http://en.wikipedia.org/wiki/John_Ramsay,_1st_Earl_of_Holderness]]
The marriage certificate of Robert Robson and Mary Holder Oxx states John Robson as father and deceased.

	Possible death from Long Benton parish records..
	14 Jan 1836  John Robson of Walker aged 44
	Familyhistoryonline.net says he was buried at St Bartholomew:
	Parish Longbenton, St. Bartholomew, NBL Buried 14/01/1836 Name John ROBSON aged 44 Abode Walker

	This would mean he was born before 14 Jan 1792. So it is likely he was born in 1791.

	<h4>Research into his birth..</h4>
	If born in 1791:
	///////////////
	1. Baptised 17/04/1791 Child"s name John ROBSON Father John Mother – Mother"s Maiden name – Place Cocklaw St.John Lee Occupation – Other info – Father – Mother – Notes – Birth date –/–/– Parish Chollerton, Nbl Checked Checked
	Amount paid £0.07
	2. Baptised 17/Ap/1791 Child"s name John ROBSON Father John Mother – Mother"s Maiden name – Place Cocklaw St. John Lee Occupation – Other info – Father – Mother – Notes – Birth date –/–/– Parish Chollerton, Nbl Checked Checked
	Amount paid £0.07
	3. Baptised 29/05/1791 Child"s name John ROBSON Father William Mother Jane Mother"s Maiden name – Place Slaley Occupation – Other info – Father – Mother – Notes – Birth date –/–/– Parish Slaley, Nbl Checked Checked : checking on Familysearch.org shows mother maiden name to be ROBERTS, siblings Barbara, Mary, Jane, William.
	note this match is unlikely due to Slaley being 25miles away from Walker.
	4.  11 DEC 1791   	Harrington, Cumberland, England : parents John Robson and Jane
	5. 08 DEC 1791    	Bridlington, Yorkshire, England : parents Joseph and ?
	6.  Christening:  15 FEB 1791   	Sedgefield, Durham, England : George & Mary
	7.  Birth: 04 SEP 1791  	Kirk Andrews Upon Esk, Cumberland, England Matthew Robson & Mary Wright
	8. Christening:  	14 AUG 1791  	Stainton In Cleveland, Yorkshire, England parents: John Robson 
	If born in 1792
	/////////////////
	There is a christening at All Saints Church..
	25 MAR 1792  	All Saints, Newcastle Upon Tyne, Northumberland, England
	- this would mean however that John was approx 43 yr 11months when he died.. unless he was born in January over 2 months before the christening.
	Parents Thomas Robson & Mary Anderson
	Thomas was born About 1760  	Of, Newcastle Upon Tyne, Northumberland, England  	Newcastle Upon Tyne, Northumberland, England and married Mary Anderson (born 	About 1764  	Of, Newcastle Upon Tyne, Northumberland, England) on 06 FEB 1791   	Newcastle Upon Tyne, Northumberland, England
	They had at least one more child Elizabeth born 	08 JUL 1798  	Newcastle Upon Tyne, Northumberland, England.
	Another..
	  	22 DEC 1793  	All Saints, Newcastle Upon Tyne, Northumberland, England
	Parents John and Margaret



	///
	Possible marriages:
	8. Parish Horton alternatively – in county Nbl Married on 12/03/1820 Groom John Robson residence GOS other – Bride Jane Watson.
	Probably not though - as Robert was born in January 1820. A possible baptism of George however can be found in Durham: 23 Jan 1825  ROBSON, George Watson; child of John and Jane


It is believed he had a wife Jane. Jane can be seen as widowed in an early census with the children.

He is believed to have died the year before the census's began. :( I seem to have lost the source of this information. Believe the death was recorded in a parish record.
Married Mary.

	This family tree line is NOT known to be directly connected to my line.
Births from 1910-1920:
	9 Robson John H Rees Neath.11a 1886 Birth 4 1911 
	10 Robson Walter R Rees Cardiff.11a 811 Birth 4 1919






Died at 96 Fitzroy Street, Ashton-u-Lyme. Was buried 5th February at St.Thomas.

	In 1881 census:
	 Name   	Relation  	Marital Status  	Gender  	Age  	Birthplace  	Occupation 	Disability
	 Joseph GARTSIDE  	 Head  	 M  	 Male  	 28  	 Saddleworth, York, England  	 Overseer In Woollen Mill  	  
	 Mary Alice GARTSIDE  	 Wife  	 M  	 Female  	 28  	 Saddleworth, York, England  	   	  
	 George Mallebieu GARTSIDE  	 Son  	 U  	 Male  	 5  	 Saddleworth, York, England  	 Scholar  	  
	 Hilton GARTSIDE  	 Son  	 U  	 Male  	 1  	 Saddleworth, York, England  	   	  

	Married at Christ Church, Denshaw.
Handweaver. Baptised 8 Jun 1794 at St. Thomas, Friarmere.
	Married at St Chad Rochdale.


Suspected to be a relation of Robert Robson... Interestingly in 1851 census he is living next door to Robert Robson and Mary Oxx.
	It is possible he married ANN FORSTER 30 APR 1843 Middlesbrough, Yorkshire, England. If this is the case his father is Solomon Robson.
	It may have been Ann Bell he married on 20 FEB 1842 All Saints, Newcastle Upon Tyne, Northumberland, England. If this is the case is father is Joseph Robson.
	The conclusion drawn is that his wife was Ann Forster/Foster as son Robert takes Foster as a middle name.

	1881 census has him living at No 15 William St, Swindon with following residents..
	Joseph ROBSON  	 M  	 Male  	 58  	 Newcastle On Tyne  	 Iron Moulder 
	 Ann ROBSON  	 M  	 Female  	 55  	 Stockton On Tees  	  
	 Saml. ROBSON  	 U  	 Male  	 20  	 Middlesborough, York, England  	 Boiler Maker 
	 Margaret ROBSON  	 U  	 Female  	 14  	 Middlesborough, York, England  	  
	 Martha KEEL  	 M  	 Female  	 23  	 Middlesborough, York, England  	  
	 Robert KEEL  	 M  	 Male  	 23  	 New Swindon, Wiltshire, England  	 Erector Engine (Fitter) 
	 Francis POWER  	   	 Male  	 2  	 London, London, Middlesex, England  	  









Three children..
Joan Spearman OXX (1917-)				
Evelyn Spearman OXX (1928-1996)				
Geoffrey Spearman OXX (1932-1953)




<<familytreelist sex:M>>
<<familytreelist sex:F>>

Lord Cullen is an ancestor of this Robson family. He is somehow related to the Spearmans/ Oxx"s.

	Link still to be confirmed.
Lived in Essex. Married in Chelmsford.

	Possibly related to this families:
	http://www.familysearch.org/Eng/search/frameset_search.asp?PAGE=ancestorsearchresults.asp http://www.familysearch.org/Eng/search/census/household_record.asp?HOUSEHOLD_CODE=1881BR_1807320&HOUSEHOLD_SUB=1&frompage=5
	http://www.familysearch.org/Eng/search/frameset_search.asp?PAGE=ancestorsearchresults.asp

	May have had older siblings unknown to us?





[[Explore]]


Died at Hillingdon Hospital, North London.

Father believed to be Adam Lyall.


Was involved in a law suit  concerning the estate of her deceased father Robert which he appeared to have won. (Please see [[Gilbert SPEARMAN]] for documentation).





m. Ramsay, John, Earl of Holdernesse 1st
m. Bertie, Montagu, Earl of Lindsey 2nd 18/04/162
Father believed to be Adam Lyall.
Born 1844/1842 in Batterknowie, Durham, England. Mother Isabella LYALL (born 1809 Jarrow, Durham) and she is believed to have at least 2 siblings Margaret (born 1841 in Cockfield, Durham) and Elizabeth Ann (born 1845 Wingate, Durham).

Married John George Robson.
Seven known children: Isabel, Robert William, Adam Lyall, Margaret Elizabeth (died young aged 5), Matthew Jackson, Mary Elizabeth and John George Robson (Junior).

The 1881 Census has her dwelling in Mossby Cottage, Workington, Cumberland, aged 38 with husband John George Robson and 4 of her children. See John George Robson for more details.

Died around 1928.

(Source: 1881 Census)
	The 1881 Census has her dwelling in Mossby Cottage, Workington, Cumberland, aged 38 with husband John George Robson and 4 of her children.

	Buried at Port Talbot.




Died at 96 Fitzroy Street, Ashton-u-Lyme and buried 5th February at St. Thomas, Friarmere

Died in 52nd year.

	Possibly married twice? Marriage 1 James WRIGLEY b: 11 Mar 1753 in Oldham - Married: 15 Sep 1772 in Oldham
Details of marriage:
"Charles was created Viscount Cullen in 1642 (fn. 231) and was in sole possession of the rectory in 1644, when his farmer was John Ward. (fn. 232) His son Brian, second viscount, (fn. 233) settled it in 1679 on the marriage of Mary, his daughter or sister, with Robert Peirson. "
From: "Parishes: Bishop Middleham", A History of the County of Durham: Volume 3 (1928), pp. 204-12. URL: http://www.british-history.ac.uk/report.asp?compid=42621. Date accessed: 07 August


surname Dyson may be incorrect.


Daughter of David Harrop of Bardsley.
	Buried 13 October 1746

Daughter of John Thomas.





Unconfirmed.
Death mentioned in a letter written by Robert Jackson.

	He seems to have sent money July 31st to Nov 31 1820 of £1 5 shillings - possibly for his son Robert?
In Sept 1824 his brother Robert in a letter says "I hope you will put my brother Matthew to serve trade which a man in this country are nothing thought of without he has a trade" this suggests to me that Matthew was unemployed.

	A Matthew Jackson appears in the 1861 census:
	Age: 50
	Estimated Birth Year: abt 1811
	Relation: Head
	Spouses"s Name: Elizabeth
	Gender: Male
	Where born: Jarrow, Durham, England

	Civil parish: Willington
	Ecclesiastical parish: Howdon
	County/Island: Northumberland
	Country: England

	Street address:Willington Quay

	Occupation: Stone Mason
	Elizabeth Jackson 48
	Margaret Ann Jackson 16
	Mary Jane Jackson 12
	Matthew Jackson 50
	Matthew Jackson 9

	The occupation and place of birth sounds correct.
In 1851:
	182 Wing Col Name Matthew LYALL Relationship So Condition U Age 18 Occupation blacksmith Birth place – DUR Piece 2392 Folio 153 Page – Place Easington District Easington Sub district Wingate County DUR Checked N

	In 1881 there is a Matthew Jackson Lyall an Iron Founder Master 40 Men Forge 50 Men 20 Boys Earthenware Manuf 48 Women lodging in 13 Hedworth Ter Bishopwearmouth, Durham, England with a family by the name of HUNTER:

	1. Name Thomas HUNTER Relationship Head Condition U Gender M Age 76 Occupation House Proprietor Birthplace Sunderland, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202
	2. Name Mary HUNTER Relationship Widow Condition W Gender F Age 62 Occupation House Proprietor Birthplace Witton Gil...t, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202
	3. Name Mary Jane HUNTER Relationship Daur Condition U Gender F Age 44 Occupation Shop Assistant Birthplace Sunderland, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202
	4. Name Sarah HUNTER Relationship Daur Condition U Gender F Age 30 Occupation Teacher Of Music Birthplace Sunderland, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202
	5. Name Joseph HUNTER Relationship Son Condition U Gender M Age 28 Occupation Mariner Birthplace Sunderland, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202
	6. Name Ann HUNTER Relationship Daur Condition U Gender F Age 25 Occupation Seamstress Birthplace Sunderland, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202
	7. Name Catherine HUNTER Relationship Daur Condition – Gender F Age 23 Occupation Shop Assistant Birthplace Sunderland, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202
	8. Name Louisa HUNTER Relationship Daur Condition – Gender F Age 20 Occupation Milliner Birthplace Sunderland, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202
	9. Name Elizabeth Moor HUNTER Relationship Daur Condition – Gender F Age 19 Occupation Shop Assistant Birthplace Sunderland, Durham, England Address 13 Hedworth Ter, Bishopwearmouth, Durham, England PRO ref RG11/4997 Folio 62 Page 13 FHL film no. 1342202

	He is unmarried and is said to have been born in Jarrow. This is likely to be the same one.

	In his life a John Brewis, solicitor, caused many problems for him regarding a sum of £350. The dispute is outlined in several letters still in possession in the family, which I am planning to transcribe and put on this website.

	A death certificate shows a Mathew Jackson Lyall died at 11 Teresa Terrace, Coatham, Redcar. He was an Iron founder and died of Hypostatic conjestion of lumps and senile decay. Interestingly, this is the house he was brought up in and he must have returned to it.

	Isabel Newton his neice was present at the death. She lived at 6 Gill Crescent, Risca, Monmouthshire.
The 1881 Census has him dwelling in Mossby Cottage, Workington, Cumberland, aged 3 with 3 siblings, mother and father.

	In 1901 he is living with his brother Robert William at Culla House as boarders to the owners David Llond (born 1853 Pembrey, Carmathenshire Wales) and Mary Jane Llond (born 1858 Pembrey, Carmarthenshire, Wales).













/***
|''Name:''| NiceTaggingPlugin|
|''Description:''| creates a nicer interface for adding and removing TiddlyWiki. Ideal for tiddly novices. |
|''Version:''|0.5|
|''Date:''|8 September 2009|
|''Source:''|http://www.jonrobson.me.uk/development/niceTagging|
|''Author:''|Jon Robson|
|''License:''|[[BSD open source license]]|
|''CoreVersion:''|2.3|
|''Dependencies:''|AdvancedEditTemplatePlugin|
***/

if(store){
  config.shadowTiddlers.NiceTaggingStyle = "/*{{{*/\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"+
  ".niceTagger input {width:200px; float:left;}\n"+
  ".deleter {color:red; font-weight:bold; padding:2px; cursor:pointer;}\n"+
  "/*}}}*/";
store.addNotification("NiceTaggingStyle", refreshStyles);
}


config.macros.niceTagger = {
	lingo:{
		add: "add"
	}
    ,saveTags: function(title,tags){
		var tiddler =  store.getTiddler(title);
		if(!tiddler) {
			store.saveTiddler(title,title,null,true,null,tags,config.defaultCustomFields,null);
			tiddler =  store.getTiddler(title);
		}
		store.setValue(tiddler,"tags",tags);
    }
    ,refreshTagDisplay: function(place,tiddler){
        jQuery(place).html("");
        var tags = tiddler.tags;
        for(var t=0; t < tags.length; t++){
            var tag = tags[t];
            jQuery(place).append(" <span class='tag'>"+tag+"</span> <span class='deleter' deletes='"+escape(tag)+"'>x</span>");
        }
        
        jQuery(".deleter",place).click(function(e){
            var todelete = jQuery(this).attr("deletes");
            var newtags = [];
            for(var i=0; i < tags.length; i++){
                if(escape(tags[i]) != todelete){
                   newtags.push(tags[i]);
                }
            }
            tiddler.tags = newtags;
            config.macros.niceTagger.saveTags(tiddler.title,tiddler.tags);
            
            config.macros.niceTagger.refreshTagDisplay(place,tiddler);
        });
    }
    ,handler: function(place,macroName,paramlist,wikifier,paramString,tiddler){
        var displayer = document.createElement("div");
        displayer.className = "niceTagger";
        place.appendChild(displayer);
        config.macros.niceTagger.refreshTagDisplay(displayer,tiddler);
        var tagplace = document.createElement("div");

        place.appendChild(tagplace);
        var saveNewTag= function(value){
          if(value.replace(" ","").length == 0) return;
		  if(tiddler.tags.indexOf(value) != -1) return;
            tiddler.tags.push(value);
            config.macros.niceTagger.refreshTagDisplay(displayer,tiddler);
            adder.value = "";
            config.macros.niceTagger.saveTags(tiddler.title,tiddler.tags);
        };
        var adder;
        if(config.macros.AdvancedEditTemplate){
            //config.macros.AdvancedEditTemplate.handler(tagplace,null,null,null,"aet type:search metaDataName:assignby valuesSource:Suggestions");
             var params = paramString.parseParams("anon",null,true,false,false);
			 var textcase = getParam(params,"case");
            var srcTiddler = getParam(params,"valuesSource");
            var suggestions = [];
            if(srcTiddler){
                var text = store.getTiddler(srcTiddler).text;
                var tempdiv = document.createElement("div");
                wikify(text,tempdiv);
                suggestions = jQuery(tempdiv).html().split("<br>");
            }
            if(textcase && textcase == "lower"){
              for(var i=0; i < suggestions.length;i++){
                suggestions[i] =suggestions[i].toLowerCase();
              }
            }
		var tagsoff = getParam(params,"nostoretags");
		if(!tagsoff) suggestions = suggestions.concat(config.macros.niceTagger.twtags);
		
		
		var uniqueSuggestions = [];
		for(var i=0; i < suggestions.length; i++){
			var s =suggestions[i];
			//rtrim then ltrim
			s = s.replace(new RegExp("[\\s]+$", "g"), "").replace(new RegExp("^[\\s]+", "g"), "");
			//console.log(uniqueSuggestions.toString(),s,uniqueSuggestions.indexOf(s));
				if(uniqueSuggestions.indexOf(s) ==-1){
					uniqueSuggestions.push(s);
				}
		}
		//console.log(uniqueSuggestions);
           config.macros.AdvancedEditTemplate.createSearchBox(tagplace,"tags",uniqueSuggestions,"",function(v){saveNewTag(v);jQuery("input",tagplace).val("");})
           adder = jQuery("input",tagplace)[0];
			
		
        }
        else{
            adder = document.createElement("input");

            tagplace.appendChild(adder);
            
        }
		jQuery(adder).keypress(function (e) {
			if(e.which == 13){
				var results = jQuery(".ac_over",".ac_results"); //is anything highlighted in autocomplete plugin
				if(results.length ==0)
		
					saveNewTag(adder.value);
			}
		});
        var addbutton = document.createElement("button");
        addbutton.innerHTML = config.macros.niceTagger.lingo.add;
		addbutton.className = "adder";
        tagplace.appendChild(addbutton);
        

        jQuery(addbutton).click(function(e){
            var val = adder.value;
            saveNewTag(val);
        });
        
        
        
    },
	twtags:[]
    
};

var x= store.getTiddlers();
for(var i=0; i < x.length; i ++){
	var y = x[i].tags;
	config.macros.niceTagger.twtags = config.macros.niceTagger.twtags.concat(y);
};






These options for customising your family tree are saved in your browser.

<<option chkSaveBackups>> [[SaveBackups]]
<<option chkAutoSave>> [[AutoSave]]

<!--{{{-->
<div class='ftTitle' refresh='content' force='true' tiddler='SiteTitle'></div>
<div class='ftSubTitle' refresh='content' force='true' tiddler='SiteSubtitle'></div>
<div macro="FamilyTree">

</div>

<div class='ftContainer'>
	<div id='topToolbar' tiddler='topToolbar' refresh='content'></div>
	<div id='sidebar'>
		<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
		<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
	</div>
	
	<div id='displayArea'>
		<div class='ftHideCorner'></div>
		<div id='messageArea'></div>
		<div id='tiddlerDisplay'></div>
		
	</div>

</div>
<!--}}}-->









Richard died young leaving his wife with a large family to bring up. Birth date is only a guess
Died 30th July 1930 in Llanwnda, Carnarvonshire, Wales.

	Richard worked on the railway at various stations.
	Swansea in 1877; Neath "79 "87, "89 & "94; Penzance "85; Glyn Neath "92 and Duffryn Yard "98.

	He seemed to be a bit of a trouble maker, receiving many fines and cautions! He also received several injuries from his work from sprained ankle to his middle finger being amputated in January 1914.


Did he marry? A census record shows Robert (Coke Drawer) born 1851 married to Elizabeth with childrne Mary Ellen, Martha Ann? It would seem strange he didn"t use his middle name if he had one. This also gos on the premise that Robert Robson had a sibling Sarah Jane (born 1858) which he didn"t


1851 census shows him living in Middlesbrough with his father, mother, and 2 brothers Joseph and George.
	Later in the 1881 census he is living in Swindon at No 13 William St - 2 doors down from his father with his 3 children Jane Elizabeth and Florence and wife.





The 1881 Census shows Robert, 28, born Chepstow, a Railway Engineer, resident in Bristol, Gloucestershire, England, with his wife Esther, 29, born Carmarthen, and their three children, Frederick Charles, 6, a scholar, born in Bristol, Sarah Jane, 4, born in Wells, Somerset, and George William, 11 months old, born Bristol. 

	1888 Death in the Registration District of Barton Regis in the City and County of Bristol

	6 March 1888, 13 Edward Street, Robert Morgan Brew, male, 36 years, Railway Engine Driver, cause of death: pneumonia, informant: E. Brew, widow of deceased, present at death, 13 Edward Street, Bristol, Arthur Hunt, Registrar.
	
Died before 29 October 1703, as a lawsuit was filed over property of his land on this date.

Married Mary Cokayne
One known child: Margaret

Owned an estate which was obviously of some importance, since it was the topic of a lawsuit filed by his son-in-law Gilbert Spearman.

Born 1820 in Plessey[1], Newcastle, Northumberland, England. Plessey being an area of Stannington.
	There is a conflicting birth date of 15th May 1820 on familysearch. But I think this is possibly incorrect as this was the date he married. The birth date given (of January 7th) was found on family tree passed down.

	Married Mary Holder Oxx 15th May 1842. The marriage is registered as being in Newcastle on Tyne district, Northumberland. The church married at is All Saints Church (built: 1786-96). Both Mary and Robert were in residence at Saint Anthony at time of marriage. It was witnessed by Ralph John Wilkinson and Jos. Peason/Pearson.

	Within the period of 1847-1850 he went to Nassau, Germany where he had his child Hannah Mary. The reason for this is unknown.
	In 1851 census he is shown to be living with wife Mary and children John George, William Isaac, Harriet Jane and Hannah Mary. Cooincidentally (??) he is living next door to another Robson - Joseph. He is living in Middlesbrough.

	In 1854 his registered address was Rostock Terrace, Middlesbrough.

	In 1877 he was living at 43 Guerney Street Darlington

	His daughter Frances birth and marriage certificates have Robert Robson working as a Roll Turner.

	The 1881 census has him as a 61 year old widow living with his daughter Hannah (now Bulmer) and her husband James at 40 Henry St, Darlington and 2 grandchildren working as a mechanic at engine works.

	His exact death is unknown, however, it is possible he died in Darlington in June 1884, aged 64.

	Sources:
	[1] 1851 census
Type the text for 'New Tiddler'



Married an Elizabeth






Baptised 28 March 1794 at Lane Ind., Holmfirth

Married 18 November 1844

christened 1 June 1834, and died 26 March 1903 

	Sarah married Thomas Godfrey, a soldier, in Aldershot, Hampshire, on 26 February 1861. Thomas was born in Southam, Warwickshire, on 14 August 1834 to William Godfrey and Sarah Wells.

	Thomas left the army in 1873. They became missionaries of the Church of Latter Day Saints and emigrated to the United States. Sarah died in Fairview, Lincoln, Wyoming, U.S.A. on 26 March 1903, and Thomas predeceased her in Acapules, Mexico, on 29 July 1902.

	Sarah and Thomas had eight children. Sarah gave birth to their first two children in England, after which they moved to Ireland, where the next two children were born, and then on to Scotland, where a further two were born, before their emigration to the United States, where the last two children were born.





Type the text for 'New Tiddler'
<<search>><<slider chkSliderOptionsPanel OptionsPanel "options »" "Change TiddlyWiki advanced options">>


Was slain at the Battle of Shrewsbury, Shropshire, on July 21st, 1403, and he was buried at Ashbourne, Derbyshire. He married Elizabeth de Herthull, who was the daughter and heiress of Sir Richard de Herthull. Elizabeth de Herthull married second John Franceys. Edmund Cokayne and Elizabeth de Herthull had five known children.

Sir Edmund Cokayne was of Ashbourne, Derbyshire, and Pooley, Warwickshire.

Sir John Cokayne was of Ashbourne, Derbyshire, and Pooley, Warwickshire. He was a Commissioner of Assay, and an M.P. for Derbyshire.

He was buried in St. Paul"s Cathedral, The City, London, England.

	Sir William Cokayne held the office of Lord Mayor of London from 1619 to 1620.1 He lived in Cokayne House, Old Broad Street, London, England.
Possibly born in Rushton, Northants, or originated from this location.

Sir Willliam Cokayne was knighted on June 8th, 1616.

He was apprenticed to his father at Christmas, 1582, and he was made free of the Skinners' Company by patrimony on March 28th, 1590. 

He amassed a great fortune and purchased numerous estates, including Rushton Hall, Northamptonshire. He gave each daughter £10,000 on marriage, and he left his son a rent roll of above £12,000 a year.

He was Sheriff of London in 1609, an Alderman from 1609 to his death, and Lord Mayor of London from 1619 to 1620.

In 1612, King James I granted a considerable tract of land in Ulster to the City of London, and William was appointed Governor, the City of Londonderry being founded under his direction. He worked as a London merchant and financer before that.

William Cokayne and Mary Morris were married at St. Leonard Eastcheap, City of London, where Mary had been baptized.

Sir William Cokayne died at his manor house at Comb Nevill in Kingston, Surrey. He was buried at St. Paul's, and a monument in St. Paul's Cathedral recorded his death at age 66 on Oct. 20th, 1626. However, under a copy of the funeral address by Dr. Donne, the date of death was given as December, 1626. His burial at St. Paul's Cathedral was recorded in the Parish registers of St. Peter Le Poer, City of London.
get yours [[here|http://www.jonrobson.me.uk/development/familytree/index.html]]
robson tree
(4 children: Sonia, Richard, Nicola, Sara)

.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:20px;}
#topToolbar {margin-top:10px;margin-left:-12px;}
#messageArea {background:#39ac1b;border:1px solid white;}
.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:absolute;
top:160px;
z-index:2;}
.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:solid 1px black;}
.tiddler .button {padding:1.2em 2em;}
.sexMale .title {border-bottom:solid 5px #71B4FF;}
.sexFemale .title{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;}
.ftTitle {color:#39ac1b;font-size:108px;left:10px;position:relative;font-weight:700;}
.ftContainer {background-color:#39ac1b;padding:20px;position:relative;top:-26px;margin-right:17px;left:10px;}
#sidebarOptions .sliderPanel {background-color:#EEEEEE;}
.ftTitleBG {color:white;z-index:2;}
.ftContainer #displayArea {background-color:auto;}
.ftContainer #sidebar {background-color:white;margin-top:110px;margin-right:40px;}
.ft_tooltip {background-color:white;padding:10px;color:#39ac1b;z-index:40; font-weight:bold;}
#tiddlerDisplay {margin-top:100px;}
.FamilyTree {left:600px;right:7px;height:200px;position:absolute;background-color:#39AC1B;top:0;}
.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;
}
.VismoCanvas {z-index:11;}
.changeroot {margin-left:50%;width:200px;right:100px;z-index:4000;position:relative;}

.yourSearchNaviBar .currentPage {color:#39AC1B;}

#yourSearchResult {background-color:#EEEEEE;background:#EEEEEE none repeat scroll 0 0;}
.yourSearchResult .button {padding:0px;}


Daughter of Robert Buckley of Grasscroft.
	Will proved 1711.
/***
|Name|TaggedTemplateTweak|
|Source|http://www.TiddlyTools.com/#TaggedTemplateTweak|
|Documentation|http://www.TiddlyTools.com/#TaggedTemplateTweakInfo|
|Version|1.5.1|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides|Story.prototype.chooseTemplateForTiddler()|
|Description|use alternative ViewTemplate/EditTemplate for tiddler's tagged with specific tag values|
This tweak extends story.chooseTemplateForTiddler() so that ''whenever a tiddler is marked with a specific tag value, it can be viewed and/or edited using alternatives to the standard tiddler templates.'' 
!!!!!Documentation
>see [[TaggedTemplateTweakInfo]]
!!!!!Revisions
<<<
2009.01.06 [1.5.1] reversed logic so that title-as-prefix takes precedence over tag-matched prefix
2008.12.18 [1.5.0] added handling for using tiddler //title// as prefix (e.g., {{{SomeTiddlerViewTemplate}}}) 
| please see [[TaggedTemplateTweakInfo]] for previous revision details |
2007.06.11 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.TaggedTemplateTweak= {major: 1, minor: 5, revision: 1, date: new Date(2009,1,6)};

Story.prototype.taggedTemplate_chooseTemplateForTiddler = Story.prototype.chooseTemplateForTiddler
Story.prototype.chooseTemplateForTiddler = function(title,template)
{
	// get default template from core
	var coreTemplate=this.taggedTemplate_chooseTemplateForTiddler.apply(this,arguments);

	// if the tiddler doesn't exist yet, return core result
	var tiddler=store.getTiddler(title); if (!tiddler) return coreTemplate;

	// split core template into theme prefix and template name
	var theme="";
	var template=coreTemplate;
	var parts=template.split(config.textPrimitives.sectionSeparator);
	if (parts[1]) { theme=parts[0]; template=parts[1]; }
	else theme=config.options.txtTheme||""; // fallback if theme is not specified
	theme+=config.textPrimitives.sectionSeparator;

	// look for template whose prefix matches the *title* of this tiddler
	if (!store.getTaggedTiddlers(title).length) { // if tiddler is not a tag
		if (store.getTiddlerText(theme+title+template)) { return theme+title+template; } // theme##TitleTemplate
		if (store.getTiddlerText(title+template)) 	{ return title+template; }	 // TitleTemplate
	}

	// look for template whose prefix matches a *tag* on this tiddler (if any)
	for (i=0; i<tiddler.tags.length; i++) {
		var t=tiddler.tags[i]+template; // add tag prefix to template
		var c=t.substr(0,1).toUpperCase()+t.substr(1); // capitalized for WikiWord title
		if (store.getTiddlerText(theme+t))	{ return theme+t; } // theme##tagTemplate
		if (store.getTiddlerText(theme+c))	{ return theme+c; } // theme##TagTemplate
		if (store.getTiddlerText(t)) 		{ return t; }	    // tagTemplate
		if (store.getTiddlerText(c))		{ return c; }	    // TagTemplate
	}

	// no matching tag OR title prefix... return core result
	return coreTemplate;
}
//}}}

Died by assassination.

An Iron Merchant Clerk, (born in Heigington Durham on 1st March 1877) at Bondgate Wesleyan Chapel, Darlington.

Thomas Bellwood died 26th April 1901 at Stockton having drowned in the River Tees.
Thomas was deaf and apparently never married.
Christened 4th December 1791 in Chepstow. Died 22nd April 1840. Buried 5 days later in Chepst, 27th April by curate Mr. Sand. Death certificate says died of consumption, a boatman at the time. Mary Ann his daughter was present at death. 

	Thomas was a seaman/merchant. He is also recorded has having a ropemaker apprenticeship.
Christened in Chepstow on 7 January 1821.

Had the following known children:
Thomas COKAYNE m. Frideswyde PUREFOY

William COKAYNE
m. Eleanor LLYOD
m2. Elizabeth 08/06/1626

Alice COKAYNE
m. Henry SHERAT 13/12/1591

Alice COKAYNE
m. Thomas ROBINSON
Possibly a brother of [[Adam Lyall]]? Mentioned in letters.


married Elizabeth


|~ViewToolbar|closeTiddler addFather addMother addSpouse addChild +editTiddler > fields permalink|
|~EditToolbar|+saveTiddler -cancelTiddler deleteTiddler|

Turlogh married Joan Fitzmaurice.




  Tairrdelbach I, High King of Ireland gained the title of  King Turough of Munster. He succeeded to the title of  High King Tairrdelbach I of Ireland in 1072. [1]

[1] [S38] John Morby, Dynasties of the World: a chronological and genealogical handbook (Oxford, Oxfordshire, U.K.: Oxford University Press, 1989), page 76. Hereinafter cited as Dynasties of the World.



This line is not necessarily connected to the Robson family tree however in 1851, his son is living next door to Robert Robson (who is an ancestor). I was curious to whether the two people were related in anyway but as of yet have found no evidence to support this theory.

	If the marriage of Joseph Robson and Mary Foster is correct then this person is called Solomon Robson.

<!--{{{-->
<div macro='tiddlerGender'>
<div class='tiddlerContainer'>
<div class='toolbar' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></div>
<div><span class='title' macro='view title'></span>&nbsp;<span macro='makeRootLink'></span></div>
<span macro='aet if:dob|dod'>(<span macro='view dob'></span><span macro='aet if:dod'>-</span><span macro='view dod'></span>)</span>

<div class='subtitle'>last modified <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='subtitle'>
<span macro='aet if:mother|father'>Child of</span>
<span macro='view father link'></span>
<span macro='aet if:father&mother'>and</span>
<span macro='view mother link'></span> 
<br/>
<span macro='aet if:spouse'>Spouse(s): </span><span macro='ftview spouse'></span>

</div>
<h3>Children of <span macro='view title'></span></h3>
<div macro='listchildren'></div>
<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></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 macro='view dob'></span> </span>
  <span macro='aet if:placeofbirth'>in </span><span macro='view placeofbirth'></span></div>

<div><span macro='aet if:occupation'>occupation </span><span macro='view occupation'></span></div>
<div>
<span macro='aet if:dod'>died </span><span macro='view dod'></span>
<span macro='aet if:placeofdeath'> in</span><span macro='view placeofdeath'></span>
</div>
</div>

<h3>Further Information</h3>
<div class='viewer' macro='view text wikified'></div>

<div class='tagClear'></div>
</div>
</div>
<!--}}}-->


/***
|''Name:''|Jon Robson's VismoLibrary|
|''Description:''|An opensource library of javascript code designed to create clickable graphics in canvas with VML alternative for Internet Explorer browsers. The purpose of this is to provide hackable, extendable graphics based plugins without being locked in to consumer products such as Flash.|
|''Author:''|JonRobson (http://www.jonrobson.me.uk/Vismo)|
|''CodeRepository:''|http://svn.tiddlywiki.org/Trunk/contributors/JonRobson/Library/Vismo/|
|''Version:''|0.9 |
|''Dependencies:''| Requires jQuery|
|''Comments:''|Please raise questions and make comments at http://groups.google.co.uk/group/TiddlyWikiDev |
|''License:''|[[BSD License|http://www.opensource.org/licenses/bsd-license.php]] |
|''Usage:''|
Not much good on it's own - it provides some nice functions to create graphicsy plugins.
Currently provides horsepower to the following plugins amongst others:
GeoTiddlyWiki (http://www.jonrobson.me.uk/workspaces/tiddlers/GeoTiddlyWiki/), ImageTaggingPlugin, TiddlyTagMindMap (http://tiddlytagmindmap.tiddlyspot.com)
!Wouldn't have been possible without..
http://spatialreference.org/ref/sr-org/google-projection/ for help with google projection hack
***/
var VismoOptimisations = {
    minradius:5,
	packCoordinates: function(coordlist){
		var res = [];
		for(var i=0; i < coordlist.length-1; i+=2){
			res.push([coordlist[i],coordlist[i+1]]);
		}
		
		return res;
	}
	,unpackCoordinates: function(coordlist){
		var res = [];
		for(var i=0; i < coordlist.length; i+=1){
			res.push(coordlist[i][0]);
			res.push(coordlist[i][1]);
		}
		return res;	
	}
	//coords in form [[x1,y1],[x2,y2]]
	,douglasPeucker: function(coords,tolerance, start,end){
		var results = [];

		if(!start) start = 0;
		if(!end) end = coords.length - 1;
		if(start >= coords.length || end >= coords.length || start == end -1){
			return [];
		}	
		var midpoint = {};
	
	
		midpoint.x = (coords[end][0] + coords[start][0]) /2;
		midpoint.y = (coords[end][1] + coords[start][1]) /2;
		
		var bestPoint = {distance:-1, index:-1};
		for(var i=start+1; i < end; i++){
			var x = coords[i][0];
			var y = coords[i][1];
			var deltax = midpoint.x - x;
			var deltay= midpoint.y - y;
			
			var perpendicular_d = Math.sqrt((deltax * deltax ) + (deltay *deltay)); //this is not perpendicular distancd.. i think!
			if(perpendicular_d > bestPoint.distance){
				bestPoint.index = i;
				bestPoint.distance = perpendicular_d;
			}
		}
	
		if(bestPoint.index ==-1 || bestPoint.distance<tolerance){
			var res = [];
			res.push(coords[start]);
			//res.push(coords[end])
			return res; //none of these points are interesting except last
		}
		else{
			results.push(coords[start]);
			var ref = bestPoint.index;
			var splice1 = VismoOptimisations.douglasPeucker(coords,tolerance,start+1,ref);
			var splice2 = VismoOptimisations.douglasPeucker(coords,tolerance,ref,end);
			results = results.concat(splice1);
			results = results.concat(splice2);
			results.push(coords[end]);
			return results;
		}
		
	}
  
	,vismoShapeIsInVisibleArea: function(vismoShape,canvas,transformation){
	    var t1= new Date();
		var left = 0,top = 0;
		var right =  parseInt(canvas.width) + left; 
		var bottom = parseInt(canvas.height) + top;
		var topleft =  VismoClickingUtils.undotransformation(left,top,transformation);
		var bottomright =  VismoClickingUtils.undotransformation(right,bottom,transformation);				
		var frame = {};
		frame.top = topleft.y;
		frame.bottom = bottomright.y;
		frame.right = bottomright.x;
		frame.left = topleft.x;
		var g = vismoShape.getBoundingBox();
		var t2 = new Date();
        VismoTimer["shape_visiblearea"] += (t2-t1);
           
		if(g.x2 < frame.left) {
			return false;}
		if(g.y2 < frame.top) {
			return false;}
		if(g.x1 > frame.right){
			return false;
		}
		if(g.y1 > frame.bottom){
			return false;	
		}
		
		return true;
	}
	
	,vismoShapeIsTooSmall: function(vismoShape,transformation){
	    VismoTimer.start("VismoOptimisations.vismoShapeIsTooSmall");

		if(!transformation ||!transformation.scale) {
		    VismoTimer.end("VismoOptimisations.vismoShapeIsTooSmall");
		    return false;
		}
		var g = vismoShape.getBoundingBox();
		var s = transformation.scale;
		var t1 = (g.width) * s.x;
		var t2 =(g.height) * s.y;

       
		if(t2 < this.minradius&& t1 < this.minradius) 
			{
			  VismoTimer.end("VismoOptimisations.vismoShapeIsTooSmall");
                    return true;}//too small
		else{
		   VismoTimer.end("VismoOptimisations.vismoShapeIsTooSmall");
			return false;
		}
		VismoTimer.end("VismoOptimisations.vismoShapeIsTooSmall");
	}

};window.onbeforeunload =function(){
    try{
        VismoUtils.scrubNodes(window.documentElement);
        
        if (window.CollectGarbage) {
    	    window.CollectGarbage();
        }
    }
    catch(e){
        //get over it
    }
};

Array.prototype.contains = function(item)
{
	return this.indexOf(item) != -1;
};
Array.prototype.clone = function () {var a = new Array(); for (var property in this) {a[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return a};

if(!Array.indexOf) {
	Array.prototype.indexOf = function(item,from)
	{
		if(!from)
			from = 0;
		for(var i=from; i<this.length; i++) {
			if(this[i] === item)
				return i; 
		}
		return -1;
	};
}

var VismoShapeUtils ={
    randomColor: function(alpha){
       var r = parseInt(Math.random() * 255);
       var g = parseInt(Math.random() * 255);
       var b = parseInt(Math.random() * 255);
       var a;
       if(alpha) var a = parseInt(Math.random() * 255);
       else a = 1;
       return "rgba("+r+","+g+","+b+","+a+")";
    }
    ,_isCoordinate: function(c){
        if(c == "M" || c == "q" || c== 'c') return false;
        else {
            if(typeof(c)== 'number') return true;
        }
    }
    
    ,toHex: function(rgba){
        if(rgba.indexOf("rgba") == 0){
            rgba = rgba.replace("rgba(","");
            rgba = rgba.replace(")","");
        }
        else if(rgba.indexOf("rgb")==0){
             rgba = rgba.replace("rgb(","");
        }
        
        rgba = rgba.replace(")","");
        rgba = rgba.split(",");
        return "#"+this._tohexadecimal(rgba[0])+this._tohexadecimal(rgba[1]) +this._tohexadecimal(rgba[2]);
    }
    ,_tohexadecimal: function(N){
        if (N==null) return "00";
        N=parseInt(N); if (N==0 || isNaN(N)) return "00";
        N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
        return "0123456789ABCDEF".charAt((N-N%16)/16)
             + "0123456789ABCDEF".charAt(N%16);
        
    }
    ,opacityFrom: function(rgba){
 
        var rgbcode = rgba.replace("rgba(","");
	    rgbcode = rgbcode.replace(")","");
	    rgbcode = rgbcode.split(",");
	    var opvalue = 0;
	    if(rgbcode.length < 4) opvalue = 1;
	    else opvalue =rgbcode[3];
	    
	    return opvalue;
    }
    ,toRgb: function(hex_rgba,opacity){
        var rgb = {};
        if(hex_rgba.indexOf("#") == 0 && hex_rgba.indexOf(",") == -1){ //hex code argument
            var hex = hex_rgba;
			var hexcode = hex.substring(1);
			rgb.red = this._hexToR(hexcode);
			rgb.blue = this._hexToB(hexcode);
			rgb.green = this._hexToG(hexcode);
		}
		else if(hex_rgba.indexOf("rgba") != -1){
		    var rgbcode = hex_rgba.replace("rgba(","");
		    rgbcode = rgbcode.replace(")","");
		    rgbcode = rgbcode.split(",");
		    rgb.red =rgbcode[0];
		    rgb.green =rgbcode[1];
		    rgb.blue =rgbcode[2];
		    opacity = rgbcode[3];
		}
		return {rgb:"rgb("+rgb.red+","+ rgb.green +","+ rgb.blue+")",opacity:opacity};
	}    
    ,toRgba: function(hex,opacity){
        var rgb = {};
        if(hex.indexOf("#") == 0 && hex.indexOf(",") == -1){ //hex code argument
			var hexcode = hex.substring(1);
			rgb.red = this._hexToR(hexcode);
			rgb.blue = this._hexToB(hexcode);
			rgb.green = this._hexToG(hexcode);
		}
		if(!opacity) opacity = "1.0";
		return "rgba("+rgb.red+","+ rgb.green +","+ rgb.blue+"," + opacity+")";
    }
	/* thank you http://www.javascripter.net/faq/hextorgb.htm*/
	,_cutHex: function(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
	,_hexToR:function(h){return parseInt((this._cutHex(h)).substring(0,2),16)}
	,_hexToG: function (h) {return parseInt((this._cutHex(h)).substring(2,4),16)}
	,_hexToB:function(h) {return parseInt((this._cutHex(h)).substring(4,6),16)}

};
var VismoUtils = {
	userAgent: navigator.userAgent.toLowerCase(),
	clone: function(obj){

        if(!obj) return obj;
        if(obj.appendChild) return obj;
	    if(obj == null || typeof(obj) != 'object')return obj;

	    var temp = new obj.constructor(); // changed (twice)

	    for(var key in obj){
	        //console.log(key);
	        temp[key] = VismoUtils.clone(obj[key]);
	        //console.log(temp[key])
	    }

	    return temp;

	}
	,invertYCoordinates: function(coords){
		var res = [];
		for(var i=0; i < coords.length; i++){
			var x = coords[i][0];
			var y = coords[i][1];
			res.push([x,-y]);
		}
		return res;
	},
	scrubNode: function(e)
    {
    	if(!VismoUtils.browser.isIE)
    		return;
    	var att = e.attributes;
    	if(att) {
    		for(var 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) {
    		 VismoUtils.scrubNode(c);
    		c = c.nextSibling;
    	}
    }
    
    ,mergejsons: function(prop1,prop2){
	    
	    var res = {};
	    var i;
	    for(i in prop1){
	        res[i] = prop1[i];
	    }
	    for(i in prop2){
	        res[i] = prop1[i];
	    }
	    return res;
	    
	}
};

VismoUtils.browser= {
		isIE: VismoUtils.userAgent.indexOf("msie") != -1 && VismoUtils.userAgent.indexOf("opera") == -1,
		isGecko: VismoUtils.userAgent.indexOf("gecko") != -1,
		ieVersion: /MSIE (\d.\d)/i.exec(VismoUtils.userAgent), // config.browser.ieVersion[1], if it exists, will be the IE version string, eg "6.0"
		isSafari: VismoUtils.userAgent.indexOf("applewebkit") != -1,
		isBadSafari: !((new RegExp("[\u0150\u0170]","g")).test("\u0150")),
		firefoxDate: /gecko\/(\d{8})/i.exec(VismoUtils.userAgent), // config.browser.firefoxDate[1], if it exists, will be Firefox release date as "YYYYMMDD"
		isOpera: VismoUtils.userAgent.indexOf("opera") != -1,
		isLinux: VismoUtils.userAgent.indexOf("linux") != -1,
		isUnix: VismoUtils.userAgent.indexOf("x11") != -1,
		isMac: VismoUtils.userAgent.indexOf("mac") != -1,
		isWindows: VismoUtils.userAgent.indexOf("win") != -1
	};

if(VismoUtils.browser.isIE && VismoUtils.browser.ieVersion[1] == "6.0"){
VismoUtils.browser.isIE6 = true;

}

if(VismoUtils.browser.isIE){
	if (!document.namespaces['vismoShapeVml_']) {
	        document.namespaces.add('vismoShapeVml_', 'urn:schemas-microsoft-com:vml'/*,"#default#VML"*/);
	        
	}
	document.namespaces.add('xmlns', 'http://www.w3.org/1999/xhtml');
	document.namespaces.add('svg', 'http://www.w3.org/2000/svg');
	document.namespaces.add('xlink', 'http://www.w3.org/1999/xlink');

	  // Setup default CSS.  Only add one style sheet per document
	 if (!document.styleSheets['vismoShape']) {
	        var ss = document.createStyleSheet();
	        ss.owningElement.id = 'vismoShape';
	        ss.cssText = 'canvas{display:inline;overflow:hidden;' +
	            'text-align:left;}' +
	            'vismoShapeVml_\\: * {behavior:url(#default#VML);}';
	}
}
VismoUtils.svgSupport = function(){
        if(VismoUtils.browser.isIE){
                try {
                 var asv = new ActiveXObject("Adobe.SVGCtl");
                 return true;
                }
                catch(e){ }
        }
        else if(document.implementation) {
                if(VismoUtils.browser.isSafari) return true;
                return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Shape", "1.0");
        }



        return true;
};
/* 
Creates primitive shapes that can be rendered across most browsers
I am not very happy with the code that follows. It is not of the best standard and needs much improvement
coordinates are a string consisting of floats and move commands (M)
*/

var VismoShape = function(properties,coordinates){
    this._isVismoShape = true;
    this.options = {pointsize:5};
    if(!coordinates) {
        coordinates = properties.coordinates;
        delete properties["coordinates"];
    }
    this._optimise_cache = {};
    
	this.coordinates = {
		projected: false,
		normal: [],
		optimised: {},
		optimisedandprojected:{}
	};
	this.grid = {};
	this.width = 0;
	this.height =0;
	this.properties = {};
	this.setProperties(properties);
	if(coordinates[0] && coordinates[0].length == 2){
		coordinates = VismoOptimisations.unpackCoordinates(coordinates);	
	}
	
	this._construct(properties,coordinates);
	this.browser =false;
	this.currentResolution = false;
	this.vml = false;
	this.unique_id = Math.random() + "_" + this.properties.id;
    this.scale = {x:1,y:1};
};



VismoShape.prototype={
    isCommand: function(i){
        if(i == 'M' || i =='b' || i =='q'){
            return true;
        }
        else{
            return false;
        }
    }
    ,clone: function(){
                var coords = this.getCoordinates("normal");
                var props = this.getProperties();
                var p = VismoUtils.clone(props);
                p.coordinates = coords;
                try{
                    //console.log(p);
                    return new VismoShape(p);
                }
                catch(e){
                    throw e;
                }
    }
    ,translate: function(x,y){
  	    var c = this.getCoordinates("normal");

  	    var newc = [];
  	    for(var i=0; i < c.length; i+=2){
  	         if(this.isCommand(c[i])) i+=1;
  	         var newx,newy;

  	        newx = c[i] + x;
  	        newy = c[i+1] + y;
  	        newc.push(newx);
  	        newc.push(newy);
  	    }

  	    this.setCoordinates(newc);
      }

  	,scale: function(x,y){
  	    this._scale.x = x;
  	    this._scale.y = y;
  	    var c = this.getCoordinates("normal");

  	    var newc = [];
  	    for(var i=0; i < c.length; i+=2){
  	        if(this.isCommand(c[i])) i+=1;
  	        var newx,newy;

  	        newx = c[i] * x;
  	        newy = c[i+1] * y;
  	        newc.push(newx);
  	        newc.push(newy);
  	    }

  	    this.setCoordinates(newc);
  	    return true;
  	}
	,resize: function(x,y){
	    var bb = this.getBoundingBox();
	    var newWidth = x *bb.width;
	    var newHeight = y * bb.height;
	    var offsetx = (bb.center.x * x) - bb.center.x;
	    var offsety = (bb.center.y * y)- bb.center.y;
	    this.scale.x = x;
	    this.scale.y = y;
	    var c = this.getCoordinates("normal");

	    var newc = [];
	    for(var i=0; i < c.length; i+=2){
	        var newx,newy;
	        
	        newx = c[i] * x;
	        newy = c[i+1] * y;
	        newx -= offsetx;
	        newy -= offsety;
	        newc.push(newx);
	        newc.push(newy);
	    }
	  
	    this.setCoordinates(newc);
	    return true;
	}
	,moveTo: function(x,y){
	    var st = this.properties.shape;
	    var dim = this.getDimensions();
	 
	    if(st == "point" || st == 'circle'){
	        this.setCoordinates([x,y,dim.width/2, dim.height/2]);
	    }
	    else if(st == 'polygon' ||st == 'path'){
	        var bb = this.getBoundingBox();
	        var movex = x - bb.center.x;
	        var movey = y - bb.center.y;
	        
	        var c = this.getCoordinates("normal");
	        var newc = [];
	        for(var i=0; i < c.length; i+=2){
	            if(this.isCommand(c[i])) i +=1;
	            newc.push(c[i]+movex);
	            newc.push(c[i+1]+movey);
	        }
	        this.setCoordinates(newc);
	    }
	}
	,getShape: function(){
		return this.getProperty("shape");
    }
	,setProperties: function(properties){
	    var newprops = VismoUtils.clone(properties);
		var i;
		for(i in newprops){
		        this.setProperty(i,newprops[i]);
		}
		if(!newprops["z-index"]){
		    this.setProperty("z-index","0");
		}
		if(!newprops.stroke){
			this.setProperty("stroke",'#000000');		
		}
		
	}
	,getBoundingBox: function(){ /* returns untransformed bounding box */
	    return this.grid;
	}
	,setPointSize: function(pointsize){
	    VismoTimer.start("VismoShape.setPointSize");
	    var st = this.properties.shape;
	    if(st != "point") return;
	    if(pointsize) {
		    this.options.pointsize = pointsize;
		    var bb= this.getBoundingBox();
		    this.setCoordinates([bb.center.x,bb.center.y,pointsize/2,pointsize/2]);
		}
		VismoTimer.end("VismoShape.setPointSize");
	}
	,render: function(canvas,transformation,projection,optimisations, browser,pointsize){
	    VismoTimer.start("VismoShape.render");
        this.setPointSize(pointsize); 
		var mode = this.getRenderMode(canvas);
		if(mode == 'ie'){
		     this.render_ie(canvas,transformation,projection,optimisations, browser);    
		}
		else{	
	        this.render_canvas(canvas,transformation,projection,optimisations, browser);
	        //this.render = this.render_canvas;
		}
		 VismoTimer.end("VismoShape.render");	
	}
	,render_ie: function(canvas,transformation,projection,optimisations, browser){
	    
	    VismoTimer.start("VismoShape.render_ie");
	    if(this.properties.hidden){
		        if(this.vml)this.vml.clear();
		        return;
		}
	    if(this.vml===false){ //not created
            this.vml = new VismoVector(this,canvas);
            this.donevml = true;
            
        }
        
           

		this.vml.render(canvas,transformation,projection);
        VismoTimer.end("VismoShape.render_ie");
        return;
	}
	,render_canvas: function(canvas,transformation,projection,optimisations, browser){
		VismoTimer.start("VismoShape.render_canvas");
		var c;
		if(this.properties.hidden) {
		    return;
    	}
    	var vismoShape = this;
    	var ctx = canvas.getContext('2d');
		if(!ctx) return;
		ctx.save();
		if(transformation){
			var o = transformation.origin;
			var tr = transformation.translate;
			var s = transformation.scale;
			var r = transformation.rotate;
			if(o && s && tr){
				ctx.translate(o.x,o.y);
				ctx.scale(s.x,s.y);
				ctx.translate(tr.x,tr.y);
			}
			if(r && r.x)ctx.rotate(r.x);
		}

		VismoCanvasRenderer.renderShape(canvas,vismoShape);
		ctx.restore();
		VismoTimer.end("VismoShape.render_canvas");
	}
	,getTransformation: function(){
	    var transform= this.getProperty("transformation");
	   
	    if(!transform) transform = {translate:false,scale:false};
   		if(!transform.translate)transform.translate = {x:0,y:0};
   		if(!transform.translate.x)transform.translate.x = 0;
   		if(!transform.translate.y)transform.translate.y = 0;
   		if(!transform.scale)transform.scale= {x:1,y:1};
   		if(!transform.scale.x)transform.scale.x = 1;
   		if(!transform.scale.y)transform.scale.y = 1;
	       
	       return transform;
	}
	
    ,setTransformation: function(transformation){
	    this.setProperty("transformation",transformation);
	    this._calculateBounds();
	}
	,setCoordinates: function(coordinates,type){
	    if(this.properties.shape == 'circle' || this.properties.shape == 'point'){
	        if(coordinates.length == 2 && this.coordinates.normal){
	            coordinates.push(this.coordinates.normal[2]);
	            coordinates.push(this.coordinates.normal[3]);
	        }
	    }	        
        var good = [];
        for(var i=0; i < coordinates.length; i++){
            if(coordinates[i] +"" !='NaN')
            {good.push(coordinates[i]);}
        }
     
        if(good.length < 2) {
                throw "cannot set coordinates for VismoShape not enough good coordinates given (coordinates may contain non-number elements)" + coordinates.toString();
        }
        coordinates = good;
                
                
		if(type == 'projected'){ 
		    this.coordinates.projected = coordinates;return;}
		
		this.coordinates.normal = coordinates;
	
		if(this.vml)this.vml.coordinatesHaveChanged();
		this.coordinates.projected= false;
		var i;
		for(i in this.coordinates_optimised){
			delete this.coordinates_optimised[i];
		}
		var j;
		for(j in this.coordinates.optimisedandprojected){
			delete this.coordinates.optimisedandprojected[j];
		}		
		this.grid = {}; //an enclosing grid
		
		if(this.vml) this.vml.path = false; //reset path so recalculation will occur
		var st = this.getShape();
		if(st== 'circle' || st == 'point'){
		    
		    if(coordinates[2] && coordinates[3]) this.setRadius(coordinates[2],coordinates[3]);
		    else this.setDimensions(this.options.pointsize,this.options.pointsize);
		}
		this._calculateBounds();

	}
	,getCoordinates: function(type){
		if(type == 'normal') return this.coordinates.normal;
	    if(type == 'projected') return this.coordinates.projected;
		
		var resolution = this.currentResolution;
		if(this.coordinates.projected) {
			if(this.browser != 'ie' && resolution){
				return this._simplifyCoordinates(resolution,this.coordinates.projected);
				var opt=this.coordinates.optimisedandprojected;
				if(!opt[resolution]) opt[resolution] =  this._simplifyCoordinates(resolution,this.coordinates.projected);
				
				return opt[resolution];
			}		
			return this.coordinates.projected;
		}
		else{
			if(this.browser != 'ie' && resolution){
				var opt=this.coordinates.optimised;
				if(!opt[resolution]) opt[resolution] =  this._simplifyCoordinates(resolution,this.coordinates.normal);
				
				return opt[resolution];
			}	
			return this.coordinates.normal;
		}
	}
	,getProperties: function(){
	    return this.properties;
	}
	,getRenderMode: function(canvas){
	    VismoTimer.start("VismoShape.getRenderMode");
	    if(!this.browser){
		    if(!canvas.getContext) {				
		                this.browser = "ie";
			}
				
			else 	this.browser = "good";
		}
		VismoTimer.end("VismoShape.getRenderMode");
		return this.browser;
	}
	
	,setProperty: function(name,value){
		this.properties[name] = value;
		 //console.log("Reset",name,this);
		 if(this.vml) {
		    this.vml.nochange = false;
	       
	    }
	    if(name == 'z-index'){ //organise a re-sort for the z-index property to kick in
	      if(Vismo.store.Canvas[this._canvasref]){
	        Vismo.store.Canvas[this._canvasref].needsSort = true;
	      }
	    }
	}
	,getProperty: function(name){
		return this.properties[name];
	}

	,_calculateBounds: function(coords){
	    VismoTimer.start("VismoShapes._calculateBounds");
	    var that = this;
		var st = this.getShape();
		var transform = this.getTransformation();

        
		if(st == 'path'){
			this.grid = {x1:0,x2:1,y1:0,y2:1,center:{x:0,y:0}};
			return;
		}
		else if(st == 'point' || st == 'circle' | st == 'image' | st == 'domElement'){
				var coords = this.getCoordinates("normal").clone();
				var x = coords[0]; var y = coords[1]; 
				var dim = this.getDimensions();
				this.grid.center = {};
				this.grid.center.x = x;
				this.grid.center.y = y;
				
				if(transform){
				        if(transform.translate){
				                var tran_x = transform.translate.x;
				                var tran_y =  transform.translate.y;
				                
				                this.grid.center.x += tran_x;
				                this.grid.center.y += tran_y;
				        }
				        if(transform.scale){
				                dim.width *= transform.scale.x;
				                dim.height *= transform.scale.y;
				        }
				}
				var newx = this.grid.center.x;
				var newy = this.grid.center.y;
				var radiusw = dim.width / 2;
				var radiush = dim.height / 2;
				this.grid ={x1: newx -radiusw ,x2: newx + radiusw, y1: newy - radiush, y2: newy + radiush,center:{x:newx,y:newy},width: dim.width,height:dim.height};	

				
				//console.log(this.grid.center.x,this.coordinates.normal,this.properties.transformation);
				return;
		}
		
		if(!coords) coords = this.getCoordinates();
		if(coords.length < 2) return;
		this.grid.x1 = coords[0];
		this.grid.y1 = coords[1];
		this.grid.x2 = coords[0];
		this.grid.y2 = coords[1];
		
		this._deltas = []
		var d = this._deltas;

		var lastX, lastY;
		var index = 0;
	
		lastX = coords[0];
		lastY = coords[1];
		for(var i=0; i < coords.length-1; i+=2){
			var xPos = parseFloat(coords[i]); //long
			var yPos = parseFloat(coords[i+1]); //lat
			var deltax =xPos - lastX;
			var deltay= yPos - lastY;
			if(deltax < 0) deltax = - deltax;
			if(deltay < 0) deltay = -deltay;
			d.push(deltax);
			d.push(deltay);
			if(xPos < this.grid.x1) this.grid.x1 = xPos;
			if(yPos < this.grid.y1) this.grid.y1 = yPos;	
			if(xPos > this.grid.x2) this.grid.x2 = xPos;
			if(yPos > this.grid.y2) this.grid.y2 = yPos;
			
			lastX = xPos;
			lastY = yPos;
		}
		
		//this.grid.x2 *= transform.scale.x;
		//this.grid.y2 *= transform.scale.y;
		this.grid.width = (this.grid.x2 - this.grid.x1);
		this.grid.height = (this.grid.y2 - this.grid.y1);
		/*var transform = this.getTransformation();
		if(transform && transform.scale){
		        var scale = transform.scale;
		        this.grid.width *= scale.x;
		        this.grid.height *= scale.y;
		        
		}*/
		this.grid.center = {};
		this.grid.center.x = (this.grid.x2 - this.grid.x1) / 2 + this.grid.x1;
		this.grid.center.y = (this.grid.y2 - this.grid.y1) / 2 + this.grid.y1;
		
		//recalculate based on scaling
		this.grid.width *= transform.scale.x;
		this.grid.height *= transform.scale.y;
		this.grid.center.x += transform.translate.x;
		this.grid.center.y += transform.translate.y;
		
		var halfw = this.grid.width / 2;
		var halfh = this.grid.height /2;
		this.grid.x1 = this.grid.center.x - halfw;
		this.grid.x2 = this.grid.center.x + halfw;
		this.grid.y1 = this.grid.center.y - halfh;
		this.grid.y2 = this.grid.center.y + halfh;
		
/*		if(transform && transform.translate){
		        var trans = transform.translate;
		        this.grid.center.x += trans.x;
		        this.grid.center.y += trans.y;
		}
*/
		this.grid.x1 = this.grid.center.x - (this.grid.width / 2);
		this.grid.x2 = this.grid.center.x + (this.grid.width /2);
		this.grid.y1 = this.grid.center.y - (this.grid.height/2);
		this.grid.y2 = this.grid.center.y +(this.grid.height/2);
		
		VismoTimer.end("VismoShapes._calculateBounds");
		//if(st == 'path') console.log(this,this.grid);
	}

    ,getCanvas: function(){
        return this.vismoCanvas;
    }
	,setRadius: function(rx,ry){
	    if(!ry) ry = rx;
		this.setDimensions(rx*2,ry*2);
	}
	,getRadius: function(){
		if(this.width) return this.width /2;
	    else{
	        var bb = this.getBoundingBox();
		    return bb.width / 2;
		}
		
	}
	,setDimensions: function(width,height){
		this.width = width;
		this.height = height;
		if(this.properties.shape == 'point'){
		    this.options.pointsize = width;
		}
		this._calculateBounds();
	    
	}
	,getDimensions: function(){
		return {width: this.width, height: this.height};
	}
	
	,_construct: function(properties, coordinates){
	    VismoTimer.start("VismoShapes._construct");
		var shapetype =properties.shape; 
		if(!shapetype) shapetype = 'polygon';
		if(shapetype == 'point' || shapetype == 'circle'){
			var radiusw,radiush;
			if(coordinates[2]) radiusw = coordinates[2];
			else radiusw = this.options.pointsize/2;
			
			if(coordinates[3]) radiush= coordinates[3];
			else radiush = radiusw;
			
			this.setDimensions(radiusw*2,radiush*2);
			this.setCoordinates([coordinates[0],coordinates[1],radiusw,radiush]);
			
		}
		else if(shapetype == 'polygon' || shapetype == 'path')
		{
			this.setCoordinates(coordinates);
		}
		else if(shapetype == 'domElement'){
					       
		        var w = jQuery(this.getProperty("element")).width(); 
		        var h = jQuery(this.getProperty("element")).height(); 
		        this.setDimensions(w,h);
		        this.setCoordinates(coordinates);

		}
		else if(shapetype == 'image'){
			var src = this.getProperty("src");
			if(!src) throw "all images must carry a property src at minimum";
			var image = new Image();
			image.src= src;
			this.image = image;
			var vismoShape = this;
			var w = vismoShape.getProperty("width"); h=  vismoShape.getProperty("height");
			if(coordinates.length > 2){
				w = coordinates[2]; h = coordinates[3];
			}
			image.onload = function(){
				if(!w && !h){
					vismoShape.setDimensions(w,h);
					vismoShape.setCoordinates([coordinates[0],coordinates[1]]);
				}
				vismoShape.ready = true;
			};
			if(image.complete)vismoShape.ready = true;
		
			vismoShape.setDimensions(w,h);
			vismoShape.setCoordinates([coordinates[0],coordinates[1]]);	
			
		}
		else{
			console.log("don't know how to construct basic shape " + properties.shape);
		}		
		VismoTimer.end("VismoShapes._construct");	
		
	}	

	,_applyProjection: function(projection,transformation){
	    VismoTimer.start("VismoShapes._applyProjection");
		var c = this.getCoordinates('normal');
	
		if(!projection || !projection.xy) return c;
	
		if(projection.init) projection.init();
		var newc = [];
		for(var i=0; i < c.length-1; i+=2){
			var moved = false;
			if(!VismoShapeUtils._isCoordinate(c[i])){
				i+= 1;
			}
			var x = parseFloat(c[i]);
			var y = parseFloat(c[i+1]);
			var newx,newy;
			var projectedCoordinate = projection.xy(c[i],c[i+1],transformation);
			if(projectedCoordinate.x && projectedCoordinate.y){
				newx= projectedCoordinate.x;
				newy= projectedCoordinate.y;
			
				if(projectedCoordinate.move){
					moved  =true;
				}
			
				cok = true;
				//check we haven't wrapped around world (For flat projections sss)
				if(!projection.nowrap){
					var diff;
					if(newx > x) diff = newx - x;
					if(x > newx) diff = x - newx;
					if(diff > 100) cok = false; //too extreme change
				}
			
				if(cok){
					if(VismoShapeUtils._isCoordinate(x) && VismoShapeUtils._isCoordinate(y)){
						if(moved){
							newc.push("M");
						}
						newc.push(newx);
						newc.push(newy);
					}

				}
			}	
		}	
		if(newc.length < 2) return;
		this.setCoordinates(newc,"projected");
		this._calculateBounds(newc);
		VismoTimer.end("VismoShapes._applyProjection");
		return newc;
	}


	
	,optimise: function(canvas,transformation,projection,justcompute){
	    VismoTimer.start("VismoShapes.optimise");
	    var ocache = this._optimise_cache;

	    
	    var cid = transformation["cache"]["id1"];
	    var cid2 =transformation["cache"]["id2"];
	    
	    if(this.scale.x > 1){
	        var newx,newy;
	        newx = this.scale.x  * transformation.scale.x;
	        newy = this.scale.y  * transformation.scale.y;
	        cid = newx + ","+newy;
	    }
	    if(!ocache[cid]) ocache[cid] = {};
	    
        if(typeof(ocache[cid][cid2]) != "undefined"){
	        return ocache[cid][cid2];
        }
	    
	    var shapetype = this.properties.shape;
	    if(shapetype == "path") {
	        ocache[cid][cid2] = true;
	        VismoTimer.end("VismoShapes.optimise");
	        return true;
		}
		if(transformation && transformation.scale) {
		    this.currentResolution = Math.min(transformation.scale.x, transformation.scale.y);
		}
		if(projection) {this._applyProjection(projection,transformation);}
		
		if(shapetype != 'point' && shapetype != 'path' && shapetype !="domElement"){ //check if worth drawing				
			if(VismoOptimisations.vismoShapeIsTooSmall(this,transformation)) {
				if(!justcompute && this.vml)this.vml.clear();
				ocache[cid][cid2] = false;
				VismoTimer.end("VismoShapes.optimise");
				return false;	
			}	
		}
		
		if(!VismoOptimisations.vismoShapeIsInVisibleArea(this,canvas,transformation)){
			if(!justcompute && this.vml)this.vml.clear();
			ocache[cid][cid2] = false;
			VismoTimer.end("VismoShapes.optimise");
			return false;	
		}
		ocache[cid][cid2] = true;
		VismoTimer.end("VismoShapes.optimise");
		return true;
	}
	,optimise_ie: function(canvas,transformation,projection){	
	    VismoTimer.start("VismoShape.optimise_ie");
	    var ocache = this._optimise_cache;
	    var cid = transformation["cache"]["id1"];
        if(typeof(ocache[cid]) != "undefined"){
	        return ocache[cid];
        }
        VismoOptimisations.minradius = 6;
	    var sh = this.properties.shape;
		if(sh == 'path' || sh == 'point') {
		        ocache[cid] =true;
               return true;
        }
        
		if(VismoOptimisations.vismoShapeIsTooSmall(this,transformation)) {
				if(this.vml)this.vml.clear();
                VismoTimer.end("VismoShape.optimise_ie");
				ocache[cid] =false;
				return false;		
		}
        ocache[cid] =true;
        VismoTimer.end("VismoShape.optimise_ie");
		return true;
	}
	
	,_simplifyCoordinates: function(scaleFactor,coordinates){// **
		VismoTimer.start("VismoShapes._simplifyCoordinates");
		if(this.getProperty("shape") == 'path') return coordinates;
		/*will use http://www.jarno.demon.nl/polygon.htm#ref2 */
		if(!coordinates) throw "give me some coordinates!";
		var originals =coordinates;
		var tolerance;
		var bb = this.getBoundingBox();
		
		var d;
		if(bb.width < bb.height) d = bb.width;
		else d = bb.height;
		tolerance = (d/4) / scaleFactor;
		
		coordinates = VismoOptimisations.packCoordinates(coordinates);
		coordinates = VismoOptimisations.douglasPeucker(coordinates,tolerance);
		
		coordinates = VismoOptimisations.unpackCoordinates(coordinates);	
		
		var diff = originals.length - coordinates.length;
		
		VismoTimer.end("VismoShapes._simplifyCoordinates");
		if(diff < 10) return originals;
		else 
		return coordinates;	
	}


};/*
A package for rendering geojson polygon and point features easily to create maps
*/
var GeoTag = function(longitude,latitude,properties){
	var geo = {};
	geo.type = "feature";
	geo.geometry = {};
	geo.geometry.type = "point";
	geo.geometry.coordinates = [longitude,latitude];
	geo.properties = properties;
	return geo;	
};

var VismoMap = function(wrapper,options){  
    
    if(wrapper.length){ //for jquery
        var result = [];
        for(var i=0; i < wrapper.length; i++){
            var x = new VismoMap(wrapper[i],options);
            result.push(x);
        }
        return x;
    }
    
	if(typeof wrapper == 'string') wrapper = document.getElementById(wrapper);
	else wrapper = wrapper;
		
	this.wrapper = wrapper;
	wrapper.vismoMap = this;
	//wrapper.style.position = "relative";
	var that = this;
	this.settings = {};
	var w= jQuery(wrapper).width();
	var h= jQuery(wrapper).height();
	jQuery(wrapper).css({width:w,height:h});
	
	this.feature_reference = {};
	if(!options) options = {};


	var that = this;
	var handler = function(t){
	    that.transform(t);
	}
	//if(!options.vismoController) options.vismoController = {};
	if(options.vismoController)options.vismoController.handler = handler;

	this.vismoCanvas = new VismoCanvas(wrapper,options);
	this.controller = this.vismoCanvas.vismoController;
	
	//run stuff
	if(this.controller)this.transform(this.controller.transformation); //set initial transformation
	this._fittocanvas = true;
	this.geofeatures = {};
	this.features = [];
	this.clear();
	
	var proj = options.projection;
	var eMap = this;
	this._hijackMouseFunctions();
	if(options.tooltip){
	    this.vismoCanvas.addTooltip(function(el,s){
	        if(s){
	        el.innerHTML = s.getProperty("name");
            }
	    });
	    
	}
		this.mouse({down:options.mousedown,up:options.mouseup,move:options.move,dblclick:options.dblclick,keypress:options.keypress});
	
	var eMap = this;
	if(proj){
		if(proj == 'globe' || proj == 'spinnyglobe'){
			eMap = new VismoGlobe(this);
			if(proj == 'spinnyglobe'){
				eMap.toggleSpin();
			}
		}
		if(proj == 'google'){
			eMap.settings.projection = VismoSlippyMap.prototype.getGoogleMercatorProjection();
		}
		else if(proj == 'slippystaticmap'){
			eMap = new VismoSlippyMap(this);					
		}
		
	}
	
	if(options.geojson){
	    this.drawFromGeojson(options.geojson,options.fullscreen);
	}
	else if(options.georss){
	    this.drawFromGeojson(VismoConversion.geoRssToGeoJson(options.georss),options.fullscreen);
	}
	else if(options.kml){
	    this.drawFromGeojson(VismoConversion.kmlToGeoJson(options.kml),options.fullscreen);
	}
	return eMap;
};  
VismoMap.prototype = {
	setTransparency: function(args){
	    var alpha = arguments[0];
		this.vismoCanvas.setTransparency(alpha);
	}
	,getVismoShapes: function(args){
		return this.vismoCanvas.getMemory();
	}
	,resize: function(args){
	    var width = arguments[0];
	    var height = arguments[1];
		this.wrapper.style.width = width+"px";
		this.wrapper.style.height = height +"px";
		var  t=this.getTransformation();
		t.origin.x = width / 2;
		t.origin.y = height / 2;
		this.setTransformation(t);
		this.vismoCanvas.resize(width,height);

		this.clear();

	}
	,getProjection: function(args){
		return this.settings.projection;
	}
	,setProjection: function(args){
	    var projection = arguments[0];
		this.settings.projection = projection;

	}
	,clear: function(args){ /* does this work in IE? */
		var deleteMemory = arguments[0];
		this.vismoCanvas.clear(deleteMemory);
	},
	
	drawFromGeojson: function(args){
        var geojson = arguments[0];
        var autosize = arguments[1];
			if(typeof geojson == 'string'){
				geojson = eval('(' +geojson+ ')');
			}
							
			this._lastgeojson = geojson;
			if(autosize){
			 	var t = VismoMapUtils.fitgeojsontocanvas(geojson,this.wrapper);

				var p =this.getProjection();
				if(p && p.name == "GLOBE") {
					t.translate = {x:0,y:0};
				}
					
				this.controller.setTransformation(t);
			}
		
			var type =geojson.type.toLowerCase();		
	 
			if(type == "featurecollection"){
				var features = geojson.features;
				this.drawGeoJsonFeatures(features);
			}  else if(type =='feature') {
				this.drawGeoJsonFeature(geojson);
			} else {
				console.log("only feature collections currently supported");
			}

			this.render();
			
	},
	drawFromGeojsonFile: function(args){
	    var file = arguments[0];
		var that = this;
		var callback = function(status,params,responseText,url,xhr){
		
			that.drawFromGeojson(responseText);
		};
		VismoFileUtils.loadRemoteFile(file,callback);
	}

	,getTransformation: function(args){
		if(!this.transformation){
			return false;
		}
		else
			return this.transformation;
	}
	,setTransformation: function(args){
	    var transformation = arguments[0];
		if(typeof transformation.translate.x != 'number'||typeof transformation.translate.y != 'number') throw "bad transformation translate given ";
		if(typeof transformation.scale.x != 'number'||typeof transformation.scale.y != 'number') throw "bad transformation scale given ";
		
		this.controller.setTransformation(transformation);
	}
	,moveTo: function(args){
	    var longitude= arguments[0];
	    var latitude = arguments[1];
	    var zoom = arguments[2];
		var newt = {translate:{},scale:{}};
		var transformation =this.getTransformation();
		
		var newxy={};
		newxy.x = parseFloat(longitude);
		newxy.y = parseFloat(latitude);
		
		if(this.settings.projection){
		 	newxy = this.settings.projection.xy(newxy.x,newxy.y,transformation);
		}
		newt.translate.x = - newxy.x;
		newt.translate.y = newxy.y;
		
		if(!zoom){
			zoom =transformation.scale.x;
		}
		else{
			zoom = parseFloat(zoom);
		}
		newt.scale.x = zoom;
		newt.scale.y = zoom;
		this.controller.setTransformation(newt)
		
	}

	,redraw: function(args){
		this.render();	

	    //alert("average VML render"+ VismoVector.rstats);
	    //alert("total average VML render time"+ VismoVector.rstats * VismoVector.rnum);
	},
		
	transform: function(args){
	    var transformation = arguments[0];
		//console.log(arguments);
		var w =parseInt(this.wrapper.style.width);
		var h = parseInt(this.wrapper.style.height);
		var t =transformation.translate;
		var s = transformation.scale;
	
		this.transformation = transformation;
		/*if(!transformation.origin){
			this.transformation.origin = {};
			var origin = this.transformation.origin;
			origin.x =w / 2;
			origin.y =h / 2;
		}*/
		
		if(s.x < 0.5) s.x = 0.5;
		if(s.y < 0.5) s.y = 0.5;
		
		if(t.x > 180) t.x = 180; //t.x=Math.min(t.x, 180)
		if(t.x < -180) t.x = -180;
		
		if(t.y > 85.0511) t.y = 85.0511;
		if(t.y < -85.0511) t.y = -85.0511;
		
		if(!this.transformation.rotate){
				this.transformation.rotate = {x:0,y:0,z:0};
		}
			
		
		var that = this;
		var f = function(args){
		    that.vismoCanvas.setTransformation(that.transformation);
		    that.redraw();
		}
		window.setTimeout(f,0);

	},


	/*onmouseup and ove are functions with following parameters:
		e,shape,mouse,longitude_latitude,feature
		
	*/
	mouse: function(args){
 	    if(!args){
	        return {up: this.onmouseup, down: this.onmousedown, move: this.onmousemove, dblclick: this.ondblclick,keypress:this.onkeypress};
	    }
			if(args.move)this.onmousemove =args.move;
			if(args.up)this.onmouseup = args.up;
			if(args.down)this.onmouseup = args.down;
			if(args.keypress) this.onkeypress = args.keypress;
			if(args.dblclick) this.ondblClick = args.dblclick;
	}

	,_hijackMouseFunctions: function(args){
	        var eMap = this;
	        var getParameters = function(e){
			var result = {};
			var code;
			if (e.which) code =e.which;
			else if (e.keyCode) code = e.keyCode;
			var character;
			if(code) character = String.fromCharCode(code);	
			var t = VismoClickingUtils.resolveTargetWithVismo(e);
			if(t && t.getAttribute("class") == 'vismoControl') return false;
			var shape = eMap.vismoCanvas.getShapeAtClick(e);
			if(shape) {
				result.shape = shape;
				result.feature = eMap.geofeatures[eMap.vismoCanvas.getMemoryID(shape)];
			}
		
			
			var pos = VismoClickingUtils.getMouseFromEvent(e);
			var x =pos.x;
			var y = pos.y;
			result.mouse = pos;
			result.longitude_latitude = VismoMapUtils.getLongLatFromMouse(x,y,eMap);
			result.event = e;
			result.keypressed = character;
			return result;
			
		};
		
		 var md = function(e,s){
	                var r = getParameters(e);
	                if(eMap.onmousedown) eMap.onmousedown(e,s,r.mouse,r.longitude_latitude,r.feature,r.key,eMap);
	        };
	        
	        var mu = function(e,s){
	                var r = getParameters(e);
	                if(eMap.onmouseup) eMap.onmouseup(e,s,r.mouse,r.longitude_latitude,r.feature,r.key,eMap);
	        };
	        var mm = function(e,s){
	            
	                var r = getParameters(e);
	                if(eMap.onmousemove) eMap.onmousemove(e,s,r.mouse,r.longitude_latitude,r.feature,r.key,eMap);	                
	        };
	        var dbl = function(e,s){
	                var r = getParameters(e);
        	        if(eMap.ondblClick) eMap.ondblClick(e,s,r.mouse,r.longitude_latitude,r.feature,r.key,eMap);
	        };
	        var key = function(e,s){
	                var r = getParameters(e);
                        if(eMap.onkeypress) eMap.onkeypress(e,s,r.mouse,r.longtitude_latitude,r.feature,r.key,eMap);
	        }
	        this.vismoCanvas.mouse({mousedown:md,mouseup:mu,mousemove:mm,dblclick:dbl,keypress:key});
	}

	,render: function(args){
	    var d1 = new Date();
	    var flag = arguments[0];
		var tran =this.transformation;

		var that = this;

		this.vismoCanvas.render(this.settings.projection);
		if(this.settings.afterRender) {
			this.settings.afterRender(tran);
			
		}
		var t = document.getElementById(that.wrapper.id + "_statustext");
		if(t) {
			t.parentNode.removeChild(t);	
		}
		var d2 = new Date();
		var id="mapRender";
		if(!VismoTimer[id]) VismoTimer[id] = 0;
		VismoTimer[id] += (d2 - d1);
		
		
		
	
	},
	
	getFeatures: function(args){
	       if(arguments[0] && this.features[arguments[0]]) return this.features[arguments[0]];
	       return this.features;
	}
	,drawGeoJsonFeature: function(args){
	    var featuredata = arguments[0];
	    var props = arguments[1];
		var feature = new VismoMap.Feature(featuredata,props);		
		var s = feature.getVismoShapes();		
		for(var i=0; i < s.length; i++){
			this.vismoCanvas.add(s[i]);
			//this.geofeatures[this.vismoCanvas.getMemoryID(s[i])] = feature;
		}	
         this.features.push(feature);
	},
	drawGeoJsonFeatures: function(args){
	    var features = arguments[0];
			var avg1 = 0;
				
			for(var i=0; i < features.length; i++){
			
				this.drawGeoJsonFeature(features[i],{featureid:i});
			}

	}
	,getVismoCanvas: function(args){
	        return this.vismoCanvas;
	}
};


VismoMap.Feature = function(feature,props){
	this.init(feature,props);
};

VismoMap.Feature.prototype = {
	init: function(args){
	    var feature = arguments[0];
	    if(arguments[1])extra_properties = arguments[1];
	    else extra_properties = {};
		this.properties = feature.properties;
		this.geometry = feature.geometry;
		this.outers = [];
		this.vismoShapes = [];
		var geometry = this.geometry;
		var type =geometry.type.toLowerCase();

		if(type == 'multipolygon'){
			this._drawGeoJsonMultiPolygonFeature(feature.geometry.coordinates,feature);
		}
		else if(type == 'linestring' || type=='multilinestring' || type == 'multipoint' || type=='geometrycollection'){
			console.log(type + " not supported yet");
		}

		else if(type == 'polygon'){
			this._drawGeoJsonPolygonFeature(feature.geometry.coordinates,feature);
		}
		else if(type == 'point'){
			this._drawGeoJsonPointFeature(feature.geometry.coordinates,feature);				
		}
		else {	
			console.log("unsupported geojson geometry type " + geometry.type);
		}		
        var x = this.getVismoShapes();
        var f;
  
        for(f in extra_properties){
    
             for(var i=0; i < x.length; i++){
                x[i].setProperty(f,extra_properties[f]);
            }
        }
	}
	,addOuterVismoShape: function(args){
		var shape = arguments[0];
		this.outers.push(shape);
	}
	,getOuterVismoShapes: function(args){
		return this.outers;
	}
	,addVismoShape: function(args){
	    var vismoShape = arguments[0];
		this.vismoShapes.push(vismoShape);
	}
	,getVismoShapes: function(args){
		return this.vismoShapes;
	}
	,_drawGeoJsonMultiPolygonFeature: function(args){
	    var coordinates=  arguments[0];
	    var feature = arguments[1];
		var outer;
		
		for(var i=0; i < coordinates.length; i++){ //it's a list of polygons!
			var s = this._drawGeoJsonPolygonFeature(coordinates[i],feature,i);
			
		}
		
	},	
	_drawGeoJsonPolygonFeature: function(args){
        var coordinates=  arguments[0];
	    var feature = arguments[1];
	    var featureid = arguments[2];
		var p = feature.properties;
		p.shape = 'polygon';
		//console.log(coordinates[0]);
		
		var outer = false;
		for(var j=0; j< coordinates.length; j++){//identify and create each polygon
			var coords =coordinates[j];	
			coords = VismoUtils.invertYCoordinates(coords);
			var s = new VismoShape(p,coords);
			s.properties.geometryid = featureid;
			s.properties.geometryid2 = j;
			this.addVismoShape(s);
		}
		return outer;		
		
	},
	_drawGeoJsonPointFeature: function(args){
	    var coordinates=  arguments[0];
	    var feature = arguments[1];

		var p = feature.properties;
		p.shape = 'point';
		coordinates[1] = -coordinates[1];
		var s = new VismoShape(p,coordinates);
		this.addVismoShape(s);
	}
	,setProperty: function(args){
	    var id = arguments[0];
	    var val = arguments[1];
	    var shapes = this.getVismoShapes();
	    for(var i=0; i < shapes.length;i++){
	        shapes[i].setProperty(id,val);
	    }
	}
};
/*Extends VismoMaps to provide tiled background */
var VismoGlobe=  function(eMap){
	var i;
	for(i in VismoGlobe.prototype){
		eMap[i] = VismoGlobe.prototype[i];
	}	
	
	eMap.setGlobeProjection("GLOBE");
	return eMap;
	
};

VismoGlobe.prototype = {
	setGlobeProjection: function(){
		var vismomap = this;
		vismomap._fittocanvas = false;
		this.settings.beforeRender = function(t){
				vismomap._createGlobe(vismomap.getProjection().getRadius(t.scale));
		};
		
		this.settings.projection= {
				name: "GLOBE",
				nowrap:true,
				radius: 10,
				direction: 0
				,init: function(){
					this.direction = 0;
				}
				,getRadius: function(){
					return this.radius;
				}
				,inversexy: function(x,y,t){
						var radius =this.getRadius(t.scale);
						var res = VismoMapUtils._undospherify(x,y,t,radius);
						return res;
				}
				,xy: function(x,y,t){
					
					var radius =this.getRadius(t.scale);
					if(!radius || !x || !y || !t) return {x:x,y:y};
					var res = VismoMapUtils._spherifycoordinate(x,y,t,radius);
					/*
					if(res.movedNorth && this.direction >= 0){
						this.direction = -1;
						res.move= true;
					}
					else if(res.movedSouth && this.direction <= 0){
						this.direction = 1;
						res.move = true;
					}
					
					if(res.y > radius - 10 || res.y < 10-radius){
						
						res.y = false;
					}*/
					return res;
				}
		};
		
		var heightR = parseInt(vismomap.wrapper.style.height)  /2;
		var widthR= parseInt(vismomap.wrapper.style.width) /2;
		if(widthR > heightR){
			this.settings.projection.radius = heightR;
		}
		else{
			this.settings.projection.radius = widthR;
		}
		
	
		
	}
	,toggleSpin: function(){
		var eMap = this;
		var f = function(){
			var t = eMap.controller.transformation;
			if(!t.rotate) t.rotate = {};
			if(!t.rotate.z) t.rotate.z  = 0;
		
			t.rotate.z += 0.3;
			eMap.controller.setTransformation(t);
			window.setTimeout(f,600);
		};
		f();
	}
	,_createGlobe: function(radius){
		if(VismoUtils.browser.isIE) {return;}
		var ctx = this.vismoClicking.canvas.getContext('2d');
		if(!ctx) return;
		var t =this.controller.transformation;
		var tr =t.translate;
		var s = t.scale;
		var o = t.origin;
		ctx.save();	
		ctx.translate(o.x,o.y);
		ctx.scale(s.x,s.y);
		ctx.translate(tr.x,tr.y);
	
	
		var radgrad = ctx.createRadialGradient(0,0,10,0,0,radius);

		radgrad.addColorStop(0,"#AFDCEC");
		radgrad.addColorStop(0.5, '#00C9FF');
		radgrad.addColorStop(1, '#00B5E2');
		radgrad.addColorStop(1, 'rgba(0,201,255,0)');

		ctx.beginPath();
		ctx.arc(0, 0, radius, 0, Math.PI*2, true);
		ctx.closePath();
		ctx.fillStyle = radgrad;
		ctx.fill();
		ctx.restore();

	}
};



var VismoSlippyMap = function(vismoMap){	
	//vismoMap.resize(512,512);
	this.loadedurls = {};
	this.setupSlippyStaticMapLayer(vismoMap);

        vismoMap.oldDrawFromGeojson = vismoMap.drawFromGeojson
         vismoMap.drawFromGeojson = function(geojson,autosize){
                vismoMap.oldDrawFromGeojson(geojson,false);
        };
        
	return vismoMap;
};

VismoSlippyMap.prototype = {
	getGoogleMercatorProjection: function(vismomap){
		
		var p = {};
		p.source = new Proj4js.Proj('WGS84');//
		p.dest = new Proj4js.Proj('GOOGLE');
		p.resultCache = {};
		var that = this;
		p.getTileServerUrl = function(){
		        return that.tileserverurl;
		}
		p.tilesize = 256;
		p.googleHack = 1/((2 * Math.PI * 6378137) /p.tilesize);
		p.inversexy = function(x,y){
			x /= this.googleHack;
			y /= this.googleHack;
			var pointSource = new Proj4js.Point(x ,y);
			var pointDest = Proj4js.transform(p.dest,p.source, pointSource);

			return pointDest;
		}

		p.calculatescalefactor= function(vismomapscale,res){
			
			if(!res){ 
				if(vismomapscale <= 1){
					return 0;
				}
				else{
					res = 0;
				}
			}
			
			if(vismomapscale <= 1){
				return res;
			}
			else{
				var news = vismomapscale / 2;
				res +=1 ;
				return this.calculatescalefactor(news,res);
			}
		};
		p.xy = function(x,y,t){
			
				if(this.resultCache[x+"|"+y]) {
					return this.resultCache[x+"|"+y];
				}
				var pointSource = new Proj4js.Point(x,y);
				var pointDest = Proj4js.transform(p.source,p.dest, pointSource);


				var newx =pointDest.x;
				var newy = pointDest.y;
				newx *= this.googleHack;
				newy *= this.googleHack;
				
				this.resultCache[x+"|"+y] = {x:newx , y:newy};
				return this.resultCache[x+"|"+y];
				
		}
		return p;
	}
	,setupSlippyStaticMapLayer: function(eMap){
		/*Filename(url) format is /zoom/x/y.png */
		
		var projection = this.getGoogleMercatorProjection(eMap);
		//var projection = {};
		eMap.setTransparency(0.7);
		eMap.settings.projection = projection;
		var that = this;
		
		var mapheight =parseInt(eMap.wrapper.style.height);
		var mapwidth =parseInt(eMap.wrapper.style.width);
		var tileGridDimension = {x:mapwidth/projection.tilesize + 1,y:(mapheight/projection.tilesize) + 1};
		var tiles = this._createTiles(eMap,tileGridDimension.x,tileGridDimension.y);
		var eMap = eMap;
		
		eMap.settings.afterRender = function(transformation){
		        var origin = transformation.origin;
			jQuery(that.tilesWrapper).css({top: origin.y, left: origin.x});
			var zoomOut = false;
			if(eMap.settings.lastScale > transformation.scale.x)
				zoomOut = true;
			eMap.settings.lastScale = transformation.scale.x;
			var x =0,y =0,lo,la, translate= transformation.translate,scale= transformation.scale;
		
			eMap.wrapper.style.backgroundImage = "none";
			var zoomL = projection.calculatescalefactor(scale.x);	
	
				
			var mapheight =parseInt(eMap.wrapper.style.height);
			var mapwidth =parseInt(eMap.wrapper.style.width);
			
			var tile = tiles["main"];
			var left = (scale.x * translate.x);
			var top = (scale.y * translate.y);
			top += (origin.y - 128);
			left += (origin.x - 128);
			tile.style.top = top + "px";
			tile.style.left = left + "px";
			if(zoomL == 0){
				var i;
				for(i in tiles){
					tiles[i].style.backgroundImage ="none";
				}
				zoomL = 0;
				tilex = 0;tiley=0;
				var slippyurl =projection.getTileServerUrl()+zoomL +"/"+tilex+"/"+tiley+".png";
				that.renderTile(slippyurl,zoomL,tilex,tiley,tile);					
			}
			else{
				
				tiles.main.style.backgroundImage = "none";
				var temp ={x: (translate.x),y:(translate.y)};
				temp.x *= scale.x;
				temp.y *= scale.y;				
				temp.x += (origin.x);
				temp.y += (origin.y);
				var tlleft = temp.x;
				var tltop =temp.y;
				//brtop = brtop%(256);
				tlleft= temp.x % 256;
				tltop =  temp.y % 256;
                                if(tltop > 0) tltop -= 256;
                                if(tltop < -256) tltop += 256;
                                if(tlleft < -256) tlleft += 256;
		                if(tlleft > 0) tlleft -= 256;
				var lola;
				
				lola = VismoMapUtils.getLongLatAtXY(tlleft+128,tltop+128,eMap);
			
				var tltilexy =VismoMapUtils.getSlippyTileNumber(lola.longitude,lola.latitude,zoomL,eMap);
				
				for(var idX=0; idX < tileGridDimension.x; idX++){
					for(var idY=0; idY < tileGridDimension.y; idY++){
						var leftShift = idX;
						var upShift = idY;
						var index = idX + "|"+idY;
						var tile = tiles[index];
						var top = tltop + (256 * idY);
						var left = tlleft + (256 *idX);
						var tilex = tltilexy.x + idX;
						var tiley = tltilexy.y + idY;

						
						var numtiles = Math.pow(2,zoomL);
						if(tilex <  0) tilex = numtiles + tilex;
						if(tiley < 0) tiley = numtiles + tiley;
						if(tilex >= numtiles) tilex -= numtiles;
						if(tiley >= numtiles) tiley -= numtiles;
					
						tile.style.left = left +"px";
						tile.style.top = top + "px";
						tile.title = zoomL+"/"+tilex + "/" + tiley;
						var slippyurl ="http://tile.openstreetmap.org/"+zoomL +"/"+tilex+"/"+tiley+".png";
						that.renderTile(slippyurl,zoomL,tilex,tiley,tile);
						
					}

				}
			
		
			}

		};
		
		
	}
	,renderTile: function(weburl,zoomlevel,x,y,tile){
		var that = this;
		var renderTile = function(dest){
			tile.style.backgroundImage = "none";
			var style ="url('"+dest+"')";
			if(style == tile.style.backgroundImage) return;
			tile.style.backgroundImage = style;
			//var numtiles = Math.pw(2,zoomL);

		};
		var renderTileWeb = function(url){
			var style ="url('"+url+"')";
			tile.style.backgroundImage = "none";
			if(style == tile.style.backgroundImage) return;
			tile.style.backgroundImage = style;

		};
		try{	
			var localurl = zoomlevel+ "_"+ x + "_" + y + ".png";
			if(localurl != tile.style.backgroundImage){
				if(that.loadedurls[localurl]){
					renderTile(localurl);
				}
				else{
					tile.style.backgroundImage = "none";
					VismoFileUtils.saveImageLocally(weburl,localurl,renderTile,renderTileWeb);
					that.loadedurls[localurl] = true;
				}
			}
		}
		catch(e){
			tile.style.backgroundImage = "none";
			//console.log("unable to cache static image for this map view. ("+e+")")
		}
	}
	,_createTiles: function(eMap,numtilesx,numtilesy){
		var res = {};
		var tiles = document.createElement("div");
		tiles.style.overflow = "hidden";
		tiles.className = "VismoTileWrapper"
		tiles.style.position= "absolute";
		tiles.style.width = eMap.wrapper.style.width;
		tiles.style.height = eMap.wrapper.style.height;
		var maintile = document.createElement("div");
		maintile.style.position = "absolute";
		maintile.style.width = "256px";
		maintile.style.height = "256px";
		tiles.appendChild(maintile);
		
		for(var y = 0; y < numtilesy; y++){
			for(var x = 0; x < numtilesx; x++){
				var tile = document.createElement("div");
				tile.className = "tile_"+x+ "_"+y;
				tile.style.position = "absolute";
				tile.style.width = "256px";
				tile.style.height = "256px";
				//if(x == 0 && y == 0) tile.style.border = "solid 1px black";
				var index =x+"|"+y;
				tiles.appendChild(tile);
				res[index] = tile;
			}
		}
		
		eMap.wrapper.appendChild(tiles);
		
		res['main'] = maintile;
		return res;
		

		
	}
	
};/*requires VismoShapes
Adds controls such as panning and zooming to a given dom element.

Mousewheel zooming currently not working as should - should center on location where mousewheel occurs
Will be changed to take a handler parameter rather then a targetjs
 */


var VismoController = function(elem,options){ //elem must have style.width and style.height etM  
   
    if(elem.length){ //for jquery
        var result = [];
        for(var i=0; i < elem.length; i++){
            var x = new VismoController(elem[i],options);
            result.push(x);
        }
        return x;
    }
     
    if(!options)options = {};
        if(elem.vismoController) throw "this already has a vismo controller!"
        elem.vismoController = true;// this;              
	this.enabledControls = [];

	if(typeof elem == 'string') elem= document.getElementById(elem);
	this.setLimits({});
	
	//jQuery(elem).css()
	//if(!elem.style || !elem.style.position) elem.style.position = "relative";
	this.wrapper = elem; //a dom element to detect mouse actions
	this.handler = options.handler; //a js object to run actions on (with pan and zoom functions)	
	this.defaultCursor = "";
	var md = elem.onmousedown;
	var mu = elem.onmouseup;
	var mm = elem.onmousemove;
	for(var i=0; i < elem.childNodes.length; i++){
		var child = elem.childNodes[i];
	    try{
		child.onmousedown = function(e){if(md)md(e);}
		child.onmouseup = function(e){if(mu)mu(e);}
		child.onmousemove = function(e){if(mm)mm(e);}
		}
		catch(e){
		    
		}
	}
        
	controlDiv = document.createElement('div');
	controlDiv.style.position = "absolute";
	controlDiv.style.top = "0";
	controlDiv.style.left = "0";
	controlDiv.className = 'vismoControls';
	jQuery(controlDiv).css({'z-index':10000, height:"120px",width:"60px"});
	this.wrapper.appendChild(controlDiv);
	this.controlDiv = controlDiv;
        this.controlCanvas = new VismoCanvas(this.controlDiv);
	//this.controlDiv.vismoController = this;
	var vismoController = this;
	var preventDef = function(e){
                if (e && e.stopPropagation) //if stopPropagation method supported
                 e.stopPropagation()
                else
                 e.cancelBubble=true
          return false;      
	};
	var that = this;
	var f = function(e,s){
	        var vismoController = that;
	        vismoController._panzoomClickHandler(e,s,vismoController);
	        return preventDef(e);
	};
	this.controlCanvas.mouse({up:preventDef,down:f,dblclick:preventDef});

	//this.wrapper.vismoController = this;
	
	

	this.transformation = {'translate':{x:0,y:0}, 'scale': {x:1, y:1},'rotate': {x:0,y:0,z:0},origin:{}};	
	             
	             
	
	this.transformation.origin.x = jQuery(elem).width() / 2;
	this.transformation.origin.y = jQuery(elem).height() / 2;
        var t = this.transformation;

	//looks for specifically named function in targetjs
	if(!this.handler) {
	    alert("no transform handler function defined");
	}
	//this.wrapper.vismoController = this;
	this.enabled = true;


	if(!options) options = {};
	if(!options.controls)options.controls =['pan','zoom','mousepanning','mousewheelzooming'];
	this.options = options;
	if(!this.options.controlStroke){
        this.options.controlStroke = "#000000";
    }
    if(!this.options.controlFill){
        this.options.controlFill = "rgba(150,150,150,0.7)";
    }
    
    
	this.addControls(this.options.controls);
	this.limits = {scale:{}};
	if(this.options.maxZoom) {
	    this.limits.scale.x =this.options.maxZoom;
	    this.limits.scale.y = this.options.maxZoom;
    }
    if(this.options.minZoom){
        
        this.limits.scale.minx =this.options.minZoom;
         this.limits.scale.miny =this.options.minZoom;
    }

    this.pansensitivity =100;
    if(this.options.pansensitivity){
        this.pansensitivity =this.options.pansensitivity;
    }


};
VismoController.prototype = {
	setLimits: function(transformation){
	        this.limits = transformation;
	}
	,getHandler: function(){
	    return this.handler;
	}
	,setHandler: function(handler){
	    this.handler = handler;
	    handler(this.transformation);
	}
	,getEnabledControls: function(){
	        return this.enabledControls;
	}
	,_addEnabledControl: function(controlName){
	        this.enabledControls.push(controlName);      
	}
	,applyLayer: function(){
	        var that = this;
	        var hidebuttons = function(){
	               var shapes = that.controlCanvas.getMemory();
	                for(var i=0; i < shapes.length; i++){
	                        shapes[i].setProperty("hidden",true);
	                }

	                that.controlCanvas.render();
	        };	        
	        this.controlCanvas.render();
	        if(this.options.hidebuttons){
	                hidebuttons();
	                return;
	        }
	        
	       	       
	        if(VismoUtils.browser.isIE6) return;
	        var enabled = this.getEnabledControls();
	        var pan,zoom;
	        if(enabled.contains("pan")) pan = true;
	        if(enabled.contains("zoom")) zoom = true;
                var callback = function(response){
                        if(!response)return;
                        if(!VismoUtils.svgSupport())return;
                        
                        var shape;
                        if(false == true){
                                //return;
                                shape = document.createElement("div");
                                shape.innerHTML = response;
                        }
                        else{
                                shape = document.createElement('object');
                                
                                shape.setAttribute('codebase', 'http://www.adobe.com/svg/viewer/install/');
                                if(VismoUtils.browser.isIE)shape.setAttribute('classid', '15');
                                shape.setAttribute('style',"overflow:hidden;position:absolute;z-index:0;width:60px;height:120px;");
                                shape.setAttribute('type',"image/svg+xml");
                                var dataString = 'data:image/svg+xml,'+ response;
                                shape.setAttribute('data', dataString); // the "<svg>...</svg>" returned from Ajax call                                      
                                jQuery(shape).css({width:60,height:120})
                        }
                        that.controlDiv.appendChild(shape);
                        jQuery(that.controlDiv).css({"background-image":"none"});
                        hidebuttons();
                };
	        if(pan && zoom) callback(this.panzoomcontrolsSVG);

        	
	}
	,getTransformation: function(){ 
		return this.transformation;
	}
	,translate: function(x,y){
	        var t= this.getTransformation();
	        t.translate.x = x;
	        t.translate.y = y;
	        this.transform();
	},
	addMouseWheelZooming: function(){ /*not supported for internet explorer*/
                var that = this;
	        this._addEnabledControl("mousewheelzooming");
	
		this.crosshair = {lastdelta:false};
		this.crosshair.pos = {x:0,y:0};

		var t = this.getTransformation();

		var mw = this.wrapper.onmousewheel;
		

		var that = this;
		var mm = this.wrapper.onmousemove;
		

        var doingmw = false;
        var mwactive = false;
        
        var cancelMouseZoomCursor = function(){
            if(VismoUtils.browser.isIE6)that.wrapper.style.cursor = "";
            else jQuery(that.wrapper).removeClass("zooming");
        }
        jQuery(this.wrapper).mousedown(function(e){
            mwactive = true;
            if(VismoUtils.browser.isIE6)this.style.cursor = "crosshair";
            else {
                if(!jQuery(that.wrapper).hasClass("panning")){
                jQuery(that.wrapper).addClass("zooming");
                }
            }
            window.setTimeout(cancelMouseZoomCursor,2000);
        });
        jQuery(this.wrapper).mouseout(function(e){
            var newTarget;
            
            if(e.toElement) newTarget = e.toElement;
            else newTarget = e.relatedTarget;
            
            if(jQuery(newTarget,that.wrapper).length == 0){ //if not a child turn off
                mwactive = false;

            }
            cancelMouseZoomCursor();
        });
        var domw = function(e){
            if(!that.enabled) return;
			/* thanks to http://adomas.org/javascript-mouse-wheel */
			var delta = 0;

                        
			if(!that.goodToTransform(e)) {
			    doingmw = false;
			    return false;
			}
			var t = VismoClickingUtils.resolveTargetWithVismo(e);
		        t= el;

                       if(t != that.wrapper && t.parentNode !=that.wrapper) return false;
	       	 	if (e.wheelDelta) { /* IE/Opera. */
		                delta = e.wheelDelta/120;
		                /** In Opera 9, delta differs in sign as compared to IE.
		                 */
		                if (window.opera)
		                        delta = -delta;
		        } else if (e.detail) { /** Mozilla case. */
		                /** In Mozilla, sign of delta is different than in IE.
		                 * Also, delta is multiple of 3.
		                 */
		                delta = -e.detail/3;
		        }
	
			var sensitivity = 0.4;
			var transform = that.getTransformation();
			var scale =transform.scale;
			var origin = transform.origin;


			var mousepos = VismoClickingUtils.getMouseFromEvent(e);
	
			var w = parseInt(that.wrapper.style.width) / 2;
			var h = parseInt(that.wrapper.style.height) / 2;
			var translation =  VismoTransformations.undoTransformation(mousepos.x,mousepos.y,that.transformation);
			transform.translate= {x: -translation.x, y: -translation.y};
			//{x: -mousepos.x + w,y: -mousepos.y + h};
			transform.origin = {
											x: mousepos.x,
											y: mousepos.y
										};
			



			if(delta > that.crosshair.lastdelta + sensitivity || delta < that.crosshair.lastdelta - sensitivity){	
				var newx,newy;
				if(delta > 0){
					newx = parseFloat(scale.x) * 2;
					newy = parseFloat(scale.y) * 2;					
				}
				else{
					newx = parseFloat(scale.x) / 2;
					newy = parseFloat(scale.y) / 2;
				}

				if(newx > 0 && newy > 0){
					scale.x = newx;
					scale.y = newy;
					that.setTransformation(transform);					
				}

			}
			that.crosshair.lastdelta = delta;	
			

            doingmw = false;
            return false;
        };
		var onmousewheel = function(e){	
		    if(!VismoUtils.browser.isIE){
		        jQuery(that.wrapper).addClass("zooming");	
		    }
		    if(e.preventDefault){e.preventDefault();}
		    if (e && e.stopPropagation) {
                e.stopPropagation();
            }
             e.cancelBubble=true;
            
		    if(!mwactive) return false;
			if(!doingmw) {
			    var f = function(){
			        domw(e);
                    return false;
			    };
			    window.setTimeout(f,50);
			    doingmw = true;
            }


			return false;

		};

		
		var element = this.wrapper;
            if(VismoUtils.browser.isIE) {
		        document.onmousewheel = function(e){
		                if(!e)e = window.event;
		            
		                var el = e.target;
		                
		                //var el =  e.srcElement;
		                if(!el) return;
		                while(el != element){
		                        
		                        if(el == element) {
		                                onmousewheel(e); 
		                                
		                                return false;    
		                        }
		                        el = el.parentNode;
		                }
		                return;
		        };
		        window.onmousewheel = document.onmousewheel;
		        return;
		}
		else if (element.addEventListener){

			element.onmousewheel = onmousewheel; //safari
		    element.addEventListener('DOMMouseScroll', onmousewheel, false);/** DOMMouseScroll is for mozilla. */
		
		}
		else if(element.attachEvent){ 	
			element.attachEvent("onmousewheel", onmousewheel); //safari
		}
		else{ //it's ie.. or something non-standardised. do nowt
		//window.onmousewheel = document.onmousewheel = onmousewheel;	
		}

		
	}
	,disable: function(){
        jQuery(".vismoControls",this.wrapper).css({display:"none"});	    
		this.enabled = false;
	}
	,enable: function(){
		this.enabled = true;
		jQuery(".vismoControls",this.wrapper).css({display:""});
	}
	
	,goodToTransform: function(e){
		var t =  VismoClickingUtils.resolveTarget(e);

		switch(t.tagName){
			case "INPUT":
				return false;
			case "SELECT":
				return false;
			case "OPTION":
				return false;
		}
		
		if(t && t.getAttribute("class") == "vismoControl") return false;
		
		return true;
		
	}
	,addMousePanning: function(){
	       
	    this._addEnabledControl("mousepanning");
		var that = this;
		
		var el = that.wrapper;
		var md = el.onmousedown;
		var mu = el.onmouseup;	
		var mm = el.onmousemove;
		var panning_status = false;	
		//alert('here');
		//jQuery(document).mouseup(function(e){alert("cool");}); //doesn't work?!
		var cancelPanning = function(e){
			panning_status = false;
			that.transform();
			if(!VismoUtils.browser.isIE6){jQuery(that.wrapper).removeClass("panning");}
			//style.cursor= that.defaultCursor;
			that.wrapper.onmousemove = mm;
			return false;
		};
		jQuery(that.controlDiv).mousedown(function(e){

		    cancelPanning();
		});
		var onmousemove = function(e){
		    if(e && e.shiftKey) {return false;}
			if(mm){mm(e);}
			if(!that.enabled) {return;}
			if(!panning_status) {
				return;
			}
			if(!VismoUtils.browser.isIE && !jQuery(that.wrapper).hasClass("panning")){
			    jQuery(that.wrapper).addClass("panning")
			}
			if(!that.goodToTransform(e)) {return;}
			var pos =  VismoClickingUtils.getMouseFromEventRelativeToElement(e,panning_status.clickpos.x,panning_status.clickpos.y,panning_status.elem);		
			if(!pos){return;}
			
			var t = that.getTransformation();
			//if(this.transformation) t = this.transformation;
			var sc = t.scale;

			/* work out deltas */
			var xd =parseFloat(pos.x /sc.x);
			var yd = parseFloat(pos.y / sc.y);
			t.translate.x = panning_status.translate.x + xd;
			t.translate.y =panning_status.translate.y +yd;
            if(!VismoUtils.browser.isIE6){
                jQuery(that.wrapper).removeClass("zooming");
                that.transform();
            }
			that.transform();
			
			if(pos.x > 5  || pos.y > 5) panning_status.isClick = false;
			if(pos.x < 5|| pos.y < 5) panning_status.isClick = false;
			return false;	
		};
     
		jQuery(this.wrapper).mousedown(function(e){
		    var jqw = jQuery(that.wrapper);
			if(panning_status){
				return;
			}
			
			if(md) {md(e);}
			if(!that.enabled) return;
			if(!VismoUtils.browser.isIE6){
			    jqw.addClass("panning");
			}
			var target =  VismoClickingUtils.resolveTarget(e);
			target = el;
			if(!target) return;

			
			var t = that.transformation.translate;
			var sc =that.transformation.scale; 
			
			var realpos = VismoClickingUtils.getMouseFromEvent(e);
			if(!realpos) return;
			//this.vismoController = that;

			var element = VismoClickingUtils.resolveTargetWithVismo(e);
			element = el;
			panning_status =  {clickpos: realpos, translate:{x: t.x,y:t.y},elem: element,isClick:true};
			that.wrapper.onmousemove = onmousemove;
				
		});
			
		jQuery(document).mouseup(function(e){
			if(panning_status.isClick && mu){
			    mu(e);
			};
			
			if(panning_status){
			    cancelPanning(e);
            }
		});
		
		jQuery(document).mousemove(function(e){
			if(panning_status){
			        onmousemove(e);
			        var parent= e.target;
			        while(parent.parentNode){
			                parent = parent.parentNode;
			                if(parent == that.wrapper) return;
			        }
				
				//if(parent != that.wrapper)cancelPanning(e); (not a good idea for tooltips)
			}
		});
	
	},

	setTransformation: function(t){
        
        if(this.limits){
            if(this.limits.scale){
            if(t.scale.x > this.limits.scale.x){ t.scale.x = this.limits.scale.x;}
            if(t.scale.y > this.limits.scale.y){ t.scale.y = this.limits.scale.y; }
            
            if(t.scale.x < this.limits.scale.minx){ t.scale.x = this.limits.scale.minx;}
            if(t.scale.y < this.limits.scale.miny){ t.scale.y = this.limits.scale.miny;}     
            }    
        }
        if(!t.origin){
            
                var w = jQuery(this.wrapper).width();
                var h = jQuery(this.wrapper).height();
                t.origin = {x: w/2, y: h/2};

        }
		if(this.enabled){
			if(!t.scale && !t.translate && !t.rotate) alert("bad transformation applied - any call to setTransformation must contain translate,scale and rotate");
			this.transformation = t;
			
			try{this.handler(t);}catch(e){};
		}
		//console.log("transformation set to ",t);
	},
	createButtonLabel: function(r,type,offset){
		var properties=  {'shape':'path', stroke: this.options.controlStroke,lineWidth: '1','z-index':'2'};
		properties.actiontype = type;
		var coords=[];
		if(type == 'E'){
			coords =[r,0,-r,0,'M',r,0,0,-r,"M",r,0,0,r];
		}
		else if(type =='W'){
			coords =[-r,0,r,0,'M',-r,0,0,r,"M",-r,0,0,-r]; 
		}
		else if(type == 'S'){
			coords =[0,-r,0,r,'M',0,r,-r,0,"M",0,r,r,0];	
		}
		else if(type == 'N'){
			coords =[0,-r,0,r,'M',0,-r,r,0,"M",0,-r,-r,0];	
		}
		else if(type == 'in'){
			coords =[-r,0,r,0,"M",0,-r,0,r];
		}
		else if(type == 'out'){
			coords = [-r,0,r,0];
		}
		for(var i=0; i < coords.length; i+=2 ){
		        if(coords[i] == "M") i+=1;
		        coords[i] += offset.x;
		        coords[i+1] += offset.y;
		}
		return new VismoShape(properties,coords);
	},	
	createButton: function(width,direction,offset,properties) {
	        var canvas = this.controlCanvas;
	        if(!canvas) throw "no canvas to create on..";
		if(!width) width = 120;
		var r = width/2;

		offset = {
			x: offset.x || 0,
			y: offset.y || 0
		};
		
		var coords;
		if(this.options.controlShape && this.options.controlShape == 'circle'){
		    	coords = [
        			offset.x , offset.y,
        			width/2
        		];
        		properties.shape = 'circle';  
		}
		else{
		    
    		coords = [
    			offset.x, offset.y,
    			offset.x + width, offset.y,
    			offset.x + width, offset.y + width,
    			offset.x, offset.y + width
    		];
    		properties.shape = 'polygon';
	    }
		properties.fill =this.options.controlFill;
		properties.stroke =this.options.controlStroke;
		var button = new VismoShape(properties,coords);
		var bb = button.getBoundingBox();
		buttoncenter = {x:bb.center.x,y:bb.center.y}; 
		var label = this.createButtonLabel(r-2,properties.actiontype,buttoncenter);
	    canvas.add(label);
		canvas.add(button);
		return button;
	},
	addControls: function(list){
		for(var i= 0; i < list.length; i++){
			this.addControl(list[i]);
		}
	}
	,addControl: function(controlType) {
		switch(controlType) {
			//case "zoom":
			case "pan":
				this.addPanningActions();
				break;
			case "zoom":
				this.addZoomingActions();
				break;
			case "mousepanning":
				this.addMousePanning();
				break;
			case "mousewheelzooming":
				this.addMouseWheelZooming();
				break;
			case "rotation":
		
				this.addRotatingActions();
				break;
			default:
				break;
		}
	
	},
	
	addPanningActions: function(controlDiv){
	        this._addEnabledControl("pan");
		this.createButton(12,180,{x:-6,y:-54},{'actiontype':'N','name':'pan north','buttonType': 'narrow'});
		this.createButton(12,270,{x:10,y:-38},{'actiontype':'E','name':'pan east','buttonType': 'earrow'});
		//this.createButton(10,90,{x:16,y:16},{'actiontype':'O','name':'re-center','buttonType': ''});
		this.createButton(12,90,{x:-22,y:-38},{'actiontype':'W','name':'pan west','buttonType': 'warrow'});
		this.createButton(12,0,{x:-6,y:-20},{'actiontype':'S','name':'pan south','buttonType': 'sarrow'});			
		this.applyLayer();		

	},
	addRotatingActions: function(){
		/*
		var rotateCanvas = this.controlCanvas.getDomElement();
		this.createButton(rotateCanvas,10,180,{x:16,y:2},{'actiontype':'rotatezup','name':'pan north','buttonType': 'narrow'});
		this.createButton(rotateCanvas,10,0,{x:16,y:30},{'actiontype':'rotatezdown','name':'pan south','buttonType': 'sarrow'});			
			
		this.createButton(rotateCanvas,10,270,{x:30,y:16},{'actiontype':'rotatezright','name':'rotate to right','buttonType': 'earrow'});
		this.createButton(rotateCanvas,10,90,{x:2,y:16},{'actiontype':'rotatezleft','name':'rotate to left','buttonType': 'warrow'});
		rotateCanvas.onmouseup = this._panzoomClickHandler;*/

	},	
	addZoomingActions: function(){
	        this._addEnabledControl("zoom");
		this.createButton(12,180,{x:-6,y:12},{'actiontype':'in','name':'zoom in','buttonType': 'plus'});		
		this.createButton(12,180,{x:-6,y:42},{'actiontype':'out','name':'zoom out','buttonType': 'minus'});	
	        this.applyLayer();
	}	
	    ,zoom: function(x,y){
	         var t = this.getTransformation();
	         t.scale.x = x;
	         if(!y) y=  x;
	         t.scale.y = y;
	         this.setTransformation(t);
	    }
        ,panTo: function(x,y){
                //if(!this.enabled) return;
                var t = this.getTransformation();
                
                var finalX = -x;
                var finalY = -y;
                var thisx,thisy;
                var direction = {};
                var difference = {};
                
                thisx = t.translate.x;
                thisy = t.translate.y;
                
                difference.x=  thisx - finalX;
                difference.y = thisy - finalY;
                
                direction.x = -difference.x / 5;
                direction.y = -difference.y / 5;

                var change = true;
                
                var that = this;
                var f = function(){
                   
                        change= {x: false,y:false};
                        if(thisx > finalX && thisx + direction.x > finalX) {thisx += direction.x;change.x=true;}
                        else if(thisx < finalX && thisx + direction.x < finalX) {thisx += direction.x;change.x=true;}
                        else{
                                t.translate.x = finalX;
                        }
                
                        if(thisy > finalY && thisy + direction.y > finalY) {thisy += direction.y;change.y=true;}
                        else if(thisy < finalY && thisy + direction.y < finalY) {thisy += direction.y;change.y=true;}
                        else{
                                change.x = true;
                                t.translate.y =finalY;
                        }
                
                        if(change.x){
                                t.translate.x = thisx;
                        }
                        else{
                                t.translate.x = finalX;
                        }
                        if(change.y){
                                t.translate.y = thisy;
                        }
                        else{
                                t.translate.y = finalY;
                        }
    
                        if(t.translate.x != finalX && t.translate.y != finalY){
                                that.setTransformation(t); 
                                window.setTimeout(f,5);
                        }
                        else{
                                that.setTransformation(t);
                        }
  
                };
                
                f();
                                       
               

                //window.setTimeout(pan,200);
        }
	,transform: function(){
		if(this.enabled){
			var t = this.getTransformation();
			var s = t.scale;
			var tr = t.translate;
			if(s.x <= 0) s.x = 0.1125;
			if(s.y <= 0) s.y = 0.1125;

                        var ok = true;
                        var lim = this.limits;
                        if(lim.scale){
                                if(s.y < lim.scale.miny) t.scale.y = lim.scale.miny;
                                if(s.x < lim.scale.minx) t.scale.x = lim.scale.minx;
                                
                                if(s.y > lim.scale.y) t.scale.y = lim.scale.y;
                                if(s.x > lim.scale.x) t.scale.x = lim.scale.x;
		        }
		        //remove origin?
		        //var translatex = t.origin.x+ (t.translate.x * t.scale.x);
                //var translatey = t.origin.y+ (t.translate.y *t.scale.y);
		        this.handler(this.transformation);

		}
	},
	_panzoomClickHandler: function(e,hit,controller) {
	
	    	if(!hit) return;
	   
		var pan = {};
		var t =controller.getTransformation();
		if(!t.scale) t.scale = {x:1,y:1};
		if(!t.translate) t.translate = {x:0,y:0};
		if(!t.rotate) t.rotate = {x:0,y:0,z:0};
		
		var scale =t.scale;
		
		pan.x = parseFloat(this.pansensitivity / scale.x);
		pan.y = parseFloat(this.pansensitivity / scale.y);
	
		switch(hit.getProperty("actiontype")) {
			case "W":
				t.translate.x += pan.x;
				break;
			case "O":
				t.translate.x = 0;
				t.translate.y = 0;
				break;

			case "E":
				t.translate.x -= pan.x;
				break;
			case "N":
				t.translate.y += pan.y;
				break;
			case "S":
				t.translate.y -= pan.y;
				break;
			case "in":
				scale.x *= 2;
				scale.y *= 2;
				break;
			case "out":
				scale.x /= 2;
				scale.y /= 2;			
				break;
			case "rotatezright":
				if(!t.rotate.z) t.rotate.z = 0;
				//console.log("right",t.rotate.z);
				t.rotate.z -= 0.1;
				var left =6.28318531;
				
				if(t.rotate.z <0 )t.rotate.z =left;
				break;
			case "rotatezup":
				if(!t.rotate.y) t.rotate.y = 0;
				t.rotate.y += 0.1;
				break;
			case "rotatezdown":
				if(!t.rotate.y) t.rotate.y = 0;
				t.rotate.y -= 0.1;
				break;
			case "rotatezleft":
				if(!t.rotate.z) t.rotate.z = 0;
				t.rotate.z += 0.1;
				break;
			default:
				break;
		}
		controller.transform();
                //console.log("done",controller);
		return false;
	}
};
/*VismoController.prototype.panzoomcontrolsSVG ="<?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:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"   xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"   width=\"60px\"   height=\"120px\"   id=\"svg3820\"   sodipodi:version=\"0.32\"   inkscape:version=\"0.46\"   sodipodi:docname=\"panzoomcontrols.svg\"   inkscape:output_extension=\"org.inkscape.output.svg.inkscape\">  <defs     id=\"defs3\">    <linearGradient       id=\"linearGradient3735\">      <stop         style=\"stop-color:#ffffff;stop-opacity:1;\"         offset=\"0\"         id=\"stop3737\" />      <stop         style=\"stop-color:#0000f0;stop-opacity:1;\"         offset=\"1\"         id=\"stop3739\" />    </linearGradient>    <linearGradient       id=\"linearGradient3745\">      <stop         style=\"stop-color:#000000;stop-opacity:1;\"         offset=\"0\"         id=\"stop3747\" />      <stop         style=\"stop-color:#ffffef;stop-opacity:0;\"         offset=\"1\"         id=\"stop3749\" />    </linearGradient>    <inkscape:perspective       sodipodi:type=\"inkscape:persp3d\"       inkscape:vp_x=\"0 : 526.18109 : 1\"       inkscape:vp_y=\"6.123234e-14 : 1000 : 0\"       inkscape:vp_z=\"744.09448 : 526.18109 : 1\"       inkscape:persp3d-origin=\"372.04724 : 350.78739 : 1\"       id=\"perspective3826\" />  </defs>  <sodipodi:namedview     inkscape:document-units=\"mm\"     id=\"base\"     pagecolor=\"#ffffff\"     bordercolor=\"#666666\"     borderopacity=\"1.0\"     inkscape:pageopacity=\"0.0\"     inkscape:pageshadow=\"2\"     inkscape:zoom=\"4\"     inkscape:cx=\"14.379355\"     inkscape:cy=\"60.049799\"     inkscape:current-layer=\"layer1\"     showgrid=\"true\"     inkscape:window-width=\"1440\"     inkscape:window-height=\"776\"     inkscape:window-x=\"-84\"     inkscape:window-y=\"22\" />  <metadata     id=\"metadata4\">    <rdf:RDF>      <cc:Work         rdf:about=\"\">        <dc:format>image/svg+xml</dc:format>        <dc:type           rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" />      </cc:Work>    </rdf:RDF>  </metadata>  <g     inkscape:label=\"Layer 1\"     inkscape:groupmode=\"layer\"     id=\"layer1\">    <rect       style=\"opacity:1;fill:#fafafa;fill-opacity:1;stroke:#000000;stroke-width:1.25095212000000000;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"       id=\"rect4374\"       width=\"3.036346\"       height=\"29.855259\"       x=\"26.456741\"       y=\"77.110023\" />    <path       sodipodi:type=\"arc\"       style=\"opacity:0;fill:#ffc100;fill-opacity:0.18999999;fill-rule:evenodd;stroke:#00d300;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.98500001\"       id=\"path2811\"       sodipodi:cx=\"36.681629\"       sodipodi:cy=\"40.457794\"       sodipodi:rx=\"22.848825\"       sodipodi:ry=\"23.466362\"       d=\"M 59.530455,40.457794 A 22.848825,23.466362 0 1 1 13.832804,40.457794 A 22.848825,23.466362 0 1 1 59.530455,40.457794 z\"       transform=\"translate(-10.077156,-13.286926)\" />    <path       sodipodi:type=\"star\"       style=\"fill:#ffffff\"       id=\"path2817\"       sodipodi:sides=\"5\"       sodipodi:cx=\"21.984276\"       sodipodi:cy=\"13.286215\"       sodipodi:r1=\"0.34933102\"       sodipodi:r2=\"0.17466551\"       sodipodi:arg1=\"-0.78539816\"       sodipodi:arg2=\"-0.15707963\"       inkscape:flatsided=\"false\"       inkscape:rounded=\"0\"       inkscape:randomized=\"0\"       d=\"M 22.23129,13.0392 L 22.156791,13.258891 L 22.295532,13.444808 L 22.063572,13.441843 L 21.929628,13.631245 L 21.860769,13.409722 L 21.639246,13.340862 L 21.828648,13.206918 L 21.825683,12.974959 L 22.0116,13.1137 L 22.23129,13.0392 z\"       transform=\"translate(-2.9137398,-0.9362086)\" />    <path       sodipodi:type=\"arc\"       style=\"fill:#fafafa;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.99893030000000005;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;opacity:1\"       id=\"path3847\"       sodipodi:cx=\"113.64216\"       sodipodi:cy=\"108.12209\"       sodipodi:rx=\"23.233507\"       sodipodi:ry=\"20.960665\"       d=\"M 136.87567,108.12209 A 23.233507,20.960665 0 1 1 90.408651,108.12209 A 23.233507,20.960665 0 1 1 136.87567,108.12209 z\"       transform=\"matrix(0.9778731,0,0,-1.0598112,-84.661617,141.94941)\" />    <path       style=\"fill:#dcdcdc;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"       d=\"M 39.621219,21.031683 L 47.389849,26.975113 L 39.969679,33.117243 L 41.484209,27.164163 L 39.621219,21.031683 z\"       id=\"north\"       inkscape:label=\"north\"       sodipodi:nodetypes=\"ccccc\" />    <path       style=\"fill:#dcdcdc;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"       d=\"M 20.231889,13.770245 L 26.175319,6.0016174 L 32.317449,13.421792 L 26.364359,11.907259 L 20.231889,13.770245 z\"       id=\"path3757\"       inkscape:label=\"north\"       sodipodi:nodetypes=\"ccccc\" />    <path       style=\"fill:#dcdcdc;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"       d=\"M 20.048989,40.437803 L 25.992419,48.206433 L 32.134549,40.786253 L 26.181459,42.300793 L 20.048989,40.437803 z\"       id=\"path3761\"       inkscape:label=\"north\"       sodipodi:nodetypes=\"ccccc\" />    <path       style=\"fill:#dcdcdc;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"       d=\"M 12.629649,33.160653 L 4.8610222,27.217223 L 12.281197,21.075093 L 10.766664,27.028173 L 12.629649,33.160653 z\"       id=\"path3765\"       inkscape:label=\"north\"       sodipodi:nodetypes=\"ccccc\" />    <path       sodipodi:type=\"arc\"       style=\"fill:#ff0000;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"       id=\"path3849\"       sodipodi:cx=\"114.65231\"       sodipodi:cy=\"133.62845\"       sodipodi:rx=\"0\"       sodipodi:ry=\"2.5253813\"       d=\"M 114.65231,133.62845 A 0,2.5253813 0 1 1 114.65231,133.62845 A 0,2.5253813 0 1 1 114.65231,133.62845 z\" />    <path       sodipodi:type=\"arc\"       style=\"fill:#fafafa;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:3.29227274000000003;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;opacity:1\"       id=\"path4600\"       sodipodi:cx=\"113.64216\"       sodipodi:cy=\"108.12209\"       sodipodi:rx=\"23.233507\"       sodipodi:ry=\"20.960665\"       d=\"M 136.87567,108.12209 A 23.233507,20.960665 0 1 1 90.408651,108.12209 A 23.233507,20.960665 0 1 1 136.87567,108.12209 z\"       transform=\"matrix(0.3044572,0,0,-0.3133744,-6.349179,108.99488)\" />    <path       sodipodi:type=\"arc\"       style=\"fill:#fafafa;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:3.29227274000000003;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;opacity:1\"       id=\"path4602\"       sodipodi:cx=\"113.64216\"       sodipodi:cy=\"108.12209\"       sodipodi:rx=\"23.233507\"       sodipodi:ry=\"20.960665\"       d=\"M 136.87567,108.12209 A 23.233507,20.960665 0 1 1 90.408651,108.12209 A 23.233507,20.960665 0 1 1 136.87567,108.12209 z\"       transform=\"matrix(0.3044572,0,0,-0.3133744,-6.5991733,140.49488)\" />    <path       style=\"fill:#dcdcdc;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;fill-opacity:1\"       d=\"M 29.344931,79.34136 L 26.693281,79.164583 L 26.870057,76.336156 L 22.804193,76.159379 L 23.157747,73.330952 L 26.870057,73.507729 L 26.870057,70.856078 L 29.875261,71.032855 L 29.875261,73.684505 L 33.587572,74.038059 L 33.587572,76.512933 L 29.521708,76.336156 L 29.344931,79.34136 z\"       id=\"path3299\" />    <path       style=\"fill:#dcdcdc;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;fill-opacity:1\"       d=\"M 26.781669,107.80241 L 22.715805,107.62563 L 23.069359,104.79721 L 26.781669,104.97398 L 29.786873,105.15076 L 33.499184,105.50431 L 33.499184,107.97919 L 29.43332,107.80241 L 26.781669,107.80241 z\"       id=\"path3301\"       sodipodi:nodetypes=\"ccccccccc\" />  </g></svg>";*/

/*
Some common utils used throughout package 
*/
var VismoMapUtils = {
	googlelocalsearchurl: "http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q="
	
	,optimiseForIE6: function(geojson){
      	var newf = [];
        for(var i=0; i < geojson.features.length;i++){
            var f = geojson.features[i];
            var coordinates = f.geometry.coordinates;


            var newc = [];
            
            var good = false;
            
            if(coordinates.length <2){
                good = true;
            }
            for(var j=0; j < coordinates.length; j++){
                var c1 = coordinates[j];
                
            }
            
            var bb = f.geometry.bbox;
            if(bb){
                var dx = bb[2] - bb[0]; var dy= bb[3]- bb[1]; if(dy<0)dy =-dy;if(dx<0)dx =-dx;
                if(dx < 1 || dy < 1){
                    good =false;
                }
            }
            
            if(good){
                newf.push(f);
            }
        }
        geojson.features= newf;
        return geojson;
	
	}
	,addBoundingBoxes: function(geojson){ //currently MultiPolygon only..
		var geojsonbb = geojson;
		for(var i=0; i < geojson.features.length; i++){
			var f = geojson.features[i];

			var g = f.geometry;
			var c = g.coordinates;

			
			if(g.type.toLowerCase() == 'multipolygon'){
				var x1,y1,x2,y2;
				
				var horizontal = {belowzero:0,abovezero:0};
				var vertical = {belowzero:0,abovezero:0};
			
				for(var j=0; j < c.length; j++){
					for(var k=0; k < c[j].length; k++){
						
						for(var l=0; l < c[j][k].length; l++){
							var x = c[j][k][l][0];
							var y = c[j][k][l][1];
							/*if(x < 0 && horizontal.abovezero > horizontal.belowzero){
								x = 180;
							}
							else if(x > 0 && horizontal.abovezero < horizontal.belowzero){
								x = -180;
							}*/
							if(!x1) x1= x;
							if(!x2) x2 =x;
							if(!y1) y1 = y;
							if(!y2) y2 = y;
							if(y > y2) y2 = y;
							if(y < y1) y1 = y;
							if(x < x1) x1 = x;
							if(x > x2) x2= x;
							
							if(x > 0){
								horizontal.abovezero +=1;
							}
							else{
								horizontal.belowzero +=1;
							}
							
							if(y > 0){
								vertical.abovezero +=1;
							}
							else{
								vertical.belowzero +=1;
							}
							
									
										
						}
					}
				}
				
				//if(f.properties.name == "RUSSIAN FEDERATION")
				//console.log(x1,x2);
	
				g.bbox = [];
				g.bbox.push(x1);
				g.bbox.push(y1);
				g.bbox.push(x2);
				g.bbox.push(y2);
				x1 = false; x2=false;y1=false;y2=false;
			}
			
		}
		return geojsonbb;
	}
	 ,tile2long: function(x,z) {
	  	return (x/Math.pow(2,z)*360-180);
	 }
	 ,tile2lat: function(y,z) {
	  	var n=Math.PI-2*Math.PI*y/Math.pow(2,z);
	  	return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
	 }
	,getLongLatAtXY: function(x,y,eMap){
		
		var res = VismoMapUtils.getLongLatFromMouse(x,y,eMap);
	
		
		return res;
	}
	,getSlippyTileNumber: function(lo,la,zoomL,eMap){
		var n = Math.pow(2,zoomL);
		var x = lo;

		var tilex = ((lo + 180)/360) *n;

		tilex = Math.floor(tilex);
		tiley =(Math.floor((1-Math.log(Math.tan(la*Math.PI/180) + 1/Math.cos(la*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoomL)));		
		return {x: tilex, y:tiley};
	}
	,getLocationsFromQuery: function(query,callback){
		var that = this;
		var fileloadedcallback = function(status,params,responseText,url,xhr){
				var response = eval("("+responseText+")");

				if(response.responseStatus == 200){
					var results = response.responseData.results;
					callback(results);
					
					return;
				}

		};
			
	
		VismoFileUtils.loadRemoteFile(that.googlelocalsearchurl+query,fileloadedcallback);
	}
	,getLongLatFromMouse: function(x,y,vismoMap){
		var t =vismoMap.getTransformation();
		var pos = VismoClickingUtils.undotransformation(x,y,t);	
		
		if(vismoMap.settings.projection) {
			pos = vismoMap.settings.projection.inversexy(pos.x,pos.y,t);
		}

		var lo = pos.x;
		var la = -pos.y;
		
		
		/*if(la > 85.0511) la = -la%85.0511;
		if(la < -85.0511) la = -la%85.0511;
		if(lo < -180) lo = -lo%180;
		if(lo > 180) lo = - lo%180;
		*/
		return {latitude: la, longitude: lo};
	}
	,_radToDeg: function(rad){
		return rad / (Math.PI /180);
	},
	_degToRad: function(deg) {
		//return ((deg + 180)/360) ;
		
		return (deg * Math.PI) / 180.0;
	},
	fitgeojsontocanvas: function(json,canvas){ /*canvas must have style width and height properties, returns an VismoTransformation*/
		var view ={};
		var f =json.features;
		for(var i=0; i < f.length; i++){
			var c = f[i].geometry.coordinates;
											
			for(var j=0; j < c.length; j++ ){
				for(var k=0; k < c[j].length; k++){
					

					for(var l=0; l < c[j][k].length;l++){
						
		
						var x =c[j][k][l][0];
						var y = c[j][k][l][1];
						if(!view.x1 || x <view.x1) {
							view.x1 = x;
						}
						else if(!view.x2 || x >view.x2) {
							view.x2 = x;
						}
						
						if(!view.y1 || y <view.y1) {
							view.y1 = y;
						}
						else if(!view.y2 || y >view.y2) {
							view.y2 = y;
						}
						

					}
						
				}
				
			}
		}
		if(!json.transform) json.transform ={};
		if(!json.transform.scale) json.transform.scale = {x:1, y:1};
		if(!json.transform.translate) json.transform.translate = {x:0,y:0};
		
		var canvasx =		parseFloat(canvas.style.width);
		var canvasy =parseFloat(canvas.style.height);
		view.center = {};
		view.width = (view.x2 - view.x1);
		view.height = (view.y2 - view.y1)
		view.center.x = view.x2 - (view.width/2);
		view.center.y = view.y2 - (view.height/2);
		//console.log(view.center.y, view.height);
		var scale = 1,temp;
		var tempx = parseFloat(canvasx/view.width);
		var tempy = parseFloat(canvasy/view.height);

		if(tempx < tempy) temp = tempx; else temp = tempy;
		
		var transform = {scale:{},translate:{}};
		transform.scale.x = temp;
		transform.scale.y = temp;

		transform.boundingBox = view;

		transform.translate.x = -view.center.x;
		transform.translate.y = view.center.y;//view.center.y;	
		return transform;
	},
	/*does not yet support undoing rotating */
	_testCanvas: function(ctx){
		ctx.beginPath();
		ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
		ctx.moveTo(110,75);
		ctx.arc(75,75,35,0,Math.PI,false);   // Mouth (clockwise)
		ctx.moveTo(65,65);
		ctx.arc(60,65,5,0,Math.PI*2,true);  // Left eye
		ctx.moveTo(95,65);
		ctx.arc(90,65,5,0,Math.PI*2,true);  // Right eye
		ctx.stroke();

	},	
	_undospherify: function (x,y,transformation,radius){
		var pos= this._spherifycoordinate(x,y,transformation);
		var latitude = Math.asin(y / radius);
		var longitude = Math.asin(parseFloat(x / radius) / Math.cos(latitude));

				
	
		//if(transformation.rotate.z && longitude != 'NaN')longitude -= transformation.rotate.z;
		//longitude = longitude % (6.28318531);
		//if(longitude < 0) longitude = longitude 

		if(transformation.rotate) {
			var r =transformation.rotate.z;
			//console.log("from",longitude);
			longitude +=r;
		
			//longitude =longitude% (6.28318531);
			
		}
		var lon = VismoMapUtils._radToDeg(longitude);
		var lat = VismoMapUtils._radToDeg(latitude);
		//console.log("to",longitude,r,lon);
		return {x:lon,y:lat};
	},
	_spherifycoordinate: function(lon,lat,transformation,radius){
		//http://board.flashkit.com/board/archive/index.php/t-666832.html
		var utils = VismoMapUtils;
		var res = {};
		
		var longitude = VismoMapUtils._degToRad(lon);
		var latitude = VismoMapUtils._degToRad(lat);
 		var wraplat = false;
 		// assume rotate values given in radians
		if(transformation && transformation.rotate){
			//latitude += transformation.rotate.x;
			
			var rotation =transformation.rotate.z;
			//rotation = transformation.translate.x;
			if(rotation){
				var r =parseFloat(rotation);
			
				var newl =parseFloat(longitude+r);
			
				//console.log(longitude,"->",newl,longitude,r,transformation.rotate.z);
			
				longitude +=r;
			}
			if(transformation.rotate.y){
				latitude += parseFloat(transformation.rotate.y);
				/*var limit =VismoMapUtils._degToRad(85);
				if(latitude <-limit){
					latitude += (2 * limit);
					res.movedNorth = true;
					
				}
				
				if(latitude > limit){
					latitude -= (2 * limit);
					res.movedSouth = true;
					
					
				}
				*/	
				
				//latitude = latitude % 6.28318531;
				
			} 
		}
		// latitude is 90-theta, where theta is the polar angle in spherical coordinates
		// cos(90-theta) = sin(theta)
		// sin(90-theta) = cos(theta)
		// to transform from spherical to cartesian, we would normally use radius*Math.cos(theta)
		//   hence in this case we use radius*Math.sin(latitude)
		// similarly longitude is phi-180, where phi is the azimuthal angle
		// cos(phi-180) = -cos(phi)
		// sin(phi-180) = -sin(phi)
		// to transform from spherical to cartesian, we would normally use radius*Math.sin(theta)*Math.cos(phi)
		//   we must exchange for theta as above, but because of the circular symmetry
		//   it does not matter whether we multiply by sin or cos of longitude	
	
		longitude = longitude % 6.28318531; //360 degrees		
	
		
		
		
		res.y = (radius) * Math.sin(latitude);	
		//console.log(latitude);
		//if(wraplat) res.y = ["M",res.y];
		/*
		
		if(latitude > 85.0511){
			res.y = (-radius) * Math.sin(latitude);	
		}
		else{
		res.y = (radius) * Math.sin(latitude);		
		}
		*/
		
		//if(latitude > 85.0511)
		
		
		if(longitude < 1.57079633 || longitude > 4.71238898){//0-90 (right) or 270-360 (left) then on other side 
			res.x = (radius) * Math.cos(latitude) * Math.sin(longitude);		
		}
		else{
			//console.log(longitude,"bad",transformation.rotate.z);
			res.x = false;
		}
	
		return res;
	}

};Array.prototype.contains = function(item)
{
	return this.indexOf(item) != -1;
};


function mozillaSaveFile(filePath,content)
{
	if(window.Components) {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
			file.initWithPath(filePath);
			if(!file.exists())
				file.create(0,0664);
			var out = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
			out.init(file,0x20|0x02,00004,null);
			out.write(content,content.length);
			out.flush();
			out.close();
			return true;
		} catch(ex) {
			return false;
		}
	}
	return null;
}


var VismoFileUtils= {
	saveFile: function(fileUrl,content)
	{
		mozillaSaveFile(fileUrl,content); return;
		jQuery.file.save({fileUrl:fileUrl,content:content});
	}	
	,convertUriToUTF8:function(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);
	}
	
	,getLocalPath:function(origPath)
	{
		var originalPath = VismoFileUtils.convertUriToUTF8(origPath,"UTF-8");
		
		// Remove any location or query part of the URL
		var argPos = originalPath.indexOf("?");
		if(argPos != -1)
			originalPath = originalPath.substr(0,argPos);
		var hashPos = originalPath.indexOf("#");
		if(hashPos != -1)
			originalPath = originalPath.substr(0,hashPos);
		// Convert file://localhost/ to file:///
		if(originalPath.indexOf("file://localhost/") == 0)
			originalPath = "file://" + originalPath.substr(16);
		// Convert to a native file format
		var localPath;

		if(originalPath.charAt(9) == ":") // pc local file
			localPath = unescape(originalPath.substr(8)).replace(new RegExp("/","g"),"\\");
		else if(originalPath.indexOf("file://///") == 0) // FireFox pc network file
			localPath = "\\\\" + unescape(originalPath.substr(10)).replace(new RegExp("/","g"),"\\");
		else if(originalPath.indexOf("file:///") == 0) // mac/unix local file
			localPath = unescape(originalPath.substr(7));
		else if(originalPath.indexOf("file:/") == 0) // mac/unix local file
			localPath = unescape(originalPath.substr(5));
		else if(originalPath.indexOf("http") == 0){ //jon hack for online

			var end =originalPath.lastIndexOf("/");
			localPath = unescape(originalPath.substr(0,end+1));
		}
		else // pc network file
			localPath = "\\\\" + unescape(originalPath.substr(7)).replace(new RegExp("/","g"),"\\");
		return localPath;
	}

	,loadRemoteFile: function(url,callback,params,headers,data,contentType,username,password,allowCache)
	{
		//callback parameters: status,params,responseText,url,xhr
		return this._httpReq("GET",url,callback,params,headers,data,contentType,username,password,allowCache);
	}
	/*currently doesnt work with jpg files - ok formats:gifs pngs*/
	,saveImageLocally: function(sourceurl,dest,dothiswhensavedlocally,dothiswhenloadedfromweb) {
		
		var localPath = VismoFileUtils.getLocalPath(document.location.toString());
	
		var savePath;
		if((p = localPath.lastIndexOf("/")) != -1) {
			savePath = localPath.substr(0,p) + "/" + dest;
		} else {
			if((p = localPath.lastIndexOf("\\")) != -1) {
				savePath = localPath.substr(0,p) + "\\" + dest;
			} else {
				savePath = localPath + "/" + dest;
			}
		}
		
		var onloadfromweb = function(status,params,responseText,url,xhr){
			try{
				if(dothiswhenloadedfromweb){
					dothiswhenloadedfromweb(url);
				}
				//console.log("VismoFileUtil.saveFile doesnt work for iamges it might seem",savePath);
				VismoFileUtils.saveFile(savePath,responseText);
		
			}
			catch(e){
				console.log("error saving locally.."+ e);
			}

		};
		
		var onloadlocally = function(responseText,url,xhr){		
		
				if(dothiswhensavedlocally){
					dothiswhensavedlocally(dest);
				}
			
		};
		

		try{
			var r = jQuery.get(dest,null,onloadlocally);
			if(r.status == 404) throw "404 error";
		
		}
		catch(e){//couldnt load probably doesn't exist!
			VismoFileUtils.loadRemoteFile(sourceurl,onloadfromweb,null,null,null,null,null,null,true);		
		}

		
		
	}
	,_httpReq: function (type,url,callback,params,headers,data,contentType,username,password,allowCache)
	{
		var x = null;
		try {
			x = new XMLHttpRequest(); //# Modern
		} catch(ex) {
			try {
				x = new ActiveXObject("Msxml2.XMLHTTP"); //# IE 6
			} catch(ex2) {
			}
		}
		if(!x)
			return "Can't create XMLHttpRequest object";
		x.onreadystatechange = function() {
			try {
				var status = x.status;
			} catch(ex) {
				status = false;
			}
			if(x.readyState == 4 && callback && (status !== undefined)) {
				if([0, 200, 201, 204, 207].contains(status))
					callback(true,params,x.responseText,url,x);
				else{
					callback(false,params,null,url,x);
			
				}
				x.onreadystatechange = function(){};
				x = null;
			}
		};
		try {
			if(window.Components && window.netscape && window.netscape.security && document.location.protocol.indexOf("http") == -1)
			window.netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			
			if(!allowCache)
				url = url + (url.indexOf("?") < 0 ? "?" : "&") + "nocache=" + Math.random();
			else{
				url = url + (url.indexOf("?") < 0 ? "?" : "&");
			}
			x.open(type,url,true,username,password);
			if(data)
				x.setRequestHeader("Content-Type", contentType || "application/x-www-form-urlencoded");
			if(x.overrideMimeType)
				x.setRequestHeader("Connection", "close");
			if(headers) {
				for(var n in headers)
					x.setRequestHeader(n,headers[n]);
			}
		//	x.setRequestHeader("X-Requested-With", "TiddlyWiki " + formatVersion());
		x.overrideMimeType('text/plain; charset=x-user-defined');
			x.send(data);
		} catch(ex) {
			//console.log(ex);
			//throw ex;
		}
		return x;
	},
	

	_getXML:function(str) {
		if(!str)
			return null;
		var errorMsg;
		try {
			var doc = new ActiveXObject("Microsoft.XMLDOM");
			doc.async="false";
			doc.loadXML(str);
		}
		catch(e) {
			try {
				var parser=  new DOMParser();
				var doc = parser.parseFromString(str,"text/xml");
			}
			catch(e) {
				return e.message;
			}
		}

		return doc;	
	}

	,getChildNodeValue: function(ofThisNode){
		var value= "";
		if(ofThisNode.childNodes){
			
			for(var k=0; k < ofThisNode.childNodes.length; k++){
			
				if(ofThisNode.childNodes[k].nodeValue){
					value += ofThisNode.childNodes[k].nodeValue;
				}
			}
		}
		return value;
	}
};/*some conversion functions that convert to geojson */
var VismoConversion ={
	niaveGeoJsonFlatten: function(geojson,niaveness){
		
		var newdata = geojson;
		var coordsDropped = 0;
		for(var i=0; i < newdata.features.length; i++){
			var g = newdata.features[i].geometry;
		
			if(g.type == 'MultiPolygon'){
				for(var ij =0; ij < g.coordinates.length; ij++){
					for(var j=0; j < g.coordinates[ij].length; j++){
		
						var bettercoords = [];
						var every = 0;
						if(g.coordinates[ij][j].length > 50){
							for(var k=0; k < g.coordinates[ij][j].length; k++){

								var c = g.coordinates[ij][j][k];
							
								if(every == 0){
									var x = parseFloat(c[0]);
									var y = parseFloat(c[1]);
									bettercoords.push([x,y]);
									every= niaveness;
								}
								else{
									every -= 1;
								}	
			
							}
							coordsDropped += (g.coordinates[ij][j].length - bettercoords.length);
							g.coordinates[ij][j] = bettercoords;
						}
					}
				}
			}
		}
		console.log(coordsDropped,"dropped");
		return newdata;
	}
	,svgToGeoJson: function(svg,canvas){
		var svgxml = VismoFileUtils._getXML(svg);
		var res = VismoMapSVGUtils.convertSVGToMultiPolygonFeatureCollection(svgxml);
		
		
		//res = VismoMapUtils.fitgeojsontocanvas(res,canvas);
		//console.log(res.boundingBox);
		//res
		//work out here where origin should be (half of the maximum width of the svg coordinate space should be 0)
		return res;
	},
	_kmlPolygonToFeature: function(xmlNode,feature){
		var geocoordinates = [];
		var polyChildren =xmlNode.childNodes;
		
		for(var k=0; k < polyChildren.length; k++){
			var fail = true;
			if(polyChildren[k].tagName =='outerBoundaryIs'){
				
				var outerChildren =polyChildren[k].childNodes;
				for(var l=0; l < outerChildren.length; l++){
					if(outerChildren[l].tagName == 'LinearRing'){
						
						var ringChildren =outerChildren[l].childNodes;
						for(var m=0; m < ringChildren.length; m++){
							if(ringChildren[m].tagName == 'coordinates'){
							
								
								var geometry = VismoFileUtils.getChildNodeValue(ringChildren[m]);
								geometry = geometry.trim();
						
								
								var coords = geometry.split(" "); //\n?
								for(var n=0; n < coords.length; n+= 1){
									var values = coords[n].split(",");
									var longitude= parseFloat(values[0]);
									var latitude = parseFloat(values[1]);
									var altitude = parseFloat(values[2]);
									geocoordinates.push([longitude,latitude]);
								
								}
								if(coords.length ==0){
									return false;
								}
								else{
									fail = false;
								}
								feature.geometry.coordinates.push([geocoordinates]);			
								
							}	
						}
					}
				}

                                                
			}
		}
		if(!feature){
			fail  = true;
		}
		else if(feature.geometry.coordinates[0].length == 0){
			fail = true;
		}
		else if(feature.geometry.coordinates[0][0].length == 1){
			fail = true;
		}
	
		if(fail) {
			return false;
		}
		else{
				
			return feature;
		}
	}
	,kmlToGeoJson: function(kml){
		var geojson = {type:"FeatureCollection", features:[]};
		
		var xml =VismoFileUtils._getXML(kml);
		var items = xml.getElementsByTagName("Placemark");
		
		for(var i=0; i < items.length; i++){
	
			var feature = {type:'Feature', geometry:{type:'MultiPolygon', coordinates:[]},properties:{'name':'georss'}};
						
			
			var att = items[i].childNodes;
			
			for(var j=0; j < att.length; j++){
				var fail = false;
				
				if(att[j].tagName == 'name' && att[j].firstChild){
					feature.properties.name =att[j].firstChild.nodeValue;
				}
				
				if(att[j].tagName == 'Polygon'){
					
					var succeeded = this._kmlPolygonToFeature(att[j],feature);

					if(succeeded){
						feature = succeeded;
					}
					else{
						fail = true;
					}
				}
				if(att[j].tagName == 'MultiGeometry'){
					
					var children = att[j].childNodes;
					for(var k=0; k < children.length; k++){
						if(children[k].tagName == 'Polygon'){

							var succeeded = this._kmlPolygonToFeature(children[k],feature);
						
							if(succeeded){
								feature = succeeded;
							}
							else{
								fail = true;
							}
						}	
					}
				}
				
			}
			//console.log("ere",fail);
			//if(!fail)
	//console.log(feature.geometry.coordinates.length);
			if(!fail && feature && feature.geometry.coordinates.length > 0) {
					geojson.features.push(feature);
			}
		}
	
		return geojson;
	}
	
	,geoRssToGeoJson : function (georss){
	
		var geojson = {type:"FeatureCollection", features:[]};
		var xml =VismoFileUtils._getXML(georss);
		var items = xml.getElementsByTagName("item");
		
		for(var i=0; i < items.length; i++){
			
			var feature = {type:'Feature', geometry:{type:'MultiPolygon', coordinates:[]},properties:{'name':'georss'}};
						
			var fail = false;
			var att = items[i].childNodes;
			for(var j=0; j < att.length; j++){

				
				if(att[j].tagName == 'title' && att[j].firstChild){
					feature.properties.name =att[j].firstChild.nodeValue;
				}
				if(att[j].tagName == 'description' && att[j].firstChild){
					feature.properties.description =att[j].firstChild.nodeValue;
				}
				
				if(att[j].tagName == 'georss:polygon'){
					var geocoordinates = [];
					//console.log(att[j].innerHTML,att[j].firstChild,"inner");

					var geometry = VismoFileUtils.getChildNodeValue(att[j]);
					geometry = geometry.trim();
					geometry = geometry.replace(/  +/g, " ");
					geometry = geometry.replace(/\n/g, "");
					var values = geometry.split(" ");
				
					if(values[0] != values[values.length-2] |values[1] != values[values.length-1]){
						values.push(values[0]);
						values.push(values[1]);
					}
					for(var k=0; k < values.length - 1; k+= 2){
						var latitude = parseFloat(values[k]);
						var longitude= parseFloat(values[k+1]);
						geocoordinates.push([longitude,latitude]);
					}
					feature.geometry.coordinates.push([geocoordinates]);
				}
				
			}
			if(!fail){
				geojson.features.push(feature);
			}
			else{
				
				//console.log("Unable to construct feature " +feature.properties.name+". Invalid georss coordinates: first and last coordinates should be same. ");
			}
		}
		
		return geojson;
	}

};var VismoClickingUtils = {
        //to be implemented..
        inVisibleArea: function(vismoCanvas,vismoShape){
                var bb = vismoShape.getBoundingBox();
                return true;
        }
        ,scrollXY: function(){
          var scrOfX = 0, scrOfY = 0;
          if( typeof( window.pageYOffset ) == 'number' ) {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
          } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
          } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
          }
          return {x: scrOfX,y: scrOfY};
        }
	,getRealXYFromMouse: function(e,t){
		var newpos =VismoClickingUtils.getMouseFromEvent(e);
		newpos = VismoClickingUtils.undotransformation(newpos.x,newpos.y,t);
		return newpos;
	}
	
	,undotransformation: function(x,y,transformation){ //porting to VismoTransformations?
		return VismoTransformations.undoTransformation(x,y,transformation);
	}	
	,resolveTarget:function(e)
	{
		if(!e) e = window.event;
		var obj;
		
		if(e && e.srcElement){
			obj = e.srcElement;
		}
	        else if(e.target)
        	        obj = e.target;
        	else{
	                obj = false;
	        }
	        try{
                        var x = obj.parentNode;
                }catch(e){return false;}
                /*
		if(obj && obj.nodeType && obj.nodeType == 3) // defeat Safari bug
			obj = obj.parentNode;
			*/
			
			/*try{
                                var x = obj.parentNode;
                        }
                        catch(e){return false;};*/
	        return obj;

		//return obj;
	}
	
	
	,getMouseFromEvent : function(e,target){
			if(!e) e = window.event;
			
			if(!target){
			       
			        var target = this.resolveTargetWithVismo(e);
			        if(!target)return false;
                        }
                        
			var offset = jQuery(target).offset();
               
                        var i;
          
			if(typeof(offset.left) != 'number') return false;
		
		        var scroll = this.scrollXY(e);
			x = e.clientX + scroll.x;
			y = e.clientY + scroll.y;
			//alert(x +"/"+y);
			x -= offset.left;
			y-=  offset.top;
			
			return {'x':x, 'y':y};		
			
	}
	,getMouseFromEventRelativeToTarget : function(e,target){
			if(!e) e = window.event;
			if(!target)return false;

			var offset = jQuery(target).offset();

			
			if(!offset.left) return false;
			var scroll = this.scrollXY();
			x = e.clientX + scroll.x - offset.left;
			y = e.clientY + scroll.y - offset.top;
			return {'x':x, 'y':y};		
			
	}

	,resolveTargetWithVismo: function(e)
	{
		var node = VismoClickingUtils.resolveTarget(e);
                

                
		if(!node)return false;
		var hasVismo = false;
     
                
		while(!hasVismo && node != document && node.parentNode && node.parentNode != document){
		        
		        if(node.vismoCanvas || node.vismoController || node.vismoClicking){
		                hasVismo = true;
			}
			else{
			        node= node.parentNode;
			}
		}
		
		if(!node) return false;
		return node;
	}
	,getMouseFromEventRelativeToElement: function (e,x,y,target){
		if(!e) e = window.event;

		var offset = jQuery(target).offset();
		if(!offset.left) return false;
		
		var scroll = this.scrollXY();
		oldx = e.clientX + scroll.x - offset.left;
		oldy = e.clientY + scroll.y - offset.top;
		var pos = {'x':oldx, 'y':oldy};

		if(!pos) return false;
		pos.x -= x;
		pos.y -= y;
		

		return pos;
		
	}

	,getMouseFromEventRelativeTo: function (e,x,y){
	
		var pos = this.getMouseFromEvent(e);
		if(!pos) return false;
		pos.x -= x;
		pos.y -= y;

		return pos;
	
	}
	,getMouseFromEventRelativeToElementCenter: function(e){ /*redundant?? */
		var w,h;
		var target = this.resolveTargetWithVismo(e);
		if(!target)return;
		if(target.style.width)
			w = parseInt(target.style.width);
		else if(target.width)
			w =parseInt(target.width);

		if(target.style.height)
			h = parseInt(target.style.height);
		else if(target.height)
			h = parseInt(target.height);
	
		if(!w || !h) throw "target has no width or height (vismomaputils)";
	
		return this.getMouseFromEventRelativeTo(e,w/2,h/2);
	}	
	

};

var VismoTransformations= {
	clone: function(transformation){
	
		var t = {};
		t.translate = {x:0,y:0};
		t.scale = {x:1,y:1};

		if(transformation.translate && transformation.translate.x){
			t.translate.x = transformation.translate.x;
			t.translate.y = transformation.translate.y;
		}
		
		if(transformation.scale && transformation.scale.x){
			t.scale.x = transformation.scale.x;
			t.scale.y = transformation.scale.y;		
		}
		
		return t;
	}
	,applyTransformation: function(x,y,t){

		var res= {};
		res.x = x;
		res.y = y;



		if(t.translate){
			res.x +=  t.translate.x;
			res.y += t.translate.y;
		}
		if(t.scale){
			res.x *= t.scale.x;
			res.y *= t.scale.y;
		}

		if(t.origin){
			res.x += t.origin.x;
			res.y += t.origin.y;
		}
		return res;
		
	}
	,mergeTransformations: function(a,b){
		if(!b) return a;
		if(!a) return b;
		
		var result = {};
		var i;
		for(i in a){
			result[i] = a[i];
		}
		
		for(i in b){
			if(result[i]){
				var oldt = result[i];
				var newt = b[i];
				
				result[i].x = oldt.x + newt.x;
				result[i].y = oldt.y + newt.y;
			}
			else{
				result[i] = b[i];
			}
		}
		return result;
	}
	,undoTransformation: function(x,y,transformation){
		var pos = {};
		var t =transformation;
		var tr =t.translate;
		var s = t.scale;
		var o = t.origin;
		if(s ===false || o ===false || tr ===false) return false;
		
		if(x ===false || y ===false)return false;
		pos.x = x - o.x;
		pos.y = y -o.y;
		//pos.x -= x;
		//pos.y += y;
		
		if(pos.x !== 0)
			pos.x /= s.x;
		
		if(pos.y !== 0)
			pos.y /= s.y;
			
		pos.x -= tr.x;
		pos.y -= tr.y;			
		return pos;	
	}
	,getXY: function(e,t){
		var pos =VismoClickingUtils.getMouseFromEvent(e);
		return this.undoTransformation(pos.x,pos.y,t);
	}
	,create: function(options){
	    var transformation= {};
	    var i;
	    for(i in options){
	        transformation[i] = options[i];
	    }
	    var s = transformation.scale;
	    var t = transformation.translate;
	    transformation["cache"] = {id1:[s.x,",",s.y].join(""),id2:[t.x,",",t.y].join("")};
	    
	    return transformation;
	    
	}
};var Vismo = {store:{Canvas:{}}};
var VismoCanvas = function(element,options){
    this._referenceid = Math.random();
    Vismo.store.Canvas[this._referenceid] = this;
    this._lastTransformation = {scale:{}};

    if(element.length){ //for jquery
        var result = [];
        for(var i=0; i < element.length; i++){
            var x = new VismoCanvas(element[i],options);
            result.push(x);
        }
        return x;
    }
    this.className = "VismoCanvas";
    this._idtoshapemap = {};
    if(!options) options = {};
	if(typeof element == 'string') element= document.getElementById(element);
	if(!element) throw "Element doesn't exist!";
	
	var canvaswidth = jQuery(element).width();
	var canvasheight = jQuery(element).height();
	element.style.width = canvaswidth;
	element.style.height = canvasheight;
	if(element.vismoClicking) {
		var update = element.vismoClicking;
		return update;
	}
	if(!options.pointsize){
        options.pointsize = 5;
    }	

	this.options = options;

	var wrapper = element;
	
	this.settings = {};
	this.settings.browser = !VismoUtils.browser.isIE ? 'good' : 'ie'
	this.settings.globalAlpha = 1;
	var canvas;
	var hideoverflow;
	if(this.settings.browser =='good'){
	    canvas = document.createElement('canvas');
	    canvas.className = "VismoCanvasRenderer";
	    hideoverflow = canvas;
	}    
	else
	{
	    hideoverflow = document.createElement("div");
	    canvas = document.createElement('div');
	    canvas.className = "VismoIECanvas VismoCanvasRenderer";
	    
	    canvas.style.setAttribute('cssText', 'position:absolute;left:0px;top:0px;', 0);
	    
	    hideoverflow.appendChild(canvas);
	    
	}
	
	
	//.VismoIECanvas
	var width =parseInt(wrapper.style.width);
	var height =parseInt(wrapper.style.height);
	canvas.width = width;
	canvas.height = height;
	
	this.setTransformation({translate:{x:0,y:0},scale:{x:1,y:1},origin:{x:canvaswidth/2, y:canvasheight/2}});
	if(!element.className)element.className = "VismoCanvas";
	jQuery(canvas).css({width:width, height:height,'z-index':1,position:'absolute'});        
	element.appendChild(hideoverflow);
	jQuery(hideoverflow).css({width:width, height:height,position:"absolute",overflow:"hidden",left:"0px",top:"0px"});
	var labels =  document.createElement("div");
    jQuery(labels).css({position:"absolute","z-index":9});      
    labels.className = "VismoLabels";
    wrapper.appendChild(labels);
    this.labelHolder = labels;
    this.labels = [];
	this.canvas = canvas;

	this.memory = [];
	
	element.vismoClicking = true;//this;//true;//this
    jQuery(this.canvas).mousedown(function(e){e.preventDefault();});

	this.wrapper = wrapper;

	this._setupMouse();

    var vc = this;
	if(options.vismoController){
	    if(!options.vismoController.handler){
	        options.vismoController.handler = function(t){
	            vc.transform(t);
	        }
	    }
	    this.vismoController = new VismoController(this.getDomElement(),options.vismoController);
	}
	
	this.mouse({down:options.mousedown,up:options.mouseup,move:options.move,dblclick:options.dblclick,keypress:options.keypress});
	var tooltipfunction;
	if(options.tooltipfunction){
	    if(typeof options.tooltipfunction == 'boolean'){
	        tooltipfunction = function(el,s){
	            if(s){
	                el.innerHTML = "cool"+s.getProperty("id");}
	            }
	    }
	    else{
	        tooltipfunction = options.tooltipfunction;
	    }
	    this.addTooltip(tooltipfunction)
	}

	if(options.shapes) {
		for(var i=0; i < options.shapes.length; i++){
	        
			this.add(options.shapes[i]);
		
		}
		this.render();
	}
	
	var x = window.onbeforeunload;
	var that = this;

	window.onbeforeunload =function(){
	    that.teardown();
	    x();
    };

};

VismoCanvas.prototype = {
    teardown: function(){
        VismoUtils.scrubNode(this.canvas);
        VismoUtils.scrubNode(this.wrapper);
        VismoUtils.scrubNode(this.labelHolder); 
       jQuery(this.canvas).unbind("mousedown");
       this.wrapper.onmouseout = null;
       this.wrapper.onmouseover = null;
      
        
    }
	,getDomElement: function(args){
		return this.wrapper;
	}
	,addTooltip: function(args){
	    var addContent = arguments[0];
	    var wrapper = this.wrapper;
	        if(addContent) this.tooltipAddContent = addContent;
	        if(!this.tooltip){
	                var tooltip =  document.createElement("div");
                        jQuery(tooltip).css({position:"absolute","z-index":1000,display:"none"});      
                        tooltip.className = "VismoTooltip";
                        
                        jQuery(tooltip).mousedown(function(e){e.preventDefault();if(wrapper && wrapper.onmousedown)wrapper.onmousedown(e);});
                        jQuery(tooltip).mousemove(function(e){e.preventDefault();});
                        jQuery(this.wrapper).parent().append(tooltip);
                        this.tooltip = tooltip;
                        
        		                       
                }
                if(!this.tooltipAdded){
                        var move= this.onmousemove;
                        var that = this;
                        var lastshape;
        		var newmove = function(e,shape){
        		        if(!e) e = window.event;
        		        if(!that.tooltip) return;     
                                jQuery(that.tooltip).html("");
                        
                        if(shape && lastshape != shape){
                                var bb = shape.getBoundingBox();
                           	    //var pos = VismoClickingUtils.getMouseFromEvent(e);
                		        if(that.tooltipAddContent)that.tooltipAddContent(that.tooltip,shape);
                		        var pos = VismoTransformations.applyTransformation(bb.x2,bb.y1,that.getTransformation())
                		        //var pos= {x: bb.center.x, y:bb.center.y};
                		        var w = jQuery(that.wrapper).width();
                		        var h = jQuery(that.wrapper).height();
                		        var off = jQuery(that.wrapper).offset();
                		        if(pos.x > off.left + w) pos.x = off.left + w;
                		        
                		        //jQuery(that.tooltip).css({top:0, right:0});             
                                }
        		        if(that.tooltipAddContent && shape){
        		                that.tooltipAddContent(that.tooltip,shape);
        		                lastshape = shape;
        		                jQuery(that.tooltip).css({display:""});
        		        }
        		        else{
     		                  jQuery(that.tooltip).css({display:"none"});
        		        }     
        		        if(move)move(e,shape);
        		        
        		};
        		this.onmousemove = newmove;
                        this.tooltipAdded = true;
                }
	}
	,getXYWindow: function(args){
	    var e = arguments[0];
	       var t = this.getTransformation();
	       var pos = this.getXY(e);
	       return  VismoTransformations.applyTransformation(pos.x,pos.y,t);
	}
	,getXY: function(args){
	    var e = arguments[0];
		return VismoTransformations.getXY(e,this.getTransformation());
	}
	,mouse: function(args){
	  
	    if(!args){
	        return {up: this.onmouseup, down: this.onmousedown, move: this.onmousemove, dblclick: this.ondblclick,keypress:this.onkeypress};
	    }
	    else{
	        var args = arguments[0];
	        
	        if(args.down)this.onmousedown = args.down;
    		if(args.up)this.onmouseup = args.up;
    		if(args.move)this.onmousemove=  args.move;
    		if(args.dblclick) this.ondblclick = args.dblclick;
    		if(args.keypress) this.onkeypress = args.keypress;

    		//if(this.madeMoveable) this.makeMoveable();
    		//if(this.tooltipAdded) this.addTooltip();	        
	    }
	}

	,_setupMouse: function(args){
		var that = this;
		this.onmousedown = function(e,s,pos){};
		this.onmouseup = function(e,s,pos){};
		this.onmousemove = function(e,s,pos){};
		this.ondblclick = function(e,s,pos){};
		this.onkeypress = function(e){};
	

		this._applyMouseBehaviours(this.wrapper);
		for(var i =0; i < this.wrapper.childNodes.length; i++){
			var child = this.wrapper.childNodes[i];
			//this._applyMouseBehaviours(child);
		}
	
	}
	,_applyMouseBehaviours: function(args){
	    var el = arguments[0];
	    var that = this;
	        
		var newbehaviour = function(e){
				//var t = VismoClickingUtils.resolveTargetWithVismo(e);              
				//if(t && t.getAttribute("class") == 'vismoControl') return false;
				var shape = that.getShapeAtClick(e,el);
				return shape;
			
		};
	    var applymice = function(el){
	        var down = el.onmousedown;
    		var up = el.onmouseup;
    		var mv = el.onmousemove;
    		var dblclick =el.ondblclick;
    		this.initialKeyPress = window.onkeypress;
    		//el.oncontextmenu=function(args) {  return false}; 		
    		el.onmouseover = function(e){

    				if(!that.keypressactive) {

    					that.keypressactive =  true;
    					window.onkeypress =function(e){
    					    that.onkeypress(e);
    					    if(that.initialKeyPress)that.initialKeyPress(e);
    					}
    					document.onkeypress = function(e){if(!e) e= window.event;if(that.initialKeyPress)that.initialKeyPress(e);if(!e) e= window.event;var s = newbehaviour(e); 
    					        if(that.onkeypress)that.onkeypress(e,s)
    					       
    					};
    				}
    		};
    		el.onmouseout = function(e){if(!e) e= window.event;that.keypressactive = false;};
	    
	    
    		jQuery(el).mousedown(function(e){
    		    //console.log("md",el);
    			var s = newbehaviour(e); 
    			if(s){
    				if(s.getProperty("onmousedown")){
    				        s.getProperty("onmousedown")(e,s);	
    				        if(that.onmousedown)that.onmousedown(e,s);

    				}
    				else{
    				    if(that.onmousedown)that.onmousedown(e,s);
    				}
    			}
    			else {
    			    //console.log("ic");
    			        if(that.onmousedown)that.onmousedown(e,s);
    			        if(down)down(e,s);
    			}

    		});

            jQuery(el).dblclick(function(e){
    			if(!e) e= window.event;
    			var s = newbehaviour(e); 				
    			if(s) {

    				if(s.getProperty("ondblclick")){
    				        s.getProperty("ondblclick")(e,s);
    				}
    				else if(that.ondblclick){
            			        that.ondblclick(e,s);
            			}
            			else{


            			}
    			}
    			else {
    				if(that.ondblclick){
            			        that.ondblclick(e,s);
            			}
    				if(dblclick){
    				        dblclick(e,s);
                                    }
    			}
    		});
            jQuery(el).mouseup(function(e){ 
                //console.log("mu",el);
                    var s = newbehaviour(e);
                    if(s){
    		                if(s.getProperty("onmouseup")){
    		                        s.getProperty("onmouseup")(e,s);
    		                        if(that.onmouseup)that.onmouseup(e,s);

    		                }
    		                else{
    		                    if(that.onmouseup)that.onmouseup(e,s);
    		                }


    		        }
    		        else{
    		                if(that.onmouseup)that.onmouseup(e,s);
    		                if(up)up(e,s);
    		        }
    		});
    		var defaultCursor;
    		jQuery(el).mousemove(function(e){ if(!e) e= window.event;var s = newbehaviour(e);

    		        if(!VismoUtils.browser.isIE){
    		                if(jQuery(el).hasClass("overVismoShape")) jQuery(el).removeClass("overVismoShape");
    		        }
    		        if(!VismoUtils.browser.isIE){

    		                if(jQuery(el).hasClass("overVismoPoint"))jQuery(el).removeClass("overVismoPoint");
    		        }

    		        if(s && !s.getProperty("unclickable")){


            		        if(that.ondblclick || that.onmousedown || that.onmouseup) {
            		                var sh;
                    		        if(s){
                    		               sh  = s.getShape();
                    		               if(!VismoUtils.browser.isIE  &&sh == "point") jQuery(el).addClass("overVismoPoint");
                    		        }
            		                if(!VismoUtils.browser.isIE && !jQuery(el).hasClass("panning") && !jQuery(el).hasClass("zooming"))jQuery(el).addClass("overVismoShape");
            	                }

    		                if(s.getProperty("onmousemove"))s.getProperty("onmousemove")(e,s);
    		        }
    		        else{
    		                //el.style.cursor = defaultCursor;
    		        }
    		        if(that.onmousemove)that.onmousemove(e,s); 
    		        if(mv)mv(e,s);
    		});       	

        };
        applymice(el);
		


	}
	,getDimensions: function(args){
		return {width: this.width() , height: this.height()};
	}
	,height: function(){
	    return parseInt(this.canvas.style.height);
	},
	width: function(){
	    return parseInt(this.canvas.style.width);
	}
	,resize: function(args){
		var width = arguments[0]; var height=arguments[1];
		if(this.canvas.getAttribute("width")){
			this.canvas.width = width;
			this.canvas.height = height;
		}
		jQuery(this.hideoverflow).css({height:height,width:width});
		jQuery(this.wrapper).css({height:height,width:width});
		jQuery(this.canvas).css({height:height,width:width});
	}
	,setTransparency: function(args){	
	    var alpha = arguments[0];
		this.settings.globalAlpha = alpha
	}
	,_setupCanvasEnvironment: function(args){
		if(VismoUtils.browser.isIE) return;
		var ctx = this.canvas.getContext('2d');
		var s =this.getTransformation().scale;
		if(s && s.x)ctx.lineWidth = (0.5 / s.x);
		ctx.globalAlpha = this.settings.globalAlpha;
		ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
		ctx.lineJoin = 'round'; //miter or bevel or round	
	}
	,clear: function(args){
	    var deleteMemory = arguments[0];
		if(deleteMemory){
			this.clearMemory();
		}
		this._maxX = 0;
		this._maxY = 0;
        
		
		if(!this.canvas.getContext) {
			return;
		}
		var ctx = this.canvas.getContext('2d');
		ctx.clearRect(0,0,this.canvas.width,this.canvas.height);		
		
	}	
	
	
	,ie_render: function(args){
	    var projection= arguments[0];
	    VismoTimer.start("VismoCanvas.ie_render");
	    //this.render = this.ie_render;
	    var that = this;
		var transformation = this.getTransformation();
		if(this.options.beforeRender) this.options.beforeRender(this);	
		if(transformation.scale.x) sc = transformation.scale.x; else sc = 1;
		
		//determine point size
		var ps = this.options.pointsize / parseFloat(sc);
			
		tran = transformation;
        var o = tran.origin,t = tran.translate, s = tran.scale;
        jQuery(this.canvas).css({left:o.x+(t.x*s.x),top:o.y +(s.y*t.y),zoom:s.x});
        
		var mem =that.memory;
        var firstTime = false;
	    var appendTo;
	    if(that.canvas.childNodes.length == 0){
	        firstTime = true;
	        appendTo  = document.createElement("div");
	    }
	    else{
	        appendTo = that.canvas;
	    }
	    var lastT = this._lastTransformation.scale;
	    var shapes = this._lastTransformation.shapes;
	    if(lastT.x  ===s.x && lastT.y === s.y && this.memory.length == shapes){
	        tran = false; //stop a transformation from being applied we've covered it here
	    }

	    var globalAlpha =that.settings.globalAlpha; 
		for(var i=0; i < mem.length; i++){
            var vs =mem[i];
		    var st = vs.properties.shape
	        //if(vs.optimise(appendTo,transformation,projection)){
		        
			    if(st == 'domElement')tran = transformation;
				vs.render(that.canvas,tran,projection,true,that.settings.browser,ps);        
				if(vs.vmlfill && !vs.vmlfill.opacity && globalAlpha) {
					vs.vmlfill.opacity =globalAlpha;
				}
			
				
			//}
			/*
			var lookahead = function(){
			    var newtransformation = VismoUtils.clone(transformation);
			    newtransformation.scale.x *=2;
			    newtransformation.scale.y *= 2;
			    vs.optimise(appendTo,newtransformation,projection,true);
			};
			window.setTimeout(lookahead,1000);
		    */
		}
	    
		this._lastTransformation = {scale:{x:s.x,y:s.y},shapes:this.memory.length};
		if(firstTime){
		    that.canvas.appendChild(appendTo.cloneNode(true));
		}
		VismoTimer.end("VismoCanvas.ie_render");
	    
        
	}
	,canvas_render: function(args){
	    	    //console.log(this.getDomElement(),this.transformation);
	    var projection = arguments[0];
	    this.render = this.canvas_render;
	    var that = this;
		var transformation = this.getTransformation();
		if(this.options.beforeRender) this.options.beforeRender(this);	
		if(transformation.scale.x) sc = transformation.scale.x; else sc = 1;
		//determine point size
		var ps = this.options.pointsize / parseFloat(sc);
	
			
		
		var appendTo;
	    var mem =that.getMemory();
	    this._setupCanvasEnvironment();
	    var ctx = that.canvas.getContext('2d');
		ctx.save();
		tran = false;

		if(transformation){
			
			var o = transformation.origin;
			var tr = transformation.translate;
			var s = transformation.scale;
			var r = transformation.rotate;
			if(o && s && tr){
				ctx.translate(o.x,o.y);
				ctx.scale(s.x,s.y);
				ctx.translate(tr.x,tr.y);
			}
			if(r && r.x)ctx.rotate(r.x);
		}
	
		appendTo = that.canvas;
		
		for(var i=0; i < mem.length; i++){
		    var st = mem[i].getShape();
	        if(mem[i].optimise(that.canvas,transformation,projection)){
			    if(st == 'domElement')tran = transformation;
				mem[i].render(that.canvas,tran,projection,true,that.settings.browser,ps);        
				if(mem[i].vmlfill && that.settings.globalAlpha) {
					mem[i].vmlfill.opacity =that.settings.globalAlpha;
				}
			}
		}
	    if(ctx)ctx.restore();
	}
	,render: function(args){
	    var projection = arguments[0];

		if(this.settings.browser == 'good'){
            this.canvas_render(projection);
		}
		else{
	        this.ie_render(projection);
		}
			
	}
	,getTransformation: function(args){
		if(!this.transformation) {
		var ox = parseInt(this.canvas.style.width);
		var oy = parseInt(this.canvas.style.height);
		this.transformation = {scale:{x:1,y:1},translate:{x:0,y:0},origin:{x: ox/2, y: oy/2}};
		//this.transformation = VismoTransformation.getBlankTransformation(this.canvas);
		}
		return this.transformation;
	}
	
	,setTransformation: function(args){
	    var transformation = arguments[0];
	        //console.log(transformation.origin.x,transformation.translate.x,transformation.translate.y);
	        if(!transformation.origin){
	                transformation.origin = {};
	                transformation.origin.x = jQuery(this.wrapper).width() / 2;
	                transformation.origin.y = jQuery(this.wrapper).height() / 2;
	        }
	      
		if(transformation) this.transformation = transformation;
		var t = transformation.translate, s = transformation.scale;	
	    transformation.cache = {id1:[s.x,",",s.y].join(""),id2:[t.x,",",t.y].join("")};
	    
	}

    ,centerOn: function(x,y){
        
        var t=  this.getTransformation();
        t.translate.x = -x;
        t.translate.y = -y;
        if(this.vismoController){
            this.vismoController.setTransformation(t);
        }
        else{
            this.setTransformation(t);
        }
        this.render();
    }
	,remove: function(args){
        var vismoShape = arguments[0];
       var shapes = this.getMemory();
       
     
       for(var i=0; i < shapes.length; i++){
            if(shapes[i] == vismoShape){
                this.memory.splice(i,1);
            }
       }
       if(vismoShape.vml)vismoShape.vml.scrub();
       
	    var id = vismoShape.properties.id;
   	    delete this._idtoshapemap[id]
	       
	}
	,add: function(args){
	    var vismoShape = arguments[0];
	    this.needsSort = true;
	    if(!vismoShape._isVismoShape){
	        vismoShape = new VismoShape(vismoShape);
	    
	    }
	    if(vismoShape.properties.shape =='point'){
	        
            vismoShape.setDimensions(this.options.pointsize,this.options.pointsize);
        }
		if(!this.memory) this.memory = [];
		
		vismoShape.vismoCanvas = this;
		if(!vismoShape.getProperty("id")){
		    var newid  = this.memory.length +"_" + Math.random();
		    vismoShape.setProperty("id",newid);
		}
		vismoShape._canvasref = this._referenceid;
		var id = vismoShape.properties.id;
		this.memory.push(vismoShape);
		
		
		this._idtoshapemap[id] = vismoShape;
		vismoShape._vismoClickingID = id;


		return vismoShape;
	}
	,addLabel:function(args){
	    var domElement = arguments[0];
	    var x=  arguments[1];
	    var y = arguments[2];
	        this.labelHolder.appendChild(domElement);
	        var properties = {element: domElement,shape:"domElement"};
	  
	        var coords = [];
	        coords.push(x);
	        coords.push(y);
	        var shape = new VismoShape(properties,coords);
	        this.add(shape);
	              //console.log(shape);
	        return {element: domElement ,vismoshape: shape};
	}
	,transform: function(args){
	    var t = arguments[0];
		this.setTransformation(t);
		this.render();

	}
	,clearMemory: function(args){
		for(var i=0; i < this.memory.length; i++){
			if(this.memory[i].vml){
				this.memory[i].vml.scrub();
			}
		}
		this._idtoshapemap = {};
		this.memory = [];

	},
	getMemory: function(args){
        if(this.needsSort){
          
    	    this.memory =this.memory.sort(function(a,b){
    	        var z1 = a.getProperty("z-index");
    	        var z2 =b.getProperty("z-index");
    	        if(z1 < z2) return -1;
    	        else if(z1 == z2){
    	            return 0;
    	        }
    	        else{
    	            return 1;
    	        }
    	        });
	        this.needsSort = false;
	    }
	        
	    return this.memory;
	}
	,getMemoryID: function(args){
	    var vismoShape = arguments[0];
		if(vismoShape && vismoShape._vismoClickingID)
			return vismoShape._vismoClickingID;
		else{
			return false;
		}
	}
	,getShapeWithID: function(args){
	    var id = arguments[0];
	    var mem = this.getMemory();
	    if(this._idtoshapemap[id]) return this._idtoshapemap[id];
	    else return false;
	}
	,getShapeAtClick: function(args){
	    var e = arguments[0];
	    var el = arguments[1]; //the dom element the behaviour occurred o
		if(!e) {
			e = window.event;
		}
	
		var node = VismoClickingUtils.resolveTarget(e);
		//alert(node.tagName);
		if(node && node.tagName) { //vml vismoShape
		    if(node.tagName.toUpperCase() == 'SHAPE'){
		        if(node._vismoClickingID){
		            
		            var shape = this.getShapeWithID(node._vismoClickingID);
		            if(shape) return shape;
		        }
		        
			}
			
		}

		var target = VismoClickingUtils.resolveTargetWithVismo(e);
	    target =el;
		if(!target) return;
		
		var offset = jQuery(target).offset();

                var xy= VismoClickingUtils.scrollXY();
		x = e.clientX + xy.x - offset.left;
		y = e.clientY + xy.y - offset.top;

		if(this.memory.length > 0){
			var shape = false;
			
			if(target.vismoClicking){
			    var pos =  VismoTransformations.undoTransformation(x,y,this.transformation);
    			x = pos.x;
    			y = pos.y;
			    shape = this.getShapeAtPosition(x,y);
			}
			else{
			    //shape = false;
			}
			return shape;
		} else{
			return false;
		}
	},
	getShapeAtPosition: function(args) {
	    /* x and y should be in VismoShape coordinate world*/
	    var x= arguments[0];
	    var y=  arguments[1];
		var shapes = this.memory;

		var hitShapes = [];
		for(var i=0; i < shapes.length; i++){
			var shape = shapes[i];
			if(!shape.getProperty("unclickable"))
	                {		
	                        var st = shape.getShape();
				var g = shape.getBoundingBox();
			
				if(x >= g.x1 && x <= g.x2 && y >=  g.y1 && y <=g.y2){
					hitShapes.push(shapes[i]);
				}
			}

		}
		
		if(hitShapes.length > 0){
		    
		        var res = this._findNeedleInHaystack(x,y,hitShapes);
			return res;
		
		}
	        else return false;
	
		// var shapesInsideBox = _findShapesInsideBoundingBox(shapes, ..) TODO RENAME
		// var points = _findPointsInsideShapes(..)
		

	},
	_findNeedleInHaystack: function(args){
		var x= arguments[0];
	    var y=  arguments[1];
	    var shapes = arguments[2];
	    var hits = [];
		
		for(var i=0; i < shapes.length; i++){
			var st = shapes[i].getShape();
			var itsahit = false;
			if(st == 'polygon'){
				itsahit = this._inPoly(x,y,shapes[i]);
			}
			else if(st == 'path'){
			    //itsahit = this._onPath(x,y,shapes[i]);
			    itsahit = false; 
			}
			else if(st == 'image'){
				itsahit = true;
			}
			else if(st == 'point' || st == 'circle'){
				itsahit = this._inCircle(x,y,shapes[i]);
			}
			if(itsahit) {
				hits.push(shapes[i]);
			}
			
		}

		if(hits.length == 0){
			return false;
		}
		else if(hits.length == 1) 
			return hits[0];
		else {//the click is in a polygon which is inside another polygon
		    var bestZindex = {s:[],z:0};
		    for(var i=0; i < hits.length; i++){
		        var zin = hits[i].getProperty("z-index"); 
		        if(zin > bestZindex.z){
		            bestZindex.s = [hits[i]];
		            bestZindex.z = zin;
		        }  
		        else if(zin == bestZindex.z){
		            bestZindex.s.push(hits[i]);
		        }
	        }
	        if(bestZindex.s.length == 1) return bestZindex.s[0];
		    
			var g = bestZindex.s[0].getBoundingBox();
			var mindist = Math.min(g.x2 - x,x - g.x1,g.y2 - y,y - g.y1);
			var closerEdge = {id:0, closeness:mindist};
			for(var i=1; i < bestZindex.s.length; i++){
				var g = bestZindex.s[i].getBoundingBox();
				var mindist = Math.min(g.x2 - x,x - g.x1,g.y2 - y,y - g.y1);
			
				if(closerEdge.closeness > mindist) {
					closerEdge.id = i; closerEdge.closeness = mindist;
				}
				
			}
			return bestZindex.s[closerEdge.id];
		
		}

	}
	,_inCircle: function(args){
	    var x= arguments[0];
	    var y=  arguments[1];
	    var vismoShape = arguments[2];
		  var bb = vismoShape.getBoundingBox();
        var transform = vismoShape.getTransformation();

		if(transform){
		        var newpos = VismoTransformations.applyTransformation(x,y,transform);
		        x= newpos.x;
		        y = newpos.y;
	    }
	    
		var a =((x - bb.center.x)*(x - bb.center.x)) + ((y - bb.center.y)*(y - bb.center.y));
		var dim = vismoShape.getDimensions();
		
		var w = dim.width;
		var h = dim.height;
		
		var inCircleOne;
		var inCircleTwo;
		
		if(transform && transform.scale) {
		    w *= transform.scale.x;
		    h *= transform.scale.y;
		}
		w *= w;
		h *=h;
		
		if (a <= w) inCircleOne= true;
		else inCircleOne = false;
		
		if (a <= h) inCircleTwo= true;		
		else inCircleTwo = false;
		

    		//console.log(bb.center.x,bb.center.y,x,y,vismoShape.properties.id,a,w,h,inCircleOne,inCircleTwo);
    		
		if(inCircleOne && inCircleTwo) return true;
		else return false;
	
	}
	,_onPath: function(args){
	    var x= arguments[0];
	    var y=  arguments[1];
	    var vismoShape = arguments[2];
	    return false;
	}
	,_inPoly: function(args) {
	    var x= arguments[0];
	    var y=  arguments[1];
	    var vismoShape = arguments[2];
		/* _inPoly adapted from inpoly.c
		Copyright (c) 1995-1996 Galacticomm, Inc.  Freeware source code.
		http://www.visibone.com/inpoly/inpoly.c.txt */
		var coords;
		coords = vismoShape.getCoordinates();
		var transform = vismoShape.getTransformation();
		
		if(transform){
		        var newpos = VismoTransformations.applyTransformation(x,y,transform);
		        x = newpos.x;
		        y = newpos.y;
		}
		
		var npoints = coords.length;
		if (npoints/2 < 3) {
			//points don't describe a polygon
			return false;
		}
		var inside = false;
		var xold = coords[npoints-2];
		var yold = coords[npoints-1];
		var x1,x2,y1,y2,xnew,ynew;
		for (var i=0; i<npoints; i+=2) {
			xnew=coords[i];
			ynew=coords[i+1];
			if (xnew > xold) {
				x1=xold;
				x2=xnew;
				y1=yold;
				y2=ynew;
			} else {
				x1=xnew;
				x2=xold;
				y1=ynew;
				y2=yold;
			}
			if ((xnew < x) == (x <= xold)
				&& (y-y1)*(x2-x1) < (y2-y1)*(x-x1)) {
				   inside=!inside;
				}
			xold=xnew;
			yold=ynew;
		 }
		 return inside;
	}

    ,isOverlap: function(shape1,shape2){
        return false;
    }


};
var VismoCanvasRenderer = {
	renderShape: function(canvas,vismoShape){
	    var ctx = canvas.getContext('2d');
		var shapetype =vismoShape.properties.shape;
		if(vismoShape.properties["lineWidth"]){
			ctx.lineWidth = vismoShape.getProperty("lineWidth");
		}
		
		ctx.save();
                
		ctx.beginPath();
		if(shapetype == 'point' || shapetype =='circle'){
			this.renderPoint(ctx,vismoShape);
		}
		else if(shapetype =='image'){
			this.renderImage(ctx,vismoShape);
		}
		else if(shapetype == "path"){
            this.renderPath(ctx,vismoShape);
		}
		else{	
			this.renderPath(ctx,vismoShape,true);	
			ctx.closePath();
		        
		}
		
		ctx.strokeStyle = vismoShape.getProperty("stroke")
		if(typeof vismoShape.getProperty("fill") == 'string') 
			fill = vismoShape.getProperty("fill");
		else
			fill = "#ffffff";


		ctx.stroke();
		if(shapetype != 'path') {
			ctx.fillStyle = fill;
			ctx.fill();
		}
	        ctx.restore();
                
                
	        
	}
	,renderPath: function(ctx,vismoShape,join){
		var move = true,quadraticCurve = false,bezierCurve = false;
		var c = vismoShape.getCoordinates();
		var t =vismoShape.getProperty("transformation");
		if(!t) t= {};
		//ctx.save(); //issue with this in safari..
		if(!t.translate)t.translate = {x:0,y:0};
		if(!t.scale) t.scale = {x:1,y:1};
		    

		//ctx.scale(t.scale.x,t.scale.y);
		if(!t.translate.y) t.translate.y = 0;
		if(!t.translate.x) t.translate.x = 0;
		if(!t.scale.x) t.scale.x = 1;
		if(!t.scale.y) t.scale.y = 1;

		var bb = vismoShape.grid;
		if(bb.center){
		    ctx.translate(bb.center.x-(bb.center.x*t.scale.x),bb.center.y-(bb.center.y*t.scale.y));
            ctx.scale(t.scale.x,t.scale.y);	
            ctx.translate(t.translate.x,t.translate.y);
        }
		var bb = vismoShape.grid;
		for(var i=0; i < c.length-1; i+=2){
            var isCoord =VismoShapeUtils._isCoordinate(c[i]);
			if(!isCoord){

				if(c[i] == "M"){
				    move=true;
			    }
			    else if(c[i] == "q"){
			        quadraticCurve = true;
			    }
			    else if(c[i] == "c"){
			        bezierCurve = true;
			    }
			    i+=1;
			}
			var x = parseFloat(c[i]);
			var y = parseFloat(c[i+1]);	
			
			if(move){ 
				ctx.moveTo(x,y);
			
				move = false;
			}
			else if(quadraticCurve){
			    var x2 = parseFloat(c[i+2]);
			    var y2 = parseFloat(c[i+3]);

			    i+= 2;
			    ctx.quadraticCurveTo(x,y,x2,y2);
			}
			else if(bezierCurve){
			    var x2 = parseFloat(c[i+2]);
			    var y2 = parseFloat(c[i+3]);
                var x3 = parseFloat(c[i+4]);
                var y3 = parseFloat(c[i+5]);
			    i+= 4;
			    ctx.bezierCurveTo(x,y,x2,y2,x3,y3);			    
			}
			else{
			       
				ctx.lineTo(x,y);
			}			
				
				
		}
	
		//ctx.restore(); //issue with this in safari..
	}
	,renderPoint: function(ctx,vismoShape){
	        //ctx.restore();
		//ctx.save();
		var bb =vismoShape.getBoundingBox();
		var dim =vismoShape.getDimensions();
		var radiusx = dim.width / 2;
		var radiusy = dim.height/2;
		
		var transform = vismoShape.getTransformation();
		if(transform && transform.scale) radiusx*= transform.scale.x;
		//ctx.save();
		if(radiusx > radiusy) {
		    //ctx.scale(radiusx/radiusy,1)
		}
		else if(radiusy > radiusx){
		    //
		    //ctx.scale(1,radiusy/radiusx)
		    //ctx.restore();
		}
		ctx.arc(bb.center.x, bb.center.y, radiusx, 0, Math.PI*2,true);
	    
	}
	,renderImage: function(ctx,vismoShape){
		var c = vismoShape.getCoordinates();
		var bb = vismoShape.getBoundingBox();
		var draw = function(){
		        if(vismoShape.ready)ctx.drawImage(vismoShape.image,bb.x1,bb.y1,bb.width,bb.height);
		        else window.setTimeout(draw,100);
		};
                draw();

	}
};


var VismoGraph = function(properties){
    this._nodes = {};
    this._children = {};
    this._parents = {};
    this._orphans = {};
    this._spouses = {};
	if(properties.nodes){
    	for(var i=0; i < properties.nodes.length; i++){
    	    this.addNode(properties.nodes[i]);
    	}
	}
	if(properties.edges){
	    var edges = properties.edges;
	    for(var i=0; i < edges.length; i++){
	        var a = edges[i][0];
	        var b = edges[i][1]; 
    	    this.addEdge(a,b);
    	}
	}
};

VismoGraph.prototype = {
    getNode: function(id){
        return this._nodes[id];
    }
    ,depth: function(id,depthsofar){
       if(!depthsofar && depthsofar !== 0)depthsofar =0;
       var kids = this.getChildren(id);
       if(kids.length == 0) return depthsofar;
       
       var maxdepth = 0;
       for(var i=0; i < kids.length;i++){
           var depth = this.depth(kids[i],depthsofar+1)
           if(depth > maxdepth) maxdepth = depth;
       }
       return maxdepth;
    }
    /* a spouse shares the same children as another node*/
    ,isSpouse: function(id1,id2){
        if(id1 == id2) return false;
        var childrenX = this.getChildren(id1);
        var childrenY = this.getChildren(id2);
        var allchildren = childrenX.concat(childrenY);
        for(var i=0; i < allchildren.length; i++){
            // if the child also has y as a parent..
            var child = allchildren[0];
            if(this._parents[child].indexOf(id2) != -1 && this._parents[child].indexOf(id1) != -1) return true;
        }
        return false;
    }
    ,getSpouses: function(id){
        var n = this.getNodes();
        var spouses = [];
        for(var i=0; i < n.length;i++){
            
            if(this.isSpouse(id,n[i].id)){
                spouses.push(n[i].id);
            }
        }
        return spouses;
    }
    ,getNodes: function(){
        var nodes = [];
        for(var i in this._nodes){
            nodes.push(this._nodes[i]);
        }
        return nodes;
    }
    ,getChildren: function(id){
        if(typeof(id) != 'string'){
	        var done = {};
	        var allchildren = [];
	        for(var i=0; i < id.length;i++){
	            var parentid = id[i];
	            var children = this.getChildren(parentid);
	            for(var j=0; j < children.length;j++){
	                var childid = children[j];
	                if(!done[childid]){
	                    allchildren.push(childid);
	                    done[childid] = true;
	                }
	            }
	        }
	        return allchildren;
	        
	        
	    }
	    
        var children = this._children[id];

        if(!children){
            return [];
        }
        else {
            return children;
        }
    }
    ,isOrphan: function(id){
        if(!this._parents[id] || this._parents[id].length == 0){
            return true;
        }
        else{
            return false;
        }
    }
    ,getParents: function(id){
        var p = this._parents[id];

        if(!p){
            return [];
        }
        else {
            return p;
        }
    }
    ,getOrphans: function(){ 
        var orphans = [];
       var nodes = this.getNodes();
       for(var i=0; i < nodes.length; i++){
           var id = nodes[i].id;
           if(this.isOrphan(id)){
               orphans.push(id);
            }
        }
    
        return orphans;
    } 
    ,addNode: function(nodejson){
        var id = nodejson.id;
        if(!nodejson.properties){
            nodejson.properties = {};
        }
        this._nodes[id] = nodejson;
        this._orphans[id] = true;
    }
    ,addEdge: function(a,b){
        //not working properly with new lines
        a = a.replace(/\n/,"");
        b= b.replace(/\n/,"");
        
        if(!a || !b ||(a && a.length == 0) || (b && b.length==0)) {
        
            return;
        
        }
        if(!this._children[a]) this._children[a] = [];
        if(!this._parents[b]) this._parents[b] = [];
        
        this._children[a].push(b);
        this._parents[b].push(a);
        
        if(!this._orphans[a])this._orphans[a] = true;
        this._orphans[b] = false;
        
    }
};

var VismoGraphRenderer = function(place,options){
    if(!options.algorithm){
        throw "GraphRenderer requires an option called algorithm which is a function. This will take two parameters graph and root and should set XPosition and YPosition on every node.";
    }
    if(!options.lineColor){
        options.lineColor = "rgb(0,0,0)";
    }
    if(!options.defaultNodeColor){
        options.defaultNodeColor = "#ffffff";
    }
    if(!options.lineWidth){
        options.lineWidth = "2";
    }
    
    this.algorithm = options.algorithm; 
    if(!options.nodeWidth) options.nodeWidth= 5;
    if(!options.nodeHeight) options.nodeHeight = 5; 
    
    this.options = options;
    this._edgeShapeCoordinates = [];
    this._graph = options.graph;
    
    var canvasopts;
    if(!options.vismoCanvas) canvasopts = {};
    else canvasopts = options.vismoCanvas;
    
    if(!options.vismoController){
        canvasopts.vismoController = {};
    } 
    else{
        canvasopts.vismoController = options.vismoController;
    }
    if(options.move)canvasopts.move = options.move;
    if(options.dblclick)canvasopts.dblclick = options.dblclick;
    this._canvas = new VismoCanvas(place,canvasopts);

    if(options.root){
        this.compute(options.root);  
    }
     
};

VismoGraphRenderer.prototype = {
    clear: function(){
        this._canvas.clear(true);
        this._edgeShapeCoordinates = [];
    }

    ,compute: function(root){
        var graph = this._graph;
        if(this.options.root != root) this.clear();
        if(root)this.options.root = root;
        this.algorithm.compute(graph,this.options);
        
        this.plot(root);
        
        if(this._edgeShapeCoordinates.length > 0){
            var edge = new VismoShape({"z-index":"-1",shape:"path",stroke:this.options.lineColor,lineWidth:this.options.lineWidth,coordinates:this._edgeShapeCoordinates});
            this._canvas.add(edge);
        }
        this._canvas.render();

        var node = graph.getNode(root);
        var half_height = this._canvas.height() /2;
        this._canvas.centerOn(node.XPosition,node.YPosition + half_height);

    }
    ,plot: function(id){
        var node = this._graph.getNode(id);
        var y = -node.YPosition;
        var x = node.XPosition;
        this.plotNode(id,{x:x,y:y});
        var children = this._graph.getChildren(id);
        for(var i=0; i < children.length; i++){
            var parentpos = {x:x,y:y};
            var ch =children[i];
            var childxy = this.plot(ch);
            if(parentpos && childxy){
                
                this._edgeShapeCoordinates=this._edgeShapeCoordinates.concat(["M",parentpos.x,parentpos.y,"q",childxy.x,parentpos.y,childxy.x,childxy.y]);
            }
        }
        return {x: x,y:y};
    }
    
    ,plotNode: function(id,pos){
        var exists = this._canvas.getShapeWithID(id);
        if(!exists){
            var st,coords;
            st= "polygon";
            var hr = this.options.nodeWidth /2;
            var vr=this.options.nodeHeight /2;
            coords = [pos.x-hr,pos.y-vr,pos.x+hr,pos.y-vr,pos.x+hr,pos.y+vr,pos.x-hr,pos.y+vr];
            
            var node= this._graph.getNode(id);
            node.properties.shape = st;
            node.properties.coordinates = coords;
            if(!node.properties.fill)node.properties.fill = this.options.defaultNodeColor;
            var shape= new VismoShape(node.properties);
            this._canvas.add(shape);          
        }
        else{
            var b = exists.getBoundingBox();
            pos = b.center;
        } 
        return pos;
        
    }

 };var VismoVector = function(vismoShape,canvas){
	
  VismoTimer.start("VismoVector.init");
	this._iemultiplier = 10; //since vml doesn't accept floats you have to define the precision of your points 100 means you can get float coordinates 0.01 and 0.04 but not 0.015 and 0.042 etc..
	this.vismoShape=  vismoShape;

	this.cache = {};
	this.maxResolution_id_x = 1;
	this._oldproperties = {};
	this.initShape(vismoShape,canvas);
    
    
	vismoShape.vml = this;
	VismoTimer.end("VismoVector.init");		
};

VismoVector.prototype = {
	scrub: function(){
	     VismoTimer.start("VismoVector.scrub");
	     if(this.el){
	    this.el.parentNode.removeChild(this.el);
	    this.el = false;
	    }
	    VismoTimer.end("VismoVector.scrub");
	}
	,initShape: function(vismoShape,canvas){
	    VismoTimer.start("VismoVector.initShape");
	    this.coordinatesHaveChanged();
	    this.el = false;
	    var isVML;
    	var shapetype =vismoShape.properties.shape;       
        this.initialshapetype= shapetype;
        
		if(shapetype == 'point' || shapetype == 'circle'){
    		this._initArc(vismoShape,canvas);
    		isVML = false;
    	}
    	else if(shapetype == 'image'){
    		this._initImage(vismoShape,canvas);
    	}
    	else if(shapetype == 'domElement'){
    	        //this.haveAppended = true;
    	        this.el = vismoShape.getProperty("element");
    	        this.el.style.position = "absolute";
    	        var el = this.el;
    	   
    	        
    	        return;
    	}
    	else{
    		this._initPoly(vismoShape,canvas);
    		isVML = true;
    	}
    	if(isVML && canvas){
    	    var w,h;
    	    if(!canvas){
    	        throw " i need a canvas to do my magic!";
    	    }
    	    if(canvas.width){
    	        w= canvas.width;
    	    } 
    	    else{
    	        w = jQuery(canvas).width();
    	        canvas.width = w;
    	    }
    	    if(canvas.height){
    	        h= canvas.height;
    	    } 
    	    else{
    	        h = jQuery(canvas).height();
    	        canvas.height= h;
    	    }
            
    	    
            	var xspace = parseInt(w);
            	xspace *=this._iemultiplier;
            	var yspace =parseInt(h);
            	yspace *= this._iemultiplier;
            	coordsize = xspace +"," + yspace;
            	this.el.coordsize = coordsize;
    	}
            if(this.vismoShape && this.el){
                //this.el.vismoShape = this.vismoShape;
    	        var nclass= "vismoShape";			
    	        if(shapetype == 'path'){ nclass= "vismoShapePath";}
    	        this.el.setAttribute("class", nclass);
    	        this.style();
    	}
    	var that= this;
	    //jQuery(window).bind("unload", function(){that.el= null;});
		 VismoTimer.end("VismoVector.initShape");
	}
	,_initImage: function(vismoShape,canvas){

		var that = this;
		var dim = vismoShape.getDimensions();
		var setup = function(){
			var shape = document.createElement("img");
			
			that.el = shape;
			shape.src = vismoShape.getProperty("src");	
			
			jQuery(shape).css({"height": dim.height, "width": dim.width,"position":"absolute","z-index":4});		

		};

		var image = new Image();
		image.src = vismoShape.getProperty("src");
		image.onload = function(e){
			setup();
		};
		if(image.complete){
			setup();
		}
		
	}
	,_initArc: function(vismoShape,canvas){
		var shape = document.createElement("vismoShapeVml_:arc");
		shape.startAngle = 0;
		shape.endAngle = 360;
		var bb = vismoShape.getBoundingBox();
		this.el = shape;	
		var diameterx = bb.width;
		var radiusx = bb.width/ 2;
		var diametery =  bb.height;
		var radiusy= bb.height/  2;
		
		jQuery(this.el).css({"height": diametery, left:bb.center.x-radiusx, top: bb.center.y-radiusy,"width":diametery,"position":"absolute","z-index":4});			
	}
	,_initPoly: function(vismoShape,canvas){
		VismoTimer.start("VismoVector._initPoly");
		var shape = document.createElement("vismoShapeVml_:shape");
		
		this.el = shape;
		this.el.name=vismoShape.properties.name;
		//var css = jQuery(canvas).css();
		var w =canvas.width;// css.width;
		var h = canvas.height;//css.height;

		
		jQuery(this.el).css({"height": h,"width": w,"position":"absolute","z-index":4});
		
		VismoTimer.end("VismoVector._initPoly");
	}
	,getVMLElement: function(){
		return this.el;
	}
	,_createvmlpathstring: function(transformation,projection){ //mr bottleneck
	    VismoTimer.start("VismoVector.createvmlpathstring");
		var vml = this.el;
		var o,t,s;
		if(transformation){
		    o = transformation.origin;
		    t = transformation.translate;
		    s = transformation.scale;
		}
		else{
		    o = {x:0,y:0};
		    t = {x:0,y:0};
		    s = {x:1,y:1};
		}
		var cindex;
		if(!s || (!s.x && !s.y)){
		    cindex = "1,1";
		}else{
		     cindex= s.x+","+s.y;
		}
		
		if(!this.cache) {this.cache = {};}
	    if(!this.cache[cindex]){ this.cache[cindex] = {};}
	
		if(!this.cache[cindex]["pathstring"]){
		    var path;
		    var buffer = [];
		    var c;
		    if(this.vismoShape.coordinates.normal){
		        c = this.vismoShape.coordinates.normal;
    		}
    		else{
    		    c =this.vismoShape.getCoordinates("normal");
	        }
	 
    		if(projection){
    			c = this.vismoShape._applyProjection(projection,transformation);
    		}
		
    		if(c.length < 2) return;

    		var x,y;
    		var startAtIndex = 0;
    		if(this.vismoShape.isCommand(c[0])){
    		    startAtIndex = 1;
    		}
    		x = c[startAtIndex];
    		y =c[startAtIndex+1];

    				
    		x *=this._iemultiplier;
    		y *= this._iemultiplier;
    		x = parseInt(x);
    		y = parseInt(y);
 
    		//path = "M";
    		buffer.push("M");
    		//path+= x + "," +y + " L";
    		buffer.push([x,",",y].join(""))
    		var lineTo = false,quadraticCurveTo = false,bezierCurveTo = false;
    		for(var i =startAtIndex+2; i < c.length; i+=2){
    		    
    			if(c[i] == 'M') {
    				//path += " M";
    				buffer.push(" M");
    				lineTo = false;
    				i+=1;
    			}
    			else if(c[i] == 'z'){
    			    buffer.push(" XE");
    			}
    			else if(c[i] == "q"){
    			    quadraticCurveTo = true;
    			    i += 1;
    			}
    			else if(c[i] == "c"){
    			    bezierCurveTo = true;
    			    i+=1;
    			}
    			else if(!lineTo) {
    				//path += " L";
    				buffer.push(" L");
    				lineTo = true;
    			}
    			else if(lineTo){
    				//path += " ";
    				buffer.push(" ");
    			}
    			var x =parseInt(c[i] * this._iemultiplier);
    			var y =parseInt(c[i+1] * this._iemultiplier);

			
    			if(quadraticCurveTo){
    			    var x2 =parseInt(c[i+2] * this._iemultiplier);
        			var y2 =parseInt(c[i+3] * this._iemultiplier);
    			    buffer.push([" c ",x,",",y,",",x2,",",y2,",",x2,",",y2,""].join(""));
    			    i += 2;
    			    quadraticCurveTo = false;
    			}
    			else if(bezierCurveTo){
    			    var x2 =parseInt(c[i+2] * this._iemultiplier);
        			var y2 =parseInt(c[i+3] * this._iemultiplier);
        			var x3 = parseInt(c[i+4] * this._iemultiplier);
        			var y3 = parseInt(c[i+5] * this._iemultiplier);
    			    buffer.push([" c ",x,",",y,",",x2,",",y2,",",x3,",",y3,""].join(""));
    			    i += 4;
    			    bezierCurveTo = false;
    			}
    			else{
    			    buffer.push([x,",",y].join(""));
    			}
    			//path += x +"," + y;
			
    			//if(i < c.length - 2) path += "";
		    }
        
		    if(this.vismoShapeProperties.shape != "path"){buffer.push(" XE");}
		    this.cache[cindex]["pathstring"] = buffer.join("");
		//console.log(buffer.join(""));
	    }
        
	
	
        VismoTimer.end("VismoVector.createvmlpathstring");
		return this.cache[cindex]["pathstring"];
	
	}

	,transformDomElement: function(transformation,projection){
	    VismoTimer.start("VismoVector.transformDomElement");
		/*var o = transformation.origin, t = transformation.translate,s = transformation.scale;
		*/
		var shape = this.vismoShape;
		var el = this.el;
		var top,left,width,height;
		var bb = shape.getBoundingBox();
		dx = bb.x1;
		dy = bb.y1;
        jQuery(this.el).css({left:dx,top:dy});
        VismoTimer.end("VismoVector.transformDomElement");
	}
	
	,coordinatesHaveChanged: function(){
	    this.coordinatesChanged = true;
	
	}
	
	,_cacheStyle: function(t,s,o){
	    VismoTimer.start("VismoVector._cacheStyle");
	    var vml = this.el;
		if(!this.initialStyle) { //remember original placement
			var initTop = parseInt(vml.style.top);
			if(!initTop) initTop = 0;
			var initLeft = parseInt(vml.style.left);
			if(!initLeft) initLeft = 0;
			var w =parseInt(vml.style.width);
			var h = parseInt(vml.style.height)
			this.initialStyle = {width: w, height: h};
		}
		var initialStyle= this.initialStyle;

		var newwidth = initialStyle.width * s.x;
		var newheight = initialStyle.height * s.y; 	
			
 
		 VismoTimer.end("VismoVector._cacheStyle");
		return { width:newwidth+"px",height:newheight+"px"};
	}
	,_cssTransform: function(transformation,projection){
	   
		VismoTimer.start("VismoVector._cssTransform");
	
		var vml = this.el;
		var st = this.vismoShapeProperties.shape;
	
		if(st == 'circle' || st == 'img' || st == 'domElement'){
		   
			this.transformDomElement(transformation,projection);
			VismoTimer.end("VismoVector._cssTransform");
			return;
		}
		if(!transformation) return;
		var ckey_1, ckey_2;
		if(transformation.cache){
		    ckey_1 = transformation.cache.id1;
		    ckey_2 = transformation.cache.id2;
		}
		else{
		    ckey_1 = "1,1";
		    ckey_2 = "0,0";
		}
		if(!this.cache[ckey_1]) this.cache[ckey_1] = {};

	
        var s =  transformation.scale;
		if(!this.cache[ckey_1][ckey_2]){
		    var o = transformation.origin, t = transformation.translate;
			this.cache[ckey_1][ckey_2] = this._cacheStyle(t,s,o);
		}
	    var style = this.cache[ckey_1][ckey_2];
	    //jQuery(this.el).css(style); //jon
		VismoTimer.end("VismoVector._cssTransform");
	}
	,clear: function(){
			VismoTimer.start("VismoVector.clear");
			var el = this.el;
			
			try{
			        if(el)jQuery(el).css({display:"none"});
			}catch(e){
			};
			VismoTimer.end("VismoVector.clear");
	}
	,render: function(canvas,transformation,projection){
	    VismoTimer.start("VismoVector.render");
        var that = this;
        var shape = this.el;
        this.vismoShapeProperties = this.vismoShape.properties;
        if(!shape){ //try again later
                var f= function(){
                        that.render(canvas,transformation);
                }
                window.setTimeout(f,50);
                return;
        }
        if(!this.haveAppended){ //append element to dom
		    shape._vismoClickingID = this.vismoShapeProperties.id;
		}
	
		if(this.coordinatesChanged) {
		    this._cssTransform(transformation,projection);
		    
			shape.path = this._createvmlpathstring(transformation,projection);//causes slow down..	
			
            
			this.coordinatesChanged = false;
			
		}
		
		
			
		var shtype= this.vismoShapeProperties.shape;
		if(this.initialshapetype != shtype){ //shape type has changed force restart
		   this.scrub();
		   this.initShape(this.vismoShape,canvas);
		   this.haveAppended = false;
		}
		if(shtype!="domElement")shape.style.display = "";
		
		if(!this.haveAppended){ //append element to dom
		    if(transformation)this._cssTransform(transformation,projection);
			canvas.appendChild(shape);
			if(shtype == 'domElement'){
    			var vismoShape = this.vismoShape;
                var c = vismoShape.getCoordinates();
                var rw = jQuery(el).width()/2;
                var rh = jQuery(el).height()/2;
          
                jQuery(el).css({position:"absolute",left:c[0],top:c[1]-rh});            	     
			}
			this.haveAppended = true;
		}
		this.style();
        VismoTimer.end("VismoVector.render");
	}
	,style: function(){
        
        VismoTimer.start("VismoVector.style");
        if(!this.vismoShapeProperties){
             this.vismoShapeProperties = this.vismoShape.properties;
         }
        if(this.vismoShapeProperties.hidden){
            jQuery(this.el).css({display:"none"});
        }
         if(this.nochange){
	       
	     	VismoTimer.end("VismoVector.style");
	        return;
	    }
	     jQuery("#log").append("Exiting");
	     this.nochange = true;
	    //if(this.el.className =='label')alert("!");
        
        
 

	    if(this.el.style.display == 'none') this.el.style.display =""
	    
	    
		var shapetype = this.vismoShapeProperties.shape;

		var shape = this.el;
		shape.stroked = "t";

		
		if(this.vismoShapeProperties["z-index"]){
		    shape.style.zIndex = this.vismoShapeProperties["z-index"];
		}
		if(this.vismoShapeProperties.lineWidth) {
			shape.strokeweight =this.vismoShapeProperties.lineWidth + "em";
		}
		else {
			shape.strokeweight = "1em";
		}
	
	
	    var strokergba = this.vismoShapeProperties.stroke;
        if(strokergba.indexOf("#") == 0 || strokergba.indexOf("rgb(") == 0){
		            shape.strokecolor = strokergba;
				}
				else{
		    		if(!this.vmlstroke){
    					this.vmlstroke =document.createElement("vismoShapeVml_:stroke");
    					shape.appendChild(this.vmlstroke); 
    				}
				
            		if(strokergba){
            		    var stroke;
            		    if(strokergba.indexOf("rgba") != -1 &&strokergba.match(/rgba\([0-9]*,[0-9]*,[0-9]*,(.*)\)/)){
            		        var match =strokergba.match(/(rgb)a(\([0-9]*,[0-9]*,[0-9]*),(.*)\)/);

        					if(match[3]){
        						stroke = match[1] + match[2] +")";
        						this.vmlstroke.opacity = match[3];
        					}
            		    }
            		    else{
            		        stroke = strokergba;
            		    }
            		    this.vmlstroke.color = stroke;
            		}
            		else{
            		    this.vmlstroke.color = "rgb(0,0,0)";
            		}
    		    }
    		    	
		if(!this.vismoShapeProperties["fill"] || shapetype == 'path'){
		    shape.filled = "f";
                    VismoTimer.end("VismoVector.style");
					return;
		}
	
		
		var fill = this.vismoShapeProperties["fill"];
		shape.filled = "t";
		if(fill.indexOf("#") == 0 || fill.indexOf("rgb(") == 0){
	        shape.fillcolor = this.vismoShapeProperties.fill;
	    
	    }
	    else{
	        if(!this.vmlfill && shape){
				this.vmlfill =document.createElement("vismoShapeVml_:fill");
				shape.appendChild(this.vmlfill); 
		    }	
			//look for rgba fill for transparency
			if(fill.indexOf("rgba") != -1 &&fill.match(/rgba\([0-9]*,[0-9]*,[0-9]*,(.*)\)/)){

				var match =fill.match(/(rgb)a(\([0-9]*,[0-9]*,[0-9]*),(.*)\)/);

				if(match[3]){
					fill = match[1] + match[2] +")";
					this.vmlfill.opacity = match[3];
				}
			}
			this.vmlfill.color = fill;
			
	        
	    }
	    this._oldproperties = VismoUtils.clone(this.vismoShapeProperties);
		VismoTimer.end("VismoVector.style");
		this.nochange = true;
	}

};


var VismoTimer = {
    startsAt:{},
    timed: {},
    clear: function(){
     
     var i;
     for(i in this.timed){
         this.timed[i] = 0;
     }   
    }
    ,start: function(id){
        if(!this.timed[id]) this.timed[id] = 0;
        this.startsAt[id] = new Date();
    },
    end: function(id){
        var d = new Date();
        this.timed[id] += (d-this.startsAt[id]);
    },
    summarise: function(selector){
        var text ="";
        for(i in this.timed){
             text += i +": " + this.timed[i] .toString() +"\n";
               
        }
        jQuery(selector).val(text);
    }
    ,blankf: function(){}
};
VismoTimer.start = VismoTimer.blankf;
VismoTimer.end = VismoTimer.blankf;



m. Elizabeth MEDCALFE (-1589)
m2. Catherine WONTON (-1596)

William had 4 daughters (all died young under age of 10) and 6 other sons






LEased farm called Denshaw with father from Roche Abbey.
	Living 1526.
	Paid rent for one eight of bakestone mine at Delph.
	Possibly had heirs since his interest in the bakestone mine does not appear to have reverted to his father.
In 1861 census he is no longer living with his parents. In the 1851 cenus he was.

	May have been born Mar 1845 in Middlesbrough, Stockton T registree - 
	LINK: http://www.middlesbrough-indexes.co.uk/contact.php?type=births&ref=M-V-006-0-0126&last_name=ROBSON&first_name=WILLIAM&initial=I&year=1845
	
From a letter sent by Joseph Jackson (probably his son) it seems they set sail for America 8 of October 1849, arriving in November?

	May 3rd 1852 William writes from Jamesville, America (just outside New York) to his brother. He mentions the sale of the house and it seems like the recipient of the letter lives near his mother as he is capable of helping the situation. He says "We are sorry to hear of your brother Matthew being sick and Elizabeth also but I hope they will soon recover." so he is not writing to Matthew. This suggests he has written to his brother Adam, as his brother Robert is in Cuba.

	He married a French woman sometime before 1824, as a letter written by Robert talks about it. This may have caused shame to the family as as much as 10 years later in a later letter Robert is still asking to send a letter to William.




Married at All Saints, Newcastle Upon Tyne, Northumberland, England.
	Died 5.30pm on 4th April 1826 aged 38.
	She was buried at St. Edmunds Burying Ground, Gateshead, letter F No. 6.

/***
|''Name:''|YourSearchPlugin|
|''Version:''|2.1.0 (2006-10-12)|
|''Source:''|http://tiddlywiki.abego-software.de/#YourSearchPlugin ([[del.icio.us|http://del.icio.us/post?url=http://tiddlywiki.abego-software.de/index.html%23YourSearchPlugin]])|
|''Author:''|UdoBorkowski (ub [at] abego-software [dot] de)|
|''Licence:''|[[BSD open source license (abego Software)|http://www.abego-software.de/legal/apl-v10.html]]|
|''Copyright:''|&copy; 2005-2006 [[abego Software|http://www.abego-software.de]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 1.0.4+; Firefox 1.5; ~InternetExplorer 6.0|
!About YourSearch
YourSearch gives you a bunch of new features to simplify and speed up your daily searches in TiddlyWiki. It seamlessly integrates into the standard TiddlyWiki search: just start typing into the 'search' field and explore!

For more information see [[Help|YourSearch Help]].
!Compatibility
This plugin requires TiddlyWiki 2.1. 
Check the [[archive|http://tiddlywiki.abego-software.de/archive]] for ~YourSearchPlugins supporting older versions of TiddlyWiki.
!Source Code
***/
/***
This plugin's source code is compressed (and hidden). Use this [[link|http://tiddlywiki.abego-software.de/archive/YourSearchPlugin/Plugin-YourSearch-src.2.1.0.js]] to get the readable source code.
***/
///%
if(!version.extensions.YourSearchPlugin){version.extensions.YourSearchPlugin={major:2,minor:1,revision:0,source:"http://tiddlywiki.abego-software.de/#YourSearchPlugin",licence:"[[BSD open source license (abego Software)|http://www.abego-software.de/legal/apl-v10.html]]",copyright:"Copyright (c) abego Software GmbH, 2005-2006 (www.abego-software.de)"};if(!window.abego){window.abego={};}if(!Array.forEach){Array.forEach=function(_1,_2,_3){for(var i=0,len=_1.length;i<len;i++){_2.call(_3,_1[i],i,_1);}};Array.prototype.forEach=function(_5,_6){for(var i=0,len=this.length;i<len;i++){_5.call(_6,this[i],i,this);}};}abego.toInt=function(s,_9){if(!s){return _9;}var n=parseInt(s);return (n==NaN)?_9:n;};abego.createEllipsis=function(_b){var e=createTiddlyElement(_b,"span");e.innerHTML="&hellip;";};abego.shallowCopy=function(_d){if(!_d){return _d;}var _e={};for(var n in _d){_e[n]=_d[n];}return _e;};abego.copyOptions=function(_10){return !_10?{}:abego.shallowCopy(_10);};abego.countStrings=function(_11,s){if(!s){return 0;}var len=s.length;var n=0;var _15=0;while(1){var i=_11.indexOf(s,_15);if(i<0){return n;}n++;_15=i+len;}return n;};abego.getBracedText=function(_17,_18,_19){if(!_18){_18=0;}var re=/\{([^\}]*)\}/gm;re.lastIndex=_18;var m=re.exec(_17);if(m){var s=m[1];var _1d=abego.countStrings(s,"{");if(!_1d){if(_19){_19.lastIndex=re.lastIndex;}return s;}var len=_17.length;for(var i=re.lastIndex;i<len&&_1d;i++){var c=_17.charAt(i);if(c=="{"){_1d++;}else{if(c=="}"){_1d--;}}}if(!_1d){if(_19){_19.lastIndex=i-1;}return _17.substring(m.index+1,i-1);}}};abego.select=function(_21,_22,_23,_24){if(!_24){_24=[];}_21.forEach(function(t){if(_22.call(_23,t)){_24.push(t);}});return _24;};abego.TiddlerFilterTerm=function(_26,_27){if(!_27){_27={};}var _28=_26;if(!_27.textIsRegExp){_28=_26.escapeRegExp();if(_27.fullWordMatch){_28="\\b"+_28+"\\b";}}var _29=new RegExp(_28,"m"+(_27.caseSensitive?"":"i"));this.tester=new abego.MultiFieldRegExpTester(_29,_27.fields,_27.withExtendedFields);};abego.TiddlerFilterTerm.prototype.test=function(_2a){return this.tester.test(_2a);};abego.parseNewTiddlerCommandLine=function(s){var m=/(.*?)\.(?:\s+|$)([^#]*)(#.*)?/.exec(s);if(!m){m=/([^#]*)()(#.*)?/.exec(s);}if(m){var r;if(m[3]){var s2=m[3].replace(/#/g,"");r=s2.parseParams("tag");}else{r=[[]];}var _2f=m[2]?m[2].trim():"";r.push({name:"text",value:_2f});r[0].text=[_2f];return {title:m[1].trim(),params:r};}else{return {title:s.trim(),params:[[]]};}};abego.parseTiddlerFilterTerm=function(_30,_31,_32){var re=/\s*(?:(?:\{([^\}]*)\})|(?:(=)|([#%!])|(?:(\w+)\s*\:(?!\/\/))|(?:(?:("(?:(?:\\")|[^"])+")|(?:\/((?:(?:\\\/)|[^\/])+)\/)|(\w+\:\/\/[^\s]+)|([^\s\)\-\"]+)))))/mg;var _34={"!":"title","%":"text","#":"tags"};var _35={};var _36;re.lastIndex=_31;while(1){var i=re.lastIndex;var m=re.exec(_30);if(!m||m.index!=i){throw "Word or String literal expected";}if(m[1]){var _39={};var _3a=abego.getBracedText(_30,0,_39);if(!_3a){throw "Invalid {...} syntax";}var f=Function("tiddler","return ("+_3a+");");return {func:f,lastIndex:_39.lastIndex,markRE:null};}if(m[2]){_36=true;}else{if(m[3]){_35[_34[m[3]]]=1;}else{if(m[4]){_35[m[4]]=1;}else{var _3c=m[6];var _3d=m[5]?window.eval(m[5]):m[6]?m[6]:m[7]?m[7]:m[8];var _32=abego.copyOptions(_32);_32.fullWordMatch=_36;_32.textIsRegExp=_3c;var _3e=[];for(var n in _35){_3e.push(n);}if(_3e.length==0){_32.fields=_32.defaultFields;}else{_32.fields=_3e;_32.withExtendedFields=false;}var _40=new abego.TiddlerFilterTerm(_3d,_32);var _41=_3c?_3d:_3d.escapeRegExp();if(_41&&_36){_41="\\b"+_41+"\\b";}return {func:function(_42){return _40.test(_42);},lastIndex:re.lastIndex,markRE:_41?"(?:"+_41+")":null};}}}}};abego.BoolExp=function(s,_44,_45){this.s=s;var _46=_45&&_45.defaultOperationIs_OR;var _47=/\s*(?:(\-|not)|(\())/gi;var _48=/\s*\)/g;var _49=/\s*(?:(and|\&\&)|(or|\|\|))/gi;var _4a=/\s*[^\)\s]/g;var _4b=/\s*(\-|not)?(\s*\()?/gi;var _4c=function(_4d){_4b.lastIndex=_4d;var m=_4b.exec(s);var _4f;var _50;if(m&&m.index==_4d){_4d=_4b.lastIndex;_4f=m[1];if(m[2]){var e=parseBoolExpression(_4d);_48.lastIndex=e.lastIndex;if(!_48.exec(s)){throw "Missing ')'";}_50={func:e.func,lastIndex:_48.lastIndex};}}if(!_50){_50=_44(s,_4d,_45);}if(_4f){_50.func=(function(f){return function(_53){return !f(_53);};})(_50.func);_50.markRE=null;}return _50;};var _54=function(_55){var _56=_4c(_55);while(1){var l=_56.lastIndex;_49.lastIndex=l;var m=_49.exec(s);var _59;var _5a;if(m&&m.index==l){_59=!m[1];_5a=_4c(_49.lastIndex);}else{try{_5a=_4c(l);}catch(e){return _56;}_59=_46;}_56.func=(function(_5b,_5c,_5d){return _5d?function(_5e){return _5b(_5e)||_5c(_5e);}:function(_5f){return _5b(_5f)&&_5c(_5f);};})(_56.func,_5a.func,_59);_56.lastIndex=_5a.lastIndex;if(!_56.markRE){_56.markRE=_5a.markRE;}else{if(_5a.markRE){_56.markRE=_56.markRE+"|"+_5a.markRE;}}}};var _60=_54(0);this.evalFunc=_60.func;if(_60.markRE){this.markRegExp=new RegExp(_60.markRE,_45.caseSensitive?"mg":"img");}};abego.BoolExp.prototype.exec=function(){return this.evalFunc.apply(this,arguments);};abego.BoolExp.prototype.getMarkRegExp=function(){return this.markRegExp;};abego.BoolExp.prototype.toString=function(){return this.s;};abego.MultiFieldRegExpTester=function(re,_62,_63){this.re=re;this.fields=_62?_62:["title","text","tags"];this.withExtendedFields=_63;};abego.MultiFieldRegExpTester.prototype.test=function(_64){var re=this.re;for(var i=0;i<this.fields.length;i++){var s=store.getValue(_64,this.fields[i]);if(typeof s=="string"&&re.test(s)){return this.fields[i];}}if(this.withExtendedFields){return store.forEachField(_64,function(_68,_69,_6a){return typeof _6a=="string"&&re.test(_6a)?_69:null;},true);}return null;};abego.TiddlerQuery=function(_6b,_6c,_6d,_6e,_6f){if(_6d){this.regExp=new RegExp(_6b,_6c?"mg":"img");this.tester=new abego.MultiFieldRegExpTester(this.regExp,_6e,_6f);}else{this.expr=new abego.BoolExp(_6b,abego.parseTiddlerFilterTerm,{defaultFields:_6e,caseSensitive:_6c,withExtendedFields:_6f});}this.getQueryText=function(){return _6b;};this.getUseRegExp=function(){return _6d;};this.getCaseSensitive=function(){return _6c;};this.getDefaultFields=function(){return _6e;};this.getWithExtendedFields=function(){return _6f;};};abego.TiddlerQuery.prototype.test=function(_70){if(!_70){return false;}if(this.regExp){return this.tester.test(_70);}return this.expr.exec(_70);};abego.TiddlerQuery.prototype.filter=function(_71){return abego.select(_71,this.test,this);};abego.TiddlerQuery.prototype.getMarkRegExp=function(){if(this.regExp){return "".search(this.regExp)>=0?null:this.regExp;}return this.expr.getMarkRegExp();};abego.TiddlerQuery.prototype.toString=function(){return (this.regExp?this.regExp:this.expr).toString();};abego.PageWiseRenderer=function(){this.firstIndexOnPage=0;};merge(abego.PageWiseRenderer.prototype,{setItems:function(_72){this.items=_72;this.setFirstIndexOnPage(0);},getMaxPagesInNavigation:function(){return 10;},getItemsCount:function(_73){return this.items?this.items.length:0;},getCurrentPageIndex:function(){return Math.floor(this.firstIndexOnPage/this.getItemsPerPage());},getLastPageIndex:function(){return Math.floor((this.getItemsCount()-1)/this.getItemsPerPage());},setFirstIndexOnPage:function(_74){this.firstIndexOnPage=Math.min(Math.max(0,_74),this.getItemsCount()-1);},getFirstIndexOnPage:function(){this.firstIndexOnPage=Math.floor(this.firstIndexOnPage/this.getItemsPerPage())*this.getItemsPerPage();return this.firstIndexOnPage;},getLastIndexOnPage:function(){return Math.min(this.getFirstIndexOnPage()+this.getItemsPerPage()-1,this.getItemsCount()-1);},onPageChanged:function(_75,_76){},renderPage:function(_77){if(_77.beginRendering){_77.beginRendering(this);}try{if(this.getItemsCount()){var _78=this.getLastIndexOnPage();var _79=-1;for(var i=this.getFirstIndexOnPage();i<=_78;i++){_79++;_77.render(this,this.items[i],i,_79);}}}finally{if(_77.endRendering){_77.endRendering(this);}}},addPageNavigation:function(_7b){if(!this.getItemsCount()){return;}var _7c=this;var _7d=function(e){if(!e){var e=window.event;}var _7f=abego.toInt(this.getAttribute("page"),0);var _80=_7c.getCurrentPageIndex();if(_7f==_80){return;}var _81=_7f*_7c.getItemsPerPage();_7c.setFirstIndexOnPage(_81);_7c.onPageChanged(_7f,_80);};var _82;var _83=this.getCurrentPageIndex();var _84=this.getLastPageIndex();if(_83>0){_82=createTiddlyButton(_7b,"Previous","Go to previous page (Shortcut: Alt-'<')",_7d,"prev");_82.setAttribute("page",(_83-1).toString());_82.setAttribute("accessKey","<");}for(var i=-this.getMaxPagesInNavigation();i<this.getMaxPagesInNavigation();i++){var _86=_83+i;if(_86<0){continue;}if(_86>_84){break;}var _87=(i+_83+1).toString();var _88=_86==_83?"currentPage":"otherPage";_82=createTiddlyButton(_7b,_87,"Go to page %0".format([_87]),_7d,_88);_82.setAttribute("page",(_86).toString());}if(_83<_84){_82=createTiddlyButton(_7b,"Next","Go to next page (Shortcut: Alt-'>')",_7d,"next");_82.setAttribute("page",(_83+1).toString());_82.setAttribute("accessKey",">");}}});abego.LimitedTextRenderer=function(){var _89=40;var _8a=4;var _8b=function(_8c,_8d,_8e){var n=_8c.length;if(n==0){_8c.push({start:_8d,end:_8e});return;}var i=0;for(;i<n;i++){var _91=_8c[i];if(_91.start<=_8e&&_8d<=_91.end){var r;var _93=i+1;for(;_93<n;_93++){r=_8c[_93];if(r.start>_8e||_8d>_91.end){break;}}var _94=_8d;var _95=_8e;for(var j=i;j<_93;j++){r=_8c[j];_94=Math.min(_94,r.start);_95=Math.max(_95,r.end);}_8c.splice(i,_93-i,{start:_94,end:_95});return;}if(_91.start>_8e){break;}}_8c.splice(i,0,{start:_8d,end:_8e});};var _97=function(_98){var _99=0;for(var i=0;i<_98.length;i++){var _9b=_98[i];_99+=_9b.end-_9b.start;}return _99;};var _9c=function(c){return (c>="a"&&c<="z")||(c>="A"&&c<="Z")||c=="_";};var _9e=function(s,_a0){if(!_9c(s[_a0])){return null;}for(var i=_a0-1;i>=0&&_9c(s[i]);i--){}var _a2=i+1;var n=s.length;for(i=_a0+1;i<n&&_9c(s[i]);i++){}return {start:_a2,end:i};};var _a4=function(s,_a6,_a7){var _a8;if(_a7){_a8=_9e(s,_a6);}else{if(_a6<=0){return _a6;}_a8=_9e(s,_a6-1);}if(!_a8){return _a6;}if(_a7){if(_a8.start>=_a6-_8a){return _a8.start;}if(_a8.end<=_a6+_8a){return _a8.end;}}else{if(_a8.end<=_a6+_8a){return _a8.end;}if(_a8.start>=_a6-_8a){return _a8.start;}}return _a6;};var _a9=function(s,_ab){var _ac=[];if(_ab){var _ad=0;var n=s.length;var _af=0;do{_ab.lastIndex=_ad;var _b0=_ab.exec(s);if(_b0){if(_ad<_b0.index){var t=s.substring(_ad,_b0.index);_ac.push({text:t});}_ac.push({text:_b0[0],isMatch:true});_ad=_b0.index+_b0[0].length;}else{_ac.push({text:s.substr(_ad)});break;}}while(true);}else{_ac.push({text:s});}return _ac;};var _b2=function(_b3){var _b4=0;for(var i=0;i<_b3.length;i++){if(_b3[i].isMatch){_b4++;}}return _b4;};var _b6=function(s,_b8,_b9,_ba,_bb){var _bc=Math.max(Math.floor(_bb/(_ba+1)),_89);var _bd=Math.max(_bc-(_b9-_b8),0);var _be=Math.min(Math.floor(_b9+_bd/3),s.length);var _bf=Math.max(_be-_bc,0);_bf=_a4(s,_bf,true);_be=_a4(s,_be,false);return {start:_bf,end:_be};};var _c0=function(_c1,s,_c3){var _c4=[];var _c5=_b2(_c1);var pos=0;for(var i=0;i<_c1.length;i++){var t=_c1[i];var _c9=t.text;if(t.isMatch){var _ca=_b6(s,pos,pos+_c9.length,_c5,_c3);_8b(_c4,_ca.start,_ca.end);}pos+=_c9.length;}return _c4;};var _cb=function(s,_cd,_ce){var _cf=_ce-_97(_cd);while(_cf>0){if(_cd.length==0){_8b(_cd,0,_a4(s,_ce,false));return;}else{var _d0=_cd[0];var _d1;var _d2;if(_d0.start==0){_d1=_d0.end;if(_cd.length>1){_d2=_cd[1].start;}else{_8b(_cd,_d1,_a4(s,_d1+_cf,false));return;}}else{_d1=0;_d2=_d0.start;}var _d3=Math.min(_d2,_d1+_cf);_8b(_cd,_d1,_d3);_cf-=(_d3-_d1);}}};var _d4=function(_d5,s,_d7,_d8,_d9){if(_d8.length==0){return;}var _da=function(_db,s,_dd,_de,_df){var t;var _e1;var pos=0;var i=0;var _e4=0;for(;i<_dd.length;i++){t=_dd[i];_e1=t.text;if(_de<pos+_e1.length){_e4=_de-pos;break;}pos+=_e1.length;}var _e5=_df-_de;for(;i<_dd.length&&_e5>0;i++){t=_dd[i];_e1=t.text.substr(_e4);_e4=0;if(_e1.length>_e5){_e1=_e1.substr(0,_e5);}if(t.isMatch){createTiddlyElement(_db,"span",null,"marked",_e1);}else{createTiddlyText(_db,_e1);}_e5-=_e1.length;}if(_df<s.length){abego.createEllipsis(_db);}};if(_d8[0].start>0){abego.createEllipsis(_d5);}var _e6=_d9;for(var i=0;i<_d8.length&&_e6>0;i++){var _e8=_d8[i];var len=Math.min(_e8.end-_e8.start,_e6);_da(_d5,s,_d7,_e8.start,_e8.start+len);_e6-=len;}};this.render=function(_ea,s,_ec,_ed){if(s.length<_ec){_ec=s.length;}var _ee=_a9(s,_ed);var _ef=_c0(_ee,s,_ec);_cb(s,_ef,_ec);_d4(_ea,s,_ee,_ef,_ec);};};(function(){function alertAndThrow(msg){alert(msg);throw msg;}if(version.major<2||(version.major==2&&version.minor<1)){alertAndThrow("YourSearchPlugin requires TiddlyWiki 2.1 or newer.\n\nCheck the archive for YourSearch plugins\nsupporting older versions of TiddlyWiki.\n\nArchive: http://tiddlywiki.abego-software.de/archive");}abego.YourSearch={};var _f1;var _f2;var _f3=function(_f4){_f1=_f4;};var _f5=function(){return _f1?_f1:[];};var _f6=function(){return _f1?_f1.length:0;};var _f7=4;var _f8=10;var _f9=2;var _fa=function(s,re){var m=s.match(re);return m?m.length:0;};var _fe=function(_ff,_100){var _101=_100.getMarkRegExp();if(!_101){return 1;}var _102=_ff.title.match(_101);var _103=_102?_102.length:0;var _104=_fa(_ff.getTags(),_101);var _105=_102?_102.join("").length:0;var _106=_ff.title.length>0?_105/_ff.title.length:0;var rank=_103*_f7+_104*_f9+_106*_f8+1;return rank;};var _108=function(_109,_10a,_10b,_10c,_10d,_10e){_f2=null;var _10f=_109.reverseLookup("tags",_10e,false);try{var _110=[];if(config.options.chkSearchInTitle){_110.push("title");}if(config.options.chkSearchInText){_110.push("text");}if(config.options.chkSearchInTags){_110.push("tags");}_f2=new abego.TiddlerQuery(_10a,_10b,_10c,_110,config.options.chkSearchExtendedFields);}catch(e){return [];}var _111=_f2.filter(_10f);var _112=abego.YourSearch.getRankFunction();for(var i=0;i<_111.length;i++){var _114=_111[i];var rank=_112(_114,_f2);_114.searchRank=rank;}if(!_10d){_10d="title";}var _116=function(a,b){var _119=a.searchRank-b.searchRank;if(_119==0){if(a[_10d]==b[_10d]){return (0);}else{return (a[_10d]<b[_10d])?-1:+1;}}else{return (_119>0)?-1:+1;}};_111.sort(_116);return _111;};var _11a=80;var _11b=50;var _11c=250;var _11d=50;var _11e=25;var _11f=10;var _120="yourSearchResult";var _121="yourSearchResultItems";var _122;var _123;var _124;var _125;var _126;var _127=function(){if(version.extensions.YourSearchPlugin.styleSheetInited){return;}version.extensions.YourSearchPlugin.styleSheetInited=true;setStylesheet(store.getTiddlerText("YourSearchStyleSheet"),"yourSearch");};var _128=function(){return _123!=null&&_123.parentNode==document.body;};var _129=function(){if(_128()){document.body.removeChild(_123);}};var _12a=function(e){_129();var _12c=this.getAttribute("tiddlyLink");if(_12c){var _12d=this.getAttribute("withHilite");var _12e=highlightHack;if(_12d&&_12d=="true"&&_f2){highlightHack=_f2.getMarkRegExp();}story.displayTiddler(this,_12c);highlightHack=_12e;}return (false);};var _12f=function(){if(!_124){return;}var root=_124;var _131=findPosX(root);var _132=findPosY(root);var _133=root.offsetHeight;var _134=_131;var _135=_132+_133;var _136=findWindowWidth();if(_136<_123.offsetWidth){_123.style.width=(_136-100)+"px";_136=findWindowWidth();}var _137=_123.offsetWidth;if(_134+_137>_136){_134=_136-_137-30;}if(_134<0){_134=0;}_123.style.left=_134+"px";_123.style.top=_135+"px";_123.style.display="block";};var _138=function(){if(_123){window.scrollTo(0,ensureVisible(_123));}if(_124){window.scrollTo(0,ensureVisible(_124));}};var _139=function(){_12f();_138();};var _13a;var _13b;var _13c=new abego.PageWiseRenderer();var _13d=function(_13e){this.itemHtml=store.getTiddlerText("YourSearchItemTemplate");if(!this.itemHtml){alertAndThrow("YourSearchItemTemplate not found");}this.place=document.getElementById(_121);if(!this.place){this.place=createTiddlyElement(_13e,"div",_121);}};merge(_13d.prototype,{render:function(_13f,_140,_141,_142){_13a=_142;_13b=_140;var item=createTiddlyElement(this.place,"div",null,"yourSearchItem");item.innerHTML=this.itemHtml;applyHtmlMacros(item,null);refreshElements(item,null);},endRendering:function(_144){_13b=null;}});var _145=function(){if(!_123||!_124){return;}var html=store.getTiddlerText("YourSearchResultTemplate");if(!html){html="<b>Tiddler YourSearchResultTemplate not found</b>";}_123.innerHTML=html;applyHtmlMacros(_123,null);refreshElements(_123,null);var _147=new _13d(_123);_13c.renderPage(_147);_139();};_13c.getItemsPerPage=function(){var n=(config.options.chkPreviewText)?abego.toInt(config.options.txtItemsPerPageWithPreview,_11f):abego.toInt(config.options.txtItemsPerPage,_11e);return (n>0)?n:1;};_13c.onPageChanged=function(){_145();};var _149=function(){if(!_123){_123=createTiddlyElement(document.body,"div",_120,"yourSearchResult");}else{if(_123.parentNode!=document.body){document.body.appendChild(_123);}}_145();};var _14a=function(){if(_124==null||!config.options.chkUseYourSearch){return;}if((_124.value==_122)&&_122&&!_128()){if(_123&&(_123.parentNode!=document.body)){document.body.appendChild(_123);_139();}else{_149();}}};var _14b=function(){_129();_123=null;_122=null;};var _14c=function(self,e){while(e!=null){if(self==e){return true;}e=e.parentNode;}return false;};var _14f=function(e){if(e.target==_124){return;}if(e.target==_125){return;}if(_123&&_14c(_123,e.target)){return;}_129();};var _151=function(e){if(e.keyCode==27){_129();}};addEvent(document,"click",_14f);addEvent(document,"keyup",_151);var _153=function(text,_155,_156){_122=text;_f3(_108(store,text,_155,_156,"title","excludeSearch"));highlightHack=_f2?_f2.getMarkRegExp():null;_13c.setItems(_f5());_149();highlightHack=null;};var _157=function(_158,_159,_15a,_15b,_15c,_15d){_127();_122="";var _15e=null;var _15f=function(txt){if(config.options.chkUseYourSearch){_153(txt.value,config.options.chkCaseSensitiveSearch,config.options.chkRegExpSearch);}else{story.search(txt.value,config.options.chkCaseSensitiveSearch,config.options.chkRegExpSearch);}_122=txt.value;};var _161=function(e){_15f(_124);return false;};var _163=function(e){if(!e){var e=window.event;}_124=this;switch(e.keyCode){case 13:if(e.ctrlKey&&_126&&_128()){_126.onclick.apply(_126,[e]);}else{_15f(this);}break;case 27:if(_128()){_129();}else{this.value="";clearMessage();}break;}if(String.fromCharCode(e.keyCode)==this.accessKey||e.altKey){_14a();}if(this.value.length<3&&_15e){clearTimeout(_15e);}if(this.value.length>2){if(this.value!=_122){if(!config.options.chkUseYourSearch||config.options.chkSearchAsYouType){if(_15e){clearTimeout(_15e);}var txt=this;_15e=setTimeout(function(){_15f(txt);},500);}}else{if(_15e){clearTimeout(_15e);}}}if(this.value.length==0){_129();}};var _166=function(e){this.select();clearMessage();_14a();};var args=_15c.parseParams("list",null,true);var _169=getFlag(args,"buttonAtRight");var _16a=getParam(args,"sizeTextbox",this.sizeTextbox);var btn;if(!_169){btn=createTiddlyButton(_158,this.label,this.prompt,_161);}var txt=createTiddlyElement(_158,"input",null,null,null);if(_15a[0]){txt.value=_15a[0];}txt.onkeyup=_163;txt.onfocus=_166;txt.setAttribute("size",_16a);txt.setAttribute("accessKey",this.accessKey);txt.setAttribute("autocomplete","off");if(config.browser.isSafari){txt.setAttribute("type","search");txt.setAttribute("results","5");}else{txt.setAttribute("type","text");}if(_169){btn=createTiddlyButton(_158,this.label,this.prompt,_161);}_124=txt;_125=btn;};var _16d=function(){_129();var _16e=_f5();var n=_16e.length;if(n){var _170=[];for(var i=0;i<n;i++){_170.push(_16e[i].title);}story.displayTiddlers(null,_170);}};var _172=function(_173,_174,_175,_176){invokeMacro(_173,"option",_174,_175,_176);var elem=_173.lastChild;var _178=elem.onclick;elem.onclick=function(e){var _17a=_178.apply(this,arguments);_145();return _17a;};return elem;};var _17b=function(s){var _17d=["''","{{{","}}}","//","<<<","/***","***/"];var _17e="";for(var i=0;i<_17d.length;i++){if(i!=0){_17e+="|";}_17e+="("+_17d[i].escapeRegExp()+")";}return s.replace(new RegExp(_17e,"mg"),"").trim();};var _180=function(){var i=_13a;return (i>=0&&i<=9)?(i<9?(i+1):0):-1;};var _182=new abego.LimitedTextRenderer();var _183=function(_184,s,_186){_182.render(_184,s,_186,_f2.getMarkRegExp());};var _187=TiddlyWiki.prototype.saveTiddler;TiddlyWiki.prototype.saveTiddler=function(_188,_189,_18a,_18b,_18c,tags,_18e){_187.apply(this,arguments);_14b();};var _18f=TiddlyWiki.prototype.removeTiddler;TiddlyWiki.prototype.removeTiddler=function(_190){_18f.apply(this,arguments);_14b();};config.macros.yourSearch={label:"yourSearch",prompt:"Gives access to the current/last YourSearch result",handler:function(_191,_192,_193,_194,_195,_196){if(_193.length==0){return;}var name=_193[0];var func=config.macros.yourSearch.funcs[name];if(func){func(_191,_192,_193,_194,_195,_196);}},tests:{"true":function(){return true;},"false":function(){return false;},"found":function(){return _f6()>0;},"previewText":function(){return config.options.chkPreviewText;}},funcs:{itemRange:function(_199){if(_f6()){var _19a=_13c.getLastIndexOnPage();var s="%0 - %1".format([_13c.getFirstIndexOnPage()+1,_19a+1]);createTiddlyText(_199,s);}},count:function(_19c){createTiddlyText(_19c,_f6().toString());},query:function(_19d){if(_f2){createTiddlyText(_19d,_f2.toString());}},version:function(_19e){var t="YourSearch %0.%1.%2".format([version.extensions.YourSearchPlugin.major,version.extensions.YourSearchPlugin.minor,version.extensions.YourSearchPlugin.revision]);var e=createTiddlyElement(_19e,"a");e.setAttribute("href","http://tiddlywiki.abego-software.de/#YourSearchPlugin");e.innerHTML="<font color=\"black\" face=\"Arial, Helvetica, sans-serif\">"+t+"<font>";},copyright:function(_1a1){var e=createTiddlyElement(_1a1,"a");e.setAttribute("href","http://www.abego-software.de");e.innerHTML="<font color=\"black\" face=\"Arial, Helvetica, sans-serif\">&copy; 2005-2006 <b><font color=\"red\">abego</font></b> Software<font>";},newTiddlerButton:function(_1a3){if(_f2){var r=abego.parseNewTiddlerCommandLine(_f2.getQueryText());var btn=config.macros.newTiddler.createNewTiddlerButton(_1a3,r.title,r.params,"new tiddler","Create a new tiddler based on search text. (Shortcut: Ctrl-Enter; Separators: '.', '#')",null,"text");var _1a6=btn.onclick;btn.onclick=function(){_129();_1a6.apply(this,arguments);};_126=btn;}},linkButton:function(_1a7,_1a8,_1a9,_1aa,_1ab,_1ac){if(_1a9<2){return;}var _1ad=_1a9[1];var text=_1a9<3?_1ad:_1a9[2];var _1af=_1a9<4?text:_1a9[3];var _1b0=_1a9<5?null:_1a9[4];var btn=createTiddlyButton(_1a7,text,_1af,_12a,null,null,_1b0);btn.setAttribute("tiddlyLink",_1ad);},closeButton:function(_1b2,_1b3,_1b4,_1b5,_1b6,_1b7){var _1b8=createTiddlyButton(_1b2,"close","Close the Search Results (Shortcut: ESC)",_129);},openAllButton:function(_1b9,_1ba,_1bb,_1bc,_1bd,_1be){var n=_f6();if(n==0){return;}var _1c0=n==1?"open tiddler":"open all %0 tiddlers".format([n]);var _1c1=createTiddlyButton(_1b9,_1c0,"Open all found tiddlers (Shortcut: Alt-O)",_16d);_1c1.setAttribute("accessKey","O");},naviBar:function(_1c2,_1c3,_1c4,_1c5,_1c6,_1c7){_13c.addPageNavigation(_1c2);},"if":function(_1c8,_1c9,_1ca,_1cb,_1cc,_1cd){if(_1ca.length<2){return;}var _1ce=_1ca[1];var _1cf=(_1ce=="not");if(_1cf){if(_1ca.length<3){return;}_1ce=_1ca[2];}var test=config.macros.yourSearch.tests[_1ce];var _1d1=false;try{if(test){_1d1=test(_1c8,_1c9,_1ca,_1cb,_1cc,_1cd)!=_1cf;}else{_1d1=(!eval(_1ce))==_1cf;}}catch(ex){}if(!_1d1){_1c8.style.display="none";}},chkPreviewText:function(_1d2,_1d3,_1d4,_1d5,_1d6,_1d7){var _1d8=_1d4.slice(1).join(" ");var elem=_172(_1d2,"chkPreviewText",_1d5,_1d7);elem.setAttribute("accessKey","P");elem.title="Show text preview of found tiddlers (Shortcut: Alt-P)";return elem;}}};config.macros.foundTiddler={label:"foundTiddler",prompt:"Provides information on the tiddler currently processed on the YourSearch result page",handler:function(_1da,_1db,_1dc,_1dd,_1de,_1df){var name=_1dc[0];var func=config.macros.foundTiddler.funcs[name];if(func){func(_1da,_1db,_1dc,_1dd,_1de,_1df);}},funcs:{title:function(_1e2,_1e3,_1e4,_1e5,_1e6,_1e7){if(!_13b){return;}var _1e8=_180();var _1e9=_1e8>=0?"Open tiddler (Shortcut: Alt-%0)".format([_1e8.toString()]):"Open tiddler";var btn=createTiddlyButton(_1e2,null,_1e9,_12a,null);btn.setAttribute("tiddlyLink",_13b.title);btn.setAttribute("withHilite","true");_183(btn,_13b.title,_11a);if(_1e8>=0){btn.setAttribute("accessKey",_1e8.toString());}},tags:function(_1eb,_1ec,_1ed,_1ee,_1ef,_1f0){if(!_13b){return;}_183(_1eb,_13b.getTags(),_11b);},text:function(_1f1,_1f2,_1f3,_1f4,_1f5,_1f6){if(!_13b){return;}_183(_1f1,_17b(_13b.text),_11c);},field:function(_1f7,_1f8,_1f9,_1fa,_1fb,_1fc){if(!_13b){return;}var name=_1f9[1];var len=_1f9.length>2?abego.toInt(_1f9[2],_11d):_11d;var v=store.getValue(_13b,name);if(v){_183(_1f7,_17b(v),len);}},number:function(_200,_201,_202,_203,_204,_205){var _206=_180();if(_206>=0){var text="%0)".format([_206.toString()]);createTiddlyElement(_200,"span",null,"shortcutNumber",text);}}}};var opts={chkUseYourSearch:true,chkPreviewText:true,chkSearchAsYouType:true,chkSearchInTitle:true,chkSearchInText:true,chkSearchInTags:true,chkSearchExtendedFields:true,txtItemsPerPage:_11e,txtItemsPerPageWithPreview:_11f};for(var n in opts){if(config.options[n]==undefined){config.options[n]=opts[n];}}config.shadowTiddlers.AdvancedOptions+="\n<<option chkUseYourSearch>> Use 'Your Search' //([[more options|YourSearch Options]]) ([[help|YourSearch Help]])// ";config.shadowTiddlers["YourSearch Help"]="!Field Search\nWith the Field Search you can restrict your search to certain fields of a tiddler, e.g"+" only search the tags or only the titles. The general form is //fieldname//'':''//textToSearch// (e."+"g. {{{title:intro}}}). In addition one-character shortcuts are also supported for the standard field"+"s {{{title}}}, {{{text}}} and {{{tags}}}:\n|!What you want|!What you type|!Example|\n|Search ''titles "+"only''|start word with ''!''|{{{!jonny}}} (shortcut for {{{title:jonny}}})|\n|Search ''contents/text "+"only''|start word with ''%''|{{{%football}}} (shortcut for {{{text:football}}})|\n|Search ''tags only"+"''|start word with ''#''|{{{#Plugin}}} (shortcut for {{{tags:Plugin}}})|\n\nUsing this feature you may"+" also search the extended fields (\"Metadata\") introduced with TiddlyWiki 2.1, e.g. use {{{priority:1"+"}}} to find all tiddlers with the priority field set to \"1\".\n\nYou may search a word in more than one"+" field. E.g. {{{!#Plugin}}} (or {{{title:tags:Plugin}}} in the \"long form\") finds tiddlers containin"+"g \"Plugin\" either in the title or in the tags (but does not look for \"Plugin\" in the text). \n\n!Boole"+"an Search\nThe Boolean Search is useful when searching for multiple words.\n|!What you want|!What you "+"type|!Example|\n|''All words'' must exist|List of words|{{{jonny jeremy}}} (or {{{jonny and jeremy}}}"+")|\n|''At least one word'' must exist|Separate words by ''or''|{{{jonny or jeremy}}}|\n|A word ''must "+"not exist''|Start word with ''-''|{{{-jonny}}} (or {{{not jonny}}})|\n\n''Note:'' When you specify two"+" words, separated with a space, YourSearch finds all tiddlers that contain both words, but not neces"+"sarily next to each other. If you want to find a sequence of word, e.g. '{{{John Brown}}}', you need"+" to put the words into quotes. I.e. you type: {{{\"john brown\"}}}.\n\nUsing parenthesis you may change "+"the default \"left to right\" evaluation of the boolean search. E.g. {{{not (jonny or jeremy)}}} finds"+" all tiddlers that contain neither \"jonny\" nor \"jeremy. In contrast to this {{{not jonny or jeremy}}"+"} (i.e. without parenthesis) finds all tiddlers that either don't contain \"jonny\" or that contain \"j"+"eremy\".\n\n!'Exact Word' Search\nBy default a search result all matches that 'contain' the searched tex"+"t. E.g. if you search for {{{Task}}} you will get all tiddlers containing 'Task', but also '~Complet"+"edTask', '~TaskForce' etc.\n\nIf you only want to get the tiddlers that contain 'exactly the word' you"+" need to prefix it with a '='. E.g. typing '=Task' will find the tiddlers that contain the word 'Tas"+"k', ignoring words that just contain 'Task' as a substring.\n\n!~CaseSensitiveSearch and ~RegExpSearch"+"\nThe standard search options ~CaseSensitiveSearch and ~RegExpSearch are fully supported by YourSearc"+"h. However when ''~RegExpSearch'' is on Filtered and Boolean Search are disabled.\n\nIn addition you m"+"ay do a \"regular expression\" search even with the ''~RegExpSearch'' set to false by directly enterin"+"g the regular expression into the search field, framed with {{{/.../}}}. \n\nExample: {{{/m[ae][iy]er/"+"}}} will find all tiddlers that contain either \"maier\", \"mayer\", \"meier\" or \"meyer\".\n\n!~JavaScript E"+"xpression Filtering\nIf you are familiar with JavaScript programming and know some TiddlyWiki interna"+"ls you may also use JavaScript expression for the search. Just enter a JavaScript boolean expression"+" into the search field, framed with {{{ { ... } }}}. In the code refer to the variable tiddler and e"+"valuate to {{{true}}} when the given tiddler should be included in the result. \n\nExample: {{{ { tidd"+"ler.modified > new Date(\"Jul 4, 2005\")} }}} returns all tiddler modified after July 4th, 2005.\n\n!Com"+"bined Search\nYou are free to combine the various search options. \n\n''Examples''\n|!What you type|!Res"+"ult|\n|{{{!jonny !jeremy -%football}}}|all tiddlers with both {{{jonny}}} and {{{jeremy}}} in its tit"+"les, but no {{{football}}} in content.|\n|{{{#=Task}}}|All tiddlers tagged with 'Task' (the exact wor"+"d). Tags named '~CompletedTask', '~TaskForce' etc. are not considered.|\n\n!Access Keys\nYou are encour"+"aged to use the access keys (also called \"shortcut\" keys) for the most frequently used operations. F"+"or quick reference these shortcuts are also mentioned in the tooltip for the various buttons etc.\n\n|"+"!Key|!Operation|\n|{{{Alt-F}}}|''The most important keystroke'': It moves the cursor to the search in"+"put field so you can directly start typing your query. Pressing {{{Alt-F}}} will also display the pr"+"evious search result. This way you can quickly display multiple tiddlers using \"Press {{{Alt-F}}}. S"+"elect tiddler.\" sequences.|\n|{{{ESC}}}|Closes the [[YourSearch Result]]. When the [[YourSearch Resul"+"t]] is already closed and the cursor is in the search input field the field's content is cleared so "+"you start a new query.|\n|{{{Alt-1}}}, {{{Alt-2}}},... |Pressing these keys opens the first, second e"+"tc. tiddler from the result list.|\n|{{{Alt-O}}}|Opens all found tiddlers.|\n|{{{Alt-P}}}|Toggles the "+"'Preview Text' mode.|\n|{{{Alt-'<'}}}, {{{Alt-'>'}}}|Displays the previous or next page in the [[Your"+"Search Result]].|\n|{{{Return}}}|When you have turned off the 'as you type' search mode pressing the "+"{{{Return}}} key actually starts the search (as does pressing the 'search' button).|\n\n//If some of t"+"hese shortcuts don't work for you check your browser if you have other extensions installed that alr"+"eady \"use\" these shortcuts.//";config.shadowTiddlers["YourSearch Options"]="|>|!YourSearch Options|\n|>|<<option chkUseYourSearch>> Use 'Your Search'|\n|!|<<option chkPreviewText"+">> Show Text Preview|\n|!|<<option chkSearchAsYouType>> 'Search As You Type' Mode (No RETURN required"+" to start search)|\n|!|Default Search Filter:<<option chkSearchInTitle>>Title ('!')     <<option chk"+"SearchInText>>Text ('%')     <<option chkSearchInTags>>Tags ('#')    <<option chkSearchExtendedFiel"+"ds>>Extended Fields<html><br><font size=\"-2\">The fields of a tiddlers that are searched when you don"+"'t explicitly specify a filter in the search text <br>(Explictly specify fields using one or more '!"+"', '%', '#' or 'fieldname:' prefix before the word/text to find).</font></html>|\n|!|Number of items "+"on search result page: <<option txtItemsPerPage>>|\n|!|Number of items on search result page with pre"+"view text: <<option txtItemsPerPageWithPreview>>|\n";config.shadowTiddlers["YourSearchStyleSheet"]="/***\n!~YourSearchResult Stylesheet\n***/\n/*{{{*/\n.yourSearchResult {\n\tposition: absolute;\n\twidth: 800"+"px;\n\n\tpadding: 0.2em;\n\tlist-style: none;\n\tmargin: 0;\n\n\tbackground: #ffd;\n\tborder: 1px solid DarkGra"+"y;\n}\n\n/*}}}*/\n/***\n!!Summary Section\n***/\n/*{{{*/\n.yourSearchResult .summary {\n\tborder-bottom-width:"+" thin;\n\tborder-bottom-style: solid;\n\tborder-bottom-color: #999999;\n\tpadding-bottom: 4px;\n}\n\n.yourSea"+"rchRange, .yourSearchCount, .yourSearchQuery   {\n\tfont-weight: bold;\n}\n\n.yourSearchResult .summary ."+"button {\n\tfont-size: 10px;\n\n\tpadding-left: 0.3em;\n\tpadding-right: 0.3em;\n}\n\n.yourSearchResult .summa"+"ry .chkBoxLabel {\n\tfont-size: 10px;\n\n\tpadding-right: 0.3em;\n}\n\n/*}}}*/\n/***\n!!Items Area\n***/\n/*{{{*"+"/\n.yourSearchResult .marked {\n\tbackground: none;\n\tfont-weight: bold;\n}\n\n.yourSearchItem {\n\tmargin-to"+"p: 2px;\n}\n\n.yourSearchNumber {\n\tcolor: #808080;\n}\n\n\n.yourSearchTags {\n\tcolor: #008000;\n}\n\n.yourSearc"+"hText {\n\tcolor: #808080;\n\tmargin-bottom: 6px;\n}\n\n/*}}}*/\n/***\n!!Footer\n***/\n/*{{{*/\n.yourSearchFoote"+"r {\n\tmargin-top: 8px;\n\tborder-top-width: thin;\n\tborder-top-style: solid;\n\tborder-top-color: #999999;"+"\n}\n\n.yourSearchFooter a:hover{\n\tbackground: none;\n\tcolor: none;\n}\n/*}}}*/\n/***\n!!Navigation Bar\n***/"+"\n/*{{{*/\n.yourSearchNaviBar a {\n\tfont-size: 16px;\n\tmargin-left: 4px;\n\tmargin-right: 4px;\n\tcolor: bla"+"ck;\n\ttext-decoration: underline;\n}\n\n.yourSearchNaviBar a:hover {\n\tbackground-color: none;\n}\n\n.yourSe"+"archNaviBar .prev {\n\tfont-weight: bold;\n\tcolor: blue;\n}\n\n.yourSearchNaviBar .currentPage {\n\tcolor: #"+"FF0000;\n\tfont-weight: bold;\n\ttext-decoration: none;\n}\n\n.yourSearchNaviBar .next {\n\tfont-weight: bold"+";\n\tcolor: blue;\n}\n/*}}}*/\n";config.shadowTiddlers["YourSearchResultTemplate"]="<!--\n{{{\n-->\n<span macro=\"yourSearch if found\">\n<!-- The Summary Header ============================"+"================ -->\n<table class=\"summary\" border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">"+"<tbody>\n  <tr>\n\t<td align=\"left\">\n\t\tYourSearch Result <span class=\"yourSearchRange\" macro=\"yourSearc"+"h itemRange\"></span>\n\t\t&nbsp;of&nbsp;<span class=\"yourSearchCount\" macro=\"yourSearch count\"></span>\n"+"\t\tfor&nbsp;<span class=\"yourSearchQuery\" macro=\"yourSearch query\"></span>\n\t</td>\n\t<td class=\"yourSea"+"rchButtons\" align=\"right\">\n\t\t<span macro=\"yourSearch chkPreviewText\"></span><span class=\"chkBoxLabel"+"\">preview text</span>\n\t\t<span macro=\"yourSearch newTiddlerButton\"></span>\n\t\t<span macro=\"yourSearch openAllButton\"></span>\n\t\t<span macro=\"yourSearch lin"+"kButton 'YourSearch Options' options 'Configure YourSearch'\"></span>\n\t\t<span macro=\"yourSearch linkB"+"utton 'YourSearch Help' help 'Get help how to use YourSearch'\"></span>\n\t\t<span macro=\"yourSearch clo"+"seButton\"></span>\n\t</td>\n  </tr>\n</tbody></table>\n\n<!-- The List of Found Tiddlers ================="+"=========================== -->\n<div id=\"yourSearchResultItems\" itemsPerPage=\"25\" itemsPerPageWithPr"+"eview=\"10\"></div>\n\n<!-- The Footer (with the Navigation) ==========================================="+"= -->\n<table class=\"yourSearchFooter\" border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tbody"+">\n  <tr>\n\t<td align=\"left\">\n\t\tResult page: <span class=\"yourSearchNaviBar\" macro=\"yourSearch naviBar"+"\"></span>\n\t</td>\n\t<td align=\"right\"><span macro=\"yourSearch version\"></span>, <span macro=\"yourSearc"+"h copyright\"></span>\n\t</td>\n  </tr>\n</tbody></table>\n<!-- end of the 'tiddlers found' case ========="+"================================== -->\n</span>\n\n\n<!-- The \"No tiddlers found\" case ================="+"========================== -->\n<span macro=\"yourSearch if not found\">\n<table class=\"summary\" border="+"\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tbody>\n  <tr>\n\t<td align=\"left\">\n\t\tYourSearch Resu"+"lt: No tiddlers found for <span class=\"yourSearchQuery\" macro=\"yourSearch query\"></span>.\n\t</td>\n\t<t"+"d class=\"yourSearchButtons\" align=\"right\">\n\t\t<span macro=\"yourSearch newTiddlerButton\"></span>\n\t\t<span macro=\"yourSearch linkButton 'YourSearch Options'"+" options 'Configure YourSearch'\"></span>\n\t\t<span macro=\"yourSearch linkButton 'YourSearch Help' help"+" 'Get help how to use YourSearch'\"></span>\n\t\t<span macro=\"yourSearch closeButton\"></span>\n\t</td>\n  <"+"/tr>\n</tbody></table>\n</span>\n\n\n<!--\n}}}\n-->\n";config.shadowTiddlers["YourSearchItemTemplate"]="<!--\n{{{\n-->\n<span class='yourSearchNumber' macro='foundTiddler number'></span>\n<span class='yourSea"+"rchTitle' macro='foundTiddler title'/></span>&nbsp;-&nbsp;\n<span class='yourSearchTags' macro='found"+"Tiddler field tags 50'/></span>\n<span macro=\"yourSearch if previewText\"><div class='yourSearchText' macro='fo"+"undTiddler field text 250'/></div></span>\n<!--\n}}}\n-->";config.shadowTiddlers["YourSearch"]="<<tiddler [[YourSearch Help]]>>";config.shadowTiddlers["YourSearch Result"]="The popup-like window displaying the result of a YourSearch query.";config.macros.search.handler=_157;var _20a=function(){if(config.macros.search.handler!=_157){alert("Message from YourSearchPlugin:\n\n\nAnother plugin has disabled the 'Your Search' features.\n\n\nYou may "+"disable the other plugin or change the load order of \nthe plugins (by changing the names of the tidd"+"lers)\nto enable the 'Your Search' features.");}};setTimeout(_20a,5000);abego.YourSearch.getStandardRankFunction=function(){return _fe;};abego.YourSearch.getRankFunction=function(){return abego.YourSearch.getStandardRankFunction();};abego.YourSearch.getCurrentTiddler=function(){return _13b;};abego.YourSearch.closeResult=function(){_129();};})();}
//%/
<!--{{{-->
<div class='toolbar' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></div>
<div class='title' macro='view title'></div>

<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></div>

<div macro='view text wikified'></div>
<div class='tagClear'></div>

<!--}}}-->
Male:M
Female:F
<<closeAll>><<permaview>><<newTiddler>><<saveChanges>>{{button{[[About]]}}}