// dynamic does not work in static yet?
            //static 
            void InitializeContent()
        {
            floorplan = new Floorplan();






            Action<string, double, double, double, double, double, double, double, double, double> buildCube =
                (colour, w, h, d, x, y, z, rx, ry, rz) =>
                {
                    new cube(colour, w, h, d, x, y, z, rx, ry, rz);

                };



            var zoom = 4;
            var zz = 60;
            var low = -500;

            var __index = 0;

            #region CreateFromFloorplan
            Action CreateFromFloorplan = delegate
            {
                foreach (var item in floorplan.Controls)
                {
                    (item as DeskCube).With(
                        f =>
                        {


                            var cubeheight = Math.Max(300, f.CubeHeight);
                            var z = 0;
                            var cubetex = "rgba(0,0,0,0.1)";

                            if (f.LeftWallSource != null)
                                if (f.LeftWallSource.StartsWith("#cloud"))
                                {
                                    z = low;
                                    cubetex = "";
                                }

                            if (f.WallSourceRight != null)
                                if (f.WallSourceRight.StartsWith("#cloud"))
                                {
                                    z = low;
                                    cubetex = "";
                                }

                            if (f.WallSourceTop != null)
                                if (f.WallSourceTop.StartsWith("#cloud"))
                                {
                                    z = low;
                                    cubetex = "";
                                }

                            if (f.WallSourceBottom != null)
                                if (f.WallSourceBottom.StartsWith("#cloud"))
                                {
                                    z = low;
                                    cubetex = "";
                                }

                            new cube(
                                cubetex,

                                 //w, h, d, x, y, z, rx, ry, rz
                                f.Width * zoom,

                                f.Height * zoom,

                                cubeheight / 4 * zoom,
                                //0,

                                -f.Right * zoom,

                                f.Top * zoom,

                                -(cubeheight / 4 * zoom) + zz - z * zoom,

                                //-250, 

                                0, 0, 0
                            ).With(
                                cube =>
                                {

                                    #region LoadContent
                                    Action<IHTMLDiv, string> LoadContent =
                                        (westContainer, src) =>
                                        {
                                            if (src == "#window" || src == "#webfiles")
                                            {
                                                var morespace = new IHTMLDiv().AttachTo(westContainer);


                                                // 3by3 grid
                                                morespace.style.position = IStyle.PositionEnum.absolute;
                                                morespace.style.top = -westContainer.clientHeight + "px";
                                                morespace.style.left = 0 + "px";
                                                morespace.style.width = westContainer.clientWidth + "px";
                                                morespace.style.height = westContainer.clientHeight + "px";

                                                // 3D DOCK
                                                var ff = new Form { Text = "Gallery #" + __index };

                                                ff.StartPosition = FormStartPosition.Manual;
                                                ff.Show();
                                                ff.Left = 8;

                                                ff.Top = westContainer.clientHeight + -27;

                                                ff.Width = westContainer.clientWidth - 16;
                                                ff.Height = westContainer.clientHeight + 27 - 8;

                                                ff.GetHTMLTarget().AttachTo(morespace);
                                                ff.GetHTMLTarget().className = "nolock";

                                                var ffw = new WebBrowser { Dock = DockStyle.Fill };

                                                ffw.AttachTo(ff);

                                                ffw.Navigate(

                                                    Native.Document.location.href + src + __index
                                                    );

                                                __index++;

                                                ff.PopupInsteadOfClosing(
                                                    SpecialNoMovement: true
                                                );


                                                return;
                                            }

                                            new IHTMLIFrame { allowFullScreen = true, src = src, frameBorder = "0" }.AttachTo(westContainer).With(
                                                iframe =>
                                                {
                                                    iframe.style.position = IStyle.PositionEnum.absolute;
                                                    iframe.style.left = "0px";
                                                    iframe.style.top = "0px";
                                                    iframe.style.width = "10%";
                                                    iframe.style.height = "10%";
                                                    iframe.style.transform = "scale(10.0)";
                                                    iframe.style.transformOrigin = "0% 0%";
                                                }
                                            );

                                            // disable mouse
                                            new IHTMLDiv { }.AttachTo(westContainer).With(
                                                 overlay =>
                                                 {
                                                     overlay.style.position = IStyle.PositionEnum.absolute;
                                                     overlay.style.left = "0px";
                                                     overlay.style.top = "0px";
                                                     overlay.style.width = "100%";
                                                     overlay.style.height = "100%";

                                                     overlay.style.backgroundColor = "red";
                                                     overlay.style.Opacity = 0;
                                                 }
                                             );
                                        };
                                    #endregion



                                    #region WallSourceRight
                                    if (!string.IsNullOrEmpty(f.WallSourceBottom))
                                        new IHTMLDiv { }.AttachTo(cube.south.node).With(
                                           westContainer =>
                                           {

                                               //innerText = f.LeftWallSource
                                               //btn.className = "nolock";


                                               //westContainer.style.transform = "rotateZ(-90deg)";
                                               westContainer.style.transformOrigin = "0% 0%";

                                               westContainer.style.position = IStyle.PositionEnum.absolute;
                                               westContainer.style.width = cube.south.node.clientWidth + "px";
                                               westContainer.style.left = "0px";
                                               westContainer.style.top = "0px";
                                               westContainer.style.height = cube.south.node.clientHeight + "px";


                                               if (f.LeftWallSourceAutoLoad)
                                               {
                                                   LoadContent(westContainer, f.WallSourceBottom);
                                               }

                                           }
                                       );
                                    #endregion
                                    #region WallSourceRight
                                    if (!string.IsNullOrEmpty(f.WallSourceTop))
                                        new IHTMLDiv { }.AttachTo(cube.north.node).With(
                                           westContainer =>
                                           {

                                               //innerText = f.LeftWallSource
                                               //btn.className = "nolock";


                                               //westContainer.style.transform = "rotateZ(-90deg)";
                                               westContainer.style.transformOrigin = "0% 0%";

                                               westContainer.style.position = IStyle.PositionEnum.absolute;
                                               westContainer.style.width = cube.north.node.clientWidth + "px";
                                               westContainer.style.left = "0px";
                                               westContainer.style.top = "0px";
                                               westContainer.style.height = cube.north.node.clientHeight + "px";



                                               if (f.LeftWallSourceAutoLoad)
                                               {
                                                   LoadContent(westContainer, f.WallSourceTop);

                                               }

                                           }
                                       );
                                    #endregion

                                    #region WallSourceRight
                                    if (!string.IsNullOrEmpty(f.WallSourceRight))
                                        new IHTMLDiv { }.AttachTo(cube.east.node).With(
                                           westContainer =>
                                           {

                                               //innerText = f.LeftWallSource
                                               //btn.className = "nolock";


                                               westContainer.style.transform = "rotateZ(-90deg)";
                                               westContainer.style.transformOrigin = "0% 0%";

                                               westContainer.style.position = IStyle.PositionEnum.absolute;
                                               westContainer.style.width = cube.east.node.clientHeight + "px";
                                               westContainer.style.top = cube.east.node.clientHeight + "px";
                                               westContainer.style.height = cube.east.node.clientWidth + "px";



                                               if (f.LeftWallSourceAutoLoad)
                                               {
                                                   LoadContent(westContainer, f.WallSourceRight);

                                               }

                                           }
                                       );
                                    #endregion

                                    #region LeftWallSource
                                    if (!string.IsNullOrEmpty(f.LeftWallSource))
                                        new IHTMLDiv { }.AttachTo(cube.west.node).With(
                                            westContainer =>
                                            {

                                                //innerText = f.LeftWallSource
                                                //btn.className = "nolock";


                                                westContainer.style.transform = "rotateZ(90deg)";
                                                westContainer.style.transformOrigin = "0% 0%";

                                                westContainer.style.position = IStyle.PositionEnum.absolute;
                                                westContainer.style.width = cube.west.node.clientHeight + "px";
                                                westContainer.style.left = cube.west.node.clientWidth + "px";
                                                westContainer.style.height = cube.west.node.clientWidth + "px";

                                                if (f.LeftWallSourceAutoLoad)
                                                {
                                                    LoadContent(westContainer, f.LeftWallSource);

                                                }

                                            }
                                        );
                                    #endregion


                                }
                            );

                        }
                    );
                    (item as Floor).With(
                        f =>
                        {

                            window.viewport.camera.position.x = (f.Left + f.Width / 2) * zoom;
                            window.viewport.camera.position.y = -(f.Top + f.Height / 2) * zoom;

                            buildCube("white",

                                 //w, h, d, x, y, z, rx, ry, rz
                                f.Width * zoom,

                                f.Height * zoom,

                                10,
                                //0,

                                -f.Right * zoom, f.Top * zoom,

                                0 - low * zoom + zz,
                                //-250, 

                                0, 0, 0);

                        }
                    );
                }
            };

            CreateFromFloorplan();

            //zz += 300;

            //CreateFromFloorplan();
            #endregion


            //avoid out of memory - elements will go missing
            //zz += 300;

            //CreateFromFloorplan();







            #region onkeydown
            Native.Document.body.onkeydown += e =>
            {
                //Console.WriteLine(new { e.KeyCode });

                if (e.KeyCode == (int)Keys.W)
                    window.keyState.forward = true;
                if (e.KeyCode == (int)Keys.S)
                    window.keyState.backward = true;
                if (e.KeyCode == (int)Keys.A)
                    window.keyState.strafeleft = true;
                if (e.KeyCode == (int)Keys.D)
                    window.keyState.straferight = true;

                if (AfterKeystateChange != null)
                    AfterKeystateChange();
            };

            Native.Document.body.onkeyup += e =>
            {
                if (e.KeyCode == (int)Keys.W)
                    window.keyState.forward = false;
                if (e.KeyCode == (int)Keys.S)
                    window.keyState.backward = false;

                if (e.KeyCode == (int)Keys.A)
                    window.keyState.strafeleft = false;
                if (e.KeyCode == (int)Keys.D)
                    window.keyState.straferight = false;

                if (AfterKeystateChange != null)
                    AfterKeystateChange();
            };
            #endregion

            Func<INode, bool> isnolock =
                p =>
                {
                    var nolock = false;

                    while (p != Native.Document.body)
                    {
                        if (((IHTMLElement)p).className == "nolock")
                            nolock = true;

                        p = p.parentNode;
                    }

                    return nolock;
                };

            #region onmousemove
            Native.Document.body.tabIndex = 101;
            Native.Document.body.onmousedown +=
                e =>
                {
                    var nolock = isnolock(e.Element);
                    if (nolock)
                        return;

                    e.PreventDefault();
                    Native.Document.body.focus();
                    Native.Document.body.requestPointerLock();
                };

            Native.Document.body.onmousemove +=
                e =>
                {
                    if (Native.Document.pointerLockElement == Native.Document.body)
                    {
                        var x = window.viewport.camera.rotation.x;
                        x -= e.movementY / 2;

                        x = Math.Min(x, -60).Max(-120);

                        //Console.WriteLine(new { x });
                        window.viewport.camera.rotation.x = x;


                        var z = window.viewport.camera.rotation.z;
                        z += e.movementX / 2;


                        window.viewport.camera.rotation.z = z;

                        if (AfterCameraRotationChange != null)
                            AfterCameraRotationChange();
                    }
                    else
                    {
                        var nolock = isnolock(e.Element);

                        if (nolock)
                            Native.Document.body.style.cursor = IStyle.CursorEnum.auto;
                        else
                            Native.Document.body.style.cursor = IStyle.CursorEnum.move;
                    }
                };


            Native.Document.body.onmouseup +=
                 e =>
                 {
                     if (Native.Document.pointerLockElement == Native.Document.body)
                     {
                         Native.Document.exitPointerLock();
                     }
                 };
            #endregion




            #region loop
            Action loop = delegate
            {
                // is external target working bot ways?
                //window.speed = window.speed;

                //Console.WriteLine(new { window.keyState.forward });

                #region speed
                if (window.keyState.backward)
                {
                    if (window.speed > -window.maxSpeed)
                        window.speed -= window.accel;
                }
                else if (window.keyState.forward)
                {
                    if (window.speed < window.maxSpeed)
                        window.speed += window.accel;
                }
                else if (window.speed > 0)
                {
                    window.speed = Math.Max(window.speed - window.accel, 0);
                }
                else if (window.speed < 0)
                {
                    window.speed = Math.Max(window.speed + window.accel, 0);
                }
                else
                {
                    window.speed = 0;
                }
                #endregion


                #region strafespeed
                if (window.keyState.straferight)
                {
                    if (window.strafespeed > -window.maxSpeed)
                        window.strafespeed -= window.accel;
                }
                else if (window.keyState.strafeleft)
                {
                    if (window.strafespeed < window.maxSpeed)
                        window.strafespeed += window.accel;
                }
                else if (window.strafespeed > 0)
                {
                    window.strafespeed = Math.Max(window.strafespeed - window.accel, 0);
                }
                else if (window.strafespeed < 0)
                {
                    window.strafespeed = Math.Max(window.strafespeed + window.accel, 0);
                }
                else
                {
                    window.strafespeed = 0;
                }
                #endregion


                // sideway
                {

                    var xo = Math.Sin(window.viewport.camera.rotation.z * 0.0174532925);
                    var yo = Math.Cos(window.viewport.camera.rotation.z * 0.0174532925);

                    window.viewport.camera.position.x -= xo * window.speed;
                    window.viewport.camera.position.y -= yo * window.speed;
                }

                {
                    var xo = Math.Sin(window.viewport.camera.rotation.z * 0.0174532925 - 3.14 / 2);
                    var yo = Math.Cos(window.viewport.camera.rotation.z * 0.0174532925 - 3.14 / 2);

                    window.viewport.camera.position.x -= xo * window.strafespeed;
                    window.viewport.camera.position.y -= yo * window.strafespeed;
                }

                window.viewport.camera.update();


            };


            loop.AtAnimationFrame();
            #endregion

        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // localStorage not available on android webview!
            //E/Web Console( 3751): Uncaught TypeError: Cannot set property '20130329 Hello world' of null at http://192.168.1.107:25459/view-source:32300


            FormStyler.AtFormCreated = FormStylerLikeFloat.LikeFloat;

            new GrayPatternBackground.HTML.Images.FromAssets.background().ToDocumentBackground();

            Console.WriteLine("serial 57770");

            "My Notez (loading...)".ToDocumentTitle();


            service.AtPendingActions +=
                count =>
                {
                    if (service.ServicePending.ElapsedMilliseconds > 500)
                    {
                        if (service.ServicePending.ElapsedMilliseconds > 4000)
                        {
                            "My Notez (offline)".ToDocumentTitle();
                            return;
                        }

                        "My Notez (pending)".ToDocumentTitle();
                        return;
                    }

                    "My Notez".ToDocumentTitle();
                };

            Native.window.onbeforeunload +=
                e =>
                {
                    if (service.ServicePending.IsRunning)
                        e.Text = "The changes made here have not yet made it to the server.";
                };

            var storage = new MyLocalStorage
            {

                AtRemove =
                    x => service.remove_LocalStorage(x),

                AtSetItem =
                    (key, value) =>
                    {
                        service.set_LocalStorage(key, value);
                    }
            };

            Console.WriteLine("Do we have localStorage? [2]");

            Native.window.localStorage.With(
                localStorage =>
                {
                    Console.WriteLine("This browser has localStorage. Lets sync with that. [2]");

                    for (uint i = 0; i < localStorage.length; i++)
                    {
                        var key = localStorage.key(i);
                        var value = localStorage[key];

                        storage[key] = value;
                    }

                    // jsc why aint ths working?
                    //storage.AtRemove += localStorage.removeItem;
                    storage.AtRemove += key => localStorage.removeItem(key);
                    storage.AtSetItem += (key, value) => { localStorage[key] = value; };

                }
            );

            #region done
            Action done = delegate
                {



                    var hh = new HorizontalSplit
                    {
                        Minimum = 0.05,
                        Maximum = 0.95,
                        Value = 0.4,
                    };


                    hh.Container.AttachToDocument();
                    hh.Container.style.position = IStyle.PositionEnum.absolute;
                    hh.Container.style.left = "0px";
                    hh.Container.style.top = "0px";
                    hh.Container.style.right = "0px";
                    hh.Container.style.bottom = "0px";

                    hh.Split.Splitter.style.backgroundColor = "rgba(0,0,0,0.0)";


                    //var vv = new VerticalSplit
                    var f = new Form
                    {
                        StartPosition = FormStartPosition.Manual,
                        SizeGripStyle = SizeGripStyle.Hide,

                        Text = "Entries"
                    };

                    var f1 = new Form
                    {
                        StartPosition = FormStartPosition.Manual,
                        SizeGripStyle = SizeGripStyle.Hide,

                        Text = "My Files"
                    };

                    f1.Show();


                    var f2 = new Form
                    {
                        StartPosition = FormStartPosition.Manual,
                        SizeGripStyle = SizeGripStyle.Hide,

                        Text = "..."
                    };

                    f2.Show();

                    var w = new WebBrowser
                    {
                        Dock = DockStyle.Fill
                    };
                    w.GetHTMLTarget().name = "viewer";
                    w.AttachTo(f2);

                    w.Navigating +=
                        delegate
                        {
                            f2.Text = "Navigating";

                        };

                    w.Navigated +=
                       delegate
                       {
                           if (w.Url.ToString() == "about:blank")
                           {

                               f2.Text = "...";


                               return;
                           }

                           //ff.Text = w.DocumentTitle;
                           f2.Text = Native.window.unescape(
                               w.Url.ToString().SkipUntilLastIfAny("/").TakeUntilLastIfAny(".")
                               );



                       };

                    Native.window.requestAnimationFrame +=
                        delegate
                        {

                            var layout = new Abstractatech.JavaScript.FileStorage.HTML.Pages.App();

                            layout.Container.AttachTo(f1.GetHTMLTargetContainer());

                            Abstractatech.JavaScript.FileStorage.ApplicationContent.Target = w.GetHTMLTarget().name;


                            new Abstractatech.JavaScript.FileStorage.ApplicationContent(
                                layout,
                                service.service
                            );

                        };


                    var LeftScrollable = new IHTMLDiv { className = "SidebarForButtons" }.AttachTo(f.GetHTMLTargetContainer());

                    LeftScrollable.style.backgroundColor = "white";

                    var CreateNew = new IHTMLButton { innerText = "+ create new", className = "SidebarButton" }.AttachTo(
                      LeftScrollable
                     );

                    var ff = new Form
                    {
                        StartPosition = FormStartPosition.Manual,
                        SizeGripStyle = SizeGripStyle.Hide

                    };



                    f.Show();
                    ff.Show();




                    //var text = new TextEditor(hh.Split.RightScrollable);
                    var text = new TextEditor(ff.GetHTMLTargetContainer());

                    text.ContainerForBorders.style.border = "";

                    text.Control.style.position = IStyle.PositionEnum.absolute;
                    text.Control.style.left = "0px";
                    text.Control.style.top = "0px";
                    text.Control.style.right = "0px";
                    text.Control.style.bottom = "0px";


                    //Native.Window.onresize +=
                    //    delegate
                    //    {
                    //        var TopToolbarHeight = text.TopToolbar.clientHeight;

                    //        //Console.WriteLine(new { TopToolbarHeight });

                    //        text.DesignerContainer.style.top = (TopToolbarHeight + 4) + "px";
                    //        text.SourceContainer.style.top = (TopToolbarHeight + 4) + "px";

                    //    };


                    #region DesignerContainer
                    text.DesignerContainer.style.position = IStyle.PositionEnum.absolute;
                    text.DesignerContainer.style.left = "0px";
                    text.DesignerContainer.style.top = "3em";
                    text.DesignerContainer.style.right = "0px";
                    text.DesignerContainer.style.bottom = "3em";
                    text.DesignerContainer.style.height = "";

                    text.Frame.style.position = IStyle.PositionEnum.absolute;
                    text.Frame.style.left = "0px";
                    text.Frame.style.top = "0px";
                    //text.Frame.style.right = "0px";
                    //text.Frame.style.bottom = "0px";
                    text.Frame.style.width = "100%";
                    text.Frame.style.height = "100%";
                    #endregion


                    #region SourceContainer
                    text.SourceContainer.style.position = IStyle.PositionEnum.absolute;
                    text.SourceContainer.style.left = "0px";
                    text.SourceContainer.style.top = "3em";
                    text.SourceContainer.style.right = "0px";
                    text.SourceContainer.style.bottom = "3em";
                    text.SourceContainer.style.height = "";

                    text.TextArea.style.position = IStyle.PositionEnum.absolute;
                    text.TextArea.style.left = "0px";
                    text.TextArea.style.top = "0px";
                    //text.Frame.style.right = "0px";
                    //text.Frame.style.bottom = "0px";
                    text.TextArea.style.width = "100%";
                    text.TextArea.style.height = "100%";
                    #endregion

                    text.BottomToolbarContainer.style.position = IStyle.PositionEnum.absolute;
                    text.BottomToolbarContainer.style.left = "0px";
                    text.BottomToolbarContainer.style.right = "0px";
                    text.BottomToolbarContainer.style.bottom = "0px";

                    var oldtitle = "";

                    Action DoRefresh = delegate { };

                    #region DoCreateNew
                    Action DoCreateNew = delegate
                    {
                        oldtitle = "";

                        #region default text
                        var now = DateTime.Now;


                        var yyyy = now.Year;
                        var mm = now.Month;
                        var dd = now.Day;


                        var yyyymmdd = yyyy
                            + mm.ToString().PadLeft(2, '0')
                            + dd.ToString().PadLeft(2, '0');

                        string header = yyyymmdd + @" New Header " + storage.Keys.Count();


                        text.InnerHTML = @"
<div><font face='Verdana' size='5' color='#0000fc'>" + header + @"</font></div><div><br /></div><blockquote style='margin: 0 0 0 40px; border: none; padding: 0px;'></blockquote><font face='Verdana'>This is your content.</font>
            ";
                        #endregion



                        DoRefresh();
                    };

                    CreateNew.onclick +=
                        delegate
                        {
                            DoCreateNew();
                        };
                    #endregion




                    var buttons = new List<IHTMLButton>();

                    Action EitherCreateNewOrSelectFirst = delegate
                    {
                        if (buttons.Count == 0)
                        {
                            DoCreateNew();
                        }
                        else
                        {
                            if (buttons.Any(k => k.innerText == oldtitle))
                            {
                                //already selected
                            }
                            else
                            {
                                oldtitle = buttons.First().innerText;

                                text.InnerHTML = storage[oldtitle];
                            }
                        }
                    };


                    #region Remove this document
                    var remove = text.AddButton(null, "Remove this document",
                          delegate
                          {
                              var button = buttons.FirstOrDefault(k => k.innerText == oldtitle);

                              if (button == null)
                                  return;

                              //Native.Window.localStorage.removeItem(button.innerText);
                              storage.Remove(button.innerText);


                              button.Orphanize();
                              buttons.Remove(button);

                              EitherCreateNewOrSelectFirst();
                          }
                      );
                    #endregion


                    IHTMLElement remove_element = remove;
                    remove_element.style.Float = IStyle.FloatEnum.right;

                    text.BottomToolbar.appendChild(remove_element);

                    #region new_SidebarButton
                    Func<IHTMLButton> new_SidebarButton =
                        delegate
                        {
                            var button = new IHTMLButton { className = "SidebarButton" }.AttachTo(
                                           LeftScrollable
                                        );

                            button.onclick +=
                                delegate
                                {
                                    oldtitle = "";
                                    text.InnerHTML = storage[button.innerText];
                                    DoRefresh();

                                };

                            button.oncontextmenu +=
                               e =>
                               {
                                   e.preventDefault();

                                   storage.Remove(button.innerText);


                                   button.Orphanize();
                                   buttons.Remove(button);

                                   EitherCreateNewOrSelectFirst();
                               };

                            buttons.Add(button);

                            return button;
                        };
                    #endregion

                    #region DoRefresh
                    DoRefresh = delegate
                   {
                       // what has changed
                       // text not default anymore?
                       // title change?


                       // document unloaded?
                       if (text.Document == null)
                           return;

                       var xml = text.Document.body.AsXElement();

                       // script: error JSC1000: No implementation found for this native method, please implement [static System.String.IsNullOrWhiteSpace(System.String)]

                       xml.Elements().FirstOrDefault(k => !string.IsNullOrWhiteSpace(k.Value)).With(
                           TitleElement =>
                           {
                               // take no action for no title
                               if (string.IsNullOrWhiteSpace(TitleElement.Value))
                                   return;

                               // is there a buttn with old title?


                               var button = buttons.FirstOrDefault(
                                   k =>
                                   {
                                       if (oldtitle == "")
                                       {
                                           return k.innerText == TitleElement.Value;
                                       }

                                       return k.innerText == oldtitle;
                                   }
                               );

                               if (button == null)
                               {
                                   button = new_SidebarButton();
                               }

                               button.innerText = TitleElement.Value;

                               buttons.WithEach(
                                   x => x.setAttribute("data-active", x == button)
                               );


                               if (oldtitle != "")
                               {
                                   if (oldtitle != TitleElement.Value)
                                       storage.Remove(oldtitle);


                               }

                               ff.Text = TitleElement.Value;

                               // src="http://192.168.1.100:5763/

                               var innerHTML = text.InnerHTML;

                               var href = Native.Document.location.href.TakeUntilLastOrEmpty("/");

                               // keep only relative paths to current host
                               var xinnerHTML = innerHTML.Replace("src=\"" + href + "/", "src=\"/");

                               if (innerHTML != xinnerHTML)
                               {
                                   text.InnerHTML = xinnerHTML;
                               }

                               storage[TitleElement.Value] = xinnerHTML;
                               oldtitle = TitleElement.Value;
                               //Console.WriteLine("TitleElement: " + TitleElement.Value);
                           }
                       );

                       // whats the title?
                   };
                    #endregion



                    foreach (var button_text in storage.Keys)
                    {
                        new_SidebarButton().innerText = button_text;
                    }



                    new ScriptCoreLib.JavaScript.Runtime.Timer(
                        t =>
                        {
                            DoRefresh();



                        }
                    ).StartInterval(500);


                    EitherCreateNewOrSelectFirst();








                    #region AtResize
                    Action AtResize = delegate
                    {
                        Native.Document.getElementById("feedlyMiniIcon").Orphanize();

                        Native.Document.body.style.minWidth = "";

                        //if (ff.GetHTMLTarget().parentNode == null)
                        //{
                        //    Native.Window.scrollTo(0, 0);
                        //    f.MoveTo(8, 8).SizeTo(Native.Window.Width - 16, Native.Window.Height - 16);

                        //    return;
                        //}

                        //if (f.GetHTMLTarget().parentNode == null)
                        //{
                        //    Native.Window.scrollTo(0, 0);
                        //    ff.MoveTo(8, 8).SizeTo(Native.Window.Width - 16, Native.Window.Height - 16);

                        //    return;
                        //}

                        //if (Native.Window.Width < 1024)
                        //{
                        //    Native.Document.body.style.minWidth = (Native.Window.Width * 2) + "px";


                        //    f.MoveTo(8, 8).SizeTo(Native.Window.Width - 16, Native.Window.Height - 16);

                        //    ff.MoveTo(Native.Window.Width + 8, 8).SizeTo(Native.Window.Width - 16, Native.Window.Height - 16);

                        //    // already scrolled...
                        //    if (w.Url.ToString() != "about:blank")
                        //        // docked?
                        //        if (ff.GetHTMLTarget().parentNode != null)
                        //            Native.Window.scrollTo(ff.Left - 8, ff.Top - 8);

                        //    return;
                        //}




                        f.MoveTo(16, 16).SizeTo(hh.LeftContainer.clientWidth - 32, Native.window.Height / 3 - 16 - 4);
                        f1.MoveTo(16, Native.window.Height / 3 + 4).SizeTo(hh.LeftContainer.clientWidth - 32, Native.window.Height / 3 - 8);
                        f2.MoveTo(16, Native.window.Height / 3 * 2 + 4).SizeTo(hh.LeftContainer.clientWidth - 32, Native.window.Height / 3 - 16);


                        ff.MoveTo(
                            Native.window.Width - hh.RightContainer.clientWidth + 16

                            , 16).SizeTo(hh.RightContainer.clientWidth - 32, Native.window.Height - 32);

                        //Console.WriteLine("LeftContainer " + new { hh.LeftContainer.clientWidth });
                        //Console.WriteLine("RightContainer " + new { hh.RightContainer.clientWidth });
                    };

                    hh.ValueChanged +=
                  delegate
                  {
                      AtResize();
                  };

                    Native.window.onresize +=
                     delegate
                     {
                         AtResize();
                     };

                    Native.window.requestAnimationFrame +=
                delegate
                {
                    AtResize();
                };
                    #endregion

                    ff.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);
                    f.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);
                    f1.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);
                    f2.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);


                };
            #endregion

            var tt = default(ScriptCoreLib.JavaScript.Runtime.Timer);

            Action done_timeout = delegate
            {
                if (done == null)
                    return;

                tt.Stop();
                done();
                done = null;
            };


            service.get_LocalStorage(
                //add_localStorage: (key, value) => Native.Window.localStorage[key] = value,
                add_localStorage:
                    (key, value) =>
                    {
                        // what if we are resuming from offline edit.
                        // merge?


                        // keep the one we got from localStorage, because it has longer entry?
                        if (storage[key].Length > value.Length)
                            return;

                        storage[key] = value;
                    },

                done: done_timeout
            );


            // either server responds in 2000 or we consider us offline...
            tt = new ScriptCoreLib.JavaScript.Runtime.Timer(
                delegate
                {
                    done_timeout();
                }
            );

            tt.StartTimeout(3000);

        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            FormStyler.AtFormCreated = FormStylerLikeFloat.LikeFloat;

            // http://html5doctor.com/drag-and-drop-to-server/

            #region ondrop
            Native.document.body.ondragover +=
                evt =>
                {
                    evt.stopPropagation();
                    evt.preventDefault();

                    evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.


                    page.Header.style.color = JSColor.Green;


                    var types = evt.dataTransfer.types == null ? 0 : evt.dataTransfer.types.Length;

                    if (evt.dataTransfer.types != null)
                        foreach (var type in evt.dataTransfer.types.AsEnumerable())
                        {
                            Console.WriteLine(
                                new { type }
                                );
                        }

                    var items = evt.dataTransfer.items == null ? 0u : evt.dataTransfer.items.length;
                    var files = evt.dataTransfer.files == null ? 0u : evt.dataTransfer.files.length;



                    Console.WriteLine("ondragover: " +
                        new
                        {

                            types,
                            items,
                            files
                        }
                    );
                };


            Native.document.body.ondragleave +=
                delegate
                {
                    page.Header.style.color = JSColor.None;
                };

            #region DetectCanvasFromBytesExperiment
            Action<Form, WebBrowser, string, string, long> DetectCanvasFromBytesExperiment =
                (ff, web, ContentValue, src, ContentBytesLength) =>
                {
                    web.Navigated +=
                           async delegate
                           {
                               if (ContentValue != "png.png")
                                   return;

                               // X:\jsc.svn\examples\javascript\canvas\CanvasFromBytes\CanvasFromBytes\Application.cs
                               //Console.WriteLine("interesting, is it one of ours? " + new { ContentValue });
                               ff.Text = "interesting, is it one of ours? " + new { ContentValue };

                               var csrci = new IHTMLImage { src = src };

                               //await csrci.async.onlo
                               await csrci;

                               if (csrci.width != csrci.height)
                                   return;


                               var w = csrci.width;


                               // do the reverse
                               var z = new CanvasRenderingContext2D(w, w);
                               z.drawImage(csrci, 0, 0, w, w);
                               //z.canvas.AttachToDocument();

                               // whats the bytes?

                               var zbytes = z.bytes;

                               ff.Text = "will decode " + new { zbytes.Length, ContentBytesLength }.ToString();

                               #region decode
                               var decodebytes = await Task.Factory.StartNew(
                                   new { zbytes },
                                   scope =>
                                   {
                                       // Native.Console.WriteLine += ?

                                       // { Length = 2053956, u4 = 3c68746d } 

                                       Console.WriteLine(
                                        new
                                        {
                                            scope.zbytes.Length,

                                            u4 = new[] { 
                                            scope.zbytes[0 * 4 + 0],
                                            scope.zbytes[0 * 4 +1],
                                            scope.zbytes[0 * 4 +2],
                                            scope.zbytes[0 * 4 +3]
                                        }.ToHexString()
                                        }
                                       );


                                       // Uncaught Error: InvalidOperationException: { MethodToken = dAAABv_a4OTKgLfLC20SaJA } function is not available at { href =

                                       var wwbytes = new byte[scope.zbytes.Length / 4];
                                       var wi = 0;

                                       for (int i = 0; i < scope.zbytes.Length; i += 4)
                                       {
                                           // that be the red
                                           //wwbytes[wi] = scope.zbytes[i];

                                           // bet we need alpha
                                           wwbytes[wi] = scope.zbytes[i + 3];
                                           wi++;
                                       }



                                       return wwbytes;
                                   }
                               );
                               #endregion


                               var html = Encoding.UTF8.GetString(decodebytes);

                               ff.Text = "decoded " + new { html.Length, ContentBytesLength }.ToString();

                               //Console.WriteLine(new { html });


                               // um hide old data.
                               web.Hide();

                               var xweb = new WebBrowser { Dock = DockStyle.Fill };
                               xweb.AttachTo(ff);
                               xweb.DocumentText = html;
                               ff.Text = "!decoded " + new { html.Length, ContentBytesLength }.ToString();
                           };

                };
            #endregion


            Native.document.body.ondrop +=
                evt =>
                {
                    //if (evt.dataTransfer == null)
                    //    return;

                    var types = evt.dataTransfer.types == null ? 0 : evt.dataTransfer.types.Length;

                    var items = evt.dataTransfer.items == null ? 0u : evt.dataTransfer.items.length;
                    var files = evt.dataTransfer.files == null ? 0u : evt.dataTransfer.files.length;


                    Console.WriteLine("ondrop: " +
                        new
                        {

                            types,
                            items,
                            files
                        }
                    );


                    page.Header.style.color = JSColor.None;


                    //var xfiles = evt.dataTransfer.files.AsEnumerable().Concat(
                    //    from x in evt.dataTransfer.items.AsEnumerable()
                    //    let f = x.getAsFile()
                    //    where f != null
                    //    select f
                    //);

                    #region DataTable
                    if (evt.dataTransfer.items != null)
                    {
                        // X:\jsc.svn\examples\javascript\DragDataTableIntoCSVFile\DragDataTableIntoCSVFile\Application.cs

                        evt.dataTransfer.items.AsEnumerable().Where(
                            x =>

                                x.type.ToLower() ==

                                // let jsc type system sort it out?
                                // how much reflection does jsc give us nowadays?
                                typeof(DataTable).Name.ToLower()

                        ).WithEach(
                            async x =>
                            {
                                // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dfnReturnLink-0
                                var DataTable_xml = await x.getAsString();

                                var DataTable = StringConversionsForDataTable.ConvertFromString(DataTable_xml);

                                var ff = new Form { Text = new { typeof(DataTable).Name }.ToString() };

                                var g = new DataGridView { DataSource = DataTable, Dock = DockStyle.Fill };

                                ff.Controls.Add(g);


                                ff.Show();

                            }
                        );
                    }
                    #endregion

                    #region files
                    evt.dataTransfer.files.AsEnumerable().WithEachIndex(
                        (f, index) =>
                        {
                            Console.WriteLine(
                                new
                                {

                                    f.name,
                                    f.size,
                                    f.lastModifiedDate
                                }
                            );

                            var ff = new Form();
                            ff.PopupInsteadOfClosing(HandleFormClosing: false);



                            ff.Text = new { f.type, f.name, f.size }.ToString();


                            ff.Show();

                            ff.MoveTo(
                                evt.CursorX + 32 * index,
                                evt.CursorY + 24 * index
                            );

                            var fc = ff.GetHTMLTargetContainer();

                            fc.title = ff.Text;

                            #region image
                            var i = default(IHTMLImage);

                            if (f.type.StartsWith("image/"))
                            {
                                // um would we have a timing issue here?
                                f.ToDataURLAsync(
                                    src =>
                                    {
                                        i = new IHTMLImage { src = src }.AttachTo(fc);
                                        i.style.width = "100%";

                                        i.InvokeOnComplete(
                                            delegate
                                            {

                                                ff.ClientSize = new System.Drawing.Size(
                                                    // keep it reasonable!
                                                    i.width.Min(600),
                                                    i.height.Min(400)
                                                );

                                            }
                                        );
                                    }
                                );
                            }
                            #endregion

                            // http://html5doctor.com/drag-and-drop-to-server/

#if FUTURE
                            service.XUpload(f, delegate { });
#endif


                            var d = new FormData();

                            d.append("foo", f, f.name);

                            var xhr = new IXMLHttpRequest();

                            xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/upload");

                            #region InvokeOnComplete
                            xhr.InvokeOnComplete(
                                delegate
                                {
                                    Console.WriteLine("upload complete!");

                                    SystemSounds.Beep.Play();

                                    //Console.Beep();
                                    XElement.Parse(xhr.responseText).Elements("ContentKey").WithEach(
                                        ContentKey =>
                                        {
                                            var __ContentKey = (Table1_ContentKey)int.Parse(ContentKey.Value);

                                            var web = new WebBrowser { Dock = DockStyle.Fill };

                                            web.Hide();
                                            web.AttachTo(ff);


                                            var src = "/io/" + ContentKey.Value;

                                            if (i == null)
                                            {
                                                web.Show();
                                            }
                                            else
                                            {
                                                web.Navigated +=
                                                    delegate
                                                    {
                                                        i.Orphanize();
                                                        web.Show();
                                                    };
                                            }


                                            // "X:\jsc.svn\examples\javascript\canvas\CanvasFromBytes\png.png"
                                            DetectCanvasFromBytesExperiment(
                                                ff,
                                                web,
                                                 f.name,
                                                src,
                                               (long)f.size
                                            );

                                            web.Navigate(src);


                                            //if (i != null)
                                            //{
                                            //    i.src = src;
                                            //}

                                            __ContentKey.SetLeft(ff.Left);
                                            __ContentKey.SetTop(ff.Top);

                                            ff.LocationChanged +=
                                                delegate
                                                {
                                                    __ContentKey.SetLeft(ff.Left);
                                                    __ContentKey.SetTop(ff.Top);
                                                };

                                            ff.SizeChanged +=
                                                delegate
                                                {
                                                    __ContentKey.SetWidth(ff.Width);
                                                    __ContentKey.SetHeight(ff.Height);
                                                };

                                            ff.FormClosing +=
                                                delegate
                                                {
                                                    __ContentKey
                                                        .Delete();
                                                };


                                            #region onmousewheel
                                            ff.GetHTMLTarget().With(
                                                ffh =>
                                                {
                                                    dynamic ffhs = ffh.style;
                                                    // http://css-infos.net/property/-webkit-transition
                                                    //ffhs.webkitTransition = "webkitTransform 0.3s linear";

                                                    ffh.onmousewheel +=
                                                        e =>
                                                        {
                                                            e.preventDefault();
                                                            e.stopPropagation();


                                                            if (e.WheelDirection > 0)
                                                            {
                                                                ff.Width = (int)(ff.Width * 1.1);
                                                                ff.Height = (int)(ff.Height * 1.1);
                                                            }
                                                            else
                                                            {
                                                                ff.Width = (int)(ff.Width * 0.9);
                                                                ff.Height = (int)(ff.Height * 0.9);
                                                            }

                                                        };

                                                }
                                            );
                                            #endregion

                                        }
                                    );
                                }
                            );
                            #endregion


                            //------WebKitFormBoundaryDmGHAZzeMBbcD5mu
                            //Content-Disposition: form-data; name="foo"; filename="FlashHeatZeeker.UnitPedControl.ApplicationSprite.swf"
                            //Content-Type: application/x-shockwave-flash


                            //------WebKitFormBoundaryDmGHAZzeMBbcD5mu--

                            Console.WriteLine("before upload...");
                            xhr.send(d);
                        }
                    );
                    #endregion


                    // let's disable other handlers
                    //evt.dataTransfer = null;

                    evt.stopPropagation();
                    evt.stopImmediatePropagation();

                    evt.preventDefault();
                };
            #endregion

            #region restore
            {
                var index = 0;

                default(Table1_ContentKey).WithEach(
                    (__ContentKey, ContentBytesLength, ContentValue, Left, Top, Width, Height) =>
                    {

                        var ff = new Form();
                        ff.PopupInsteadOfClosing(HandleFormClosing: false);


                        ff.Text = new { __ContentKey, ContentValue, ContentBytesLength }.ToString();


                        ff.Show();

                        if (Left > 0)
                            ff.MoveTo(
                                Left,
                                Top
                            );
                        else

                            ff.MoveBy(
                                32 * index,
                                24 * index
                            );

                        index++;

                        #region onmousewheel
                        ff.GetHTMLTarget().With(
                            ffh =>
                            {
                                dynamic ffhs = ffh.style;
                                // http://css-infos.net/property/-webkit-transition
                                //ffhs.webkitTransition = "webkitTransform 0.3s linear";

                                ffh.onmousewheel +=
                                    e =>
                                    {
                                        e.preventDefault();
                                        e.stopPropagation();

                                        if (e.WheelDirection > 0)
                                        {
                                            ff.Width = (int)(ff.Width * 1.1);
                                            ff.Height = (int)(ff.Height * 1.1);
                                        }
                                        else
                                        {
                                            ff.Width = (int)(ff.Width * 0.9);
                                            ff.Height = (int)(ff.Height * 0.9);
                                        }

                                    };

                            }
                        );
                        #endregion



                        //var fc = ff.GetHTMLTargetContainer();
                        var src = "/io/" + __ContentKey;

                        //var i = new IHTMLImage { src = src }.AttachTo(fc);
                        //i.style.width = "100%";

                        var web = new WebBrowser { Dock = DockStyle.Fill };

                        web.AttachTo(ff);

                        //script: error JSC1000: No implementation found for this native method, please implement [System.Windows.Forms.WebBrowser.add_DocumentCompleted(System.Windows.Forms.WebBrowserDocumentCompletedEventHandler)]
                        //script: warning JSC1000: Did you reference ScriptCoreLib via IAssemblyReferenceToken?
                        //script: error JSC1000: error at DropFileIntoSQLite.Application+<>c__DisplayClass2e.<.ctor>b__15,
                        // assembly: V:\DropFileIntoSQLite.Application.exe
                        // type: DropFileIntoSQLite.Application+<>c__DisplayClass2e, DropFileIntoSQLite.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

                        //web.DocumentCompleted +=
                        //    delegate
                        //    {



                        //};

                        DetectCanvasFromBytesExperiment(
                            ff,
                            web,
                            ContentValue,
                            src,
                            ContentBytesLength
                        );


                        web.Navigate(src);

                        if (Width > 0)
                            ff.SizeTo(
                               Width,
                               Height
                           );
                        //else
                        //    i.InvokeOnComplete(
                        //        delegate
                        //        {


                        //            ff.ClientSize = new System.Drawing.Size(i.width, i.height);

                        //        }
                        //    );

                        ff.LocationChanged +=
                            delegate
                            {
                                __ContentKey.SetLeft(ff.Left);
                                __ContentKey.SetTop(ff.Top);
                            };

                        ff.SizeChanged +=
                            delegate
                            {
                                __ContentKey.SetWidth(ff.Width);
                                __ContentKey.SetHeight(ff.Height);
                            };

                        ff.FormClosing +=
                            delegate
                            {
                                __ContentKey.Delete();
                            };
                    }
                );
            }
            #endregion



            // can we write about this?
            #region bookmark launcher
            var href = @"javascript:
((function(h,i)
{ 
    

    var a=-1, 
    b='onreadystatechange', 
    c=document.getElementsByTagName('HEAD')[0], 
    d, 
    e, 
    f, 
    g=c.childNodes, 
    d; 

    e=document.createElement('base');   
    e.href='%%';
    c.appendChild(e);     

    d = function () 
    {  
        next: while (1)  
        {   
            a++;     
            if (a ==h.length)   
            {   
                i();    
                return;   
            }     

            /*
            for (f=0;f<g.length;f++)   
            {   
                var v =g[f];    
                var w =h[a];       

                if (v.nodeName =='SCRIPT')    
                    if (v.src ==w || v.src.substr(v.src.length - w.length - 1,w.length + 1) =='/' + w)    
                        continue next;   
            } */      
            e=document.createElement('SCRIPT');   
            e.src='%%' + h[a];     
            e[b in e?b:'onload']=  function()    
            {       
                var f=e.readyState;    
                if(f==null||f=='loaded'||f=='complete')     
                    d();    
            };  
 
        c.appendChild(e);     
        return;  
    } 
}; 
d();

}

)(['view-source'],function(){}))".Replace("%%", Native.Document.location + "");

            page.Header.draggable = true;
            page.Header.ondragstart +=
                e =>
                {
                    e.dataTransfer.setData("text/uri-list", href);
                };


            IStyleSheet.Default["#Header:hover"].style.color = "red";
            IStyleSheet.Default["#Header:hover"].style.cursor = IStyle.CursorEnum.pointer;

            #endregion


            new About().Show();
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {


            GrayScaleRule.InitializeGrayScaleFor("CLRForm");


            #region AddCLRForm
            Func<Form> AddCLRForm = delegate
            {
                var f = new Form();

                f.GetHTMLTarget().className = "CLRForm";

                f.Text = "CSS filter shader";

                #region WhileDragging
                Native.window.requestAnimationFrame +=
                    delegate
                    {
                        if (f.Capture)
                        {
                            f.GetHTMLTarget().className = "";
                            f.Text = "CSS filter shader (dragging)";
                        }
                        else
                        {
                            f.GetHTMLTarget().className = "CLRForm";
                            f.Text = "CSS filter shader";

                        }
                    };
                #endregion

                var i = new WebBrowser
                {
                    //Url = new Uri("/jsc"), 

                    Dock = DockStyle.Fill
                };

                i.AttachTo(f);

                f.Show();

                i.Navigate("/jsc");

                return f;
            };
            #endregion


            AddCLRForm().MoveBy(0, 0);

            FormStyler.AtFormCreated = FormStyler.LikeVisualStudioMetro;

            AddCLRForm().MoveBy(32, 16);

            FormStyler.AtFormCreated =
                s =>
                {

                    FormStyler.LikeVisualStudioMetro(s);

                    s.TargetOuterBorder.style.borderColor = ScriptCoreLib.JavaScript.Runtime.JSColor.Red;
                    s.Caption.style.backgroundColor = ScriptCoreLib.JavaScript.Runtime.JSColor.Red;
                    s.TargetOuterBorder.style.boxShadow = "rgba(255, 0, 0, 0.3) 0px 0px 6px 3px";
                };

            AddCLRForm().MoveBy(64, 32);

            //f.GotFocus +=
            //    delegate
            //    {
            //        f.Text = "GotFocus";
            //    };

            //f.LostFocus +=
            //  delegate
            //  {
            //      f.Text = "LostFocus";
            //  };

            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.WebMethod2(
                @"A string from JavaScript.",
                value => value.ToDocumentTitle()
            );
        }