/// <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)
        {
            sprite.wmode();

            sprite.AttachSpriteToDocument().With(
                   embed =>
                   {
                       embed.style.SetLocation(0, 0);
                       embed.style.SetSize(Native.Window.Width, Native.Window.Height);

                       Native.Window.onresize +=
                           delegate
                           {
                               embed.style.SetSize(Native.Window.Width, Native.Window.Height);
                           };
                   }
               );


            #region con
            var con = new ConsoleForm();

            con.InitializeConsoleFormWriter();

            con.Show();

            con.Height = 150;
            con.Left = Native.Window.Width - con.Width;
            con.Top = 0;

            Native.Window.onresize +=
                  delegate
                  {
                      con.Left = Native.Window.Width - con.Width;
                      con.Top = 0;
                  };


            con.Opacity = 0.6;




            // !! not compatible yet

            con.HandleFormClosing = false;
            con.PopupInsteadOfClosing();
            #endregion



            sprite.fps +=
                (fps, nid) =>
                {
                    new { fps, nid }.ToString().ToDocumentTitle();
                };


            #region context_new_remotegame
            sprite.context_new_remotegame +=
                remotegame =>
                {
                    var remotegame_con = new ConsoleForm();

                    remotegame_con.Show();
                    remotegame_con.Left = 0;
                    remotegame_con.Top = Native.Window.Height - remotegame_con.Height;

                    remotegame_con.Opacity = 0.5;

                    remotegame.AtTitleChange +=
                        e => remotegame_con.Text = e;

                    remotegame.AtWriteLine +=
                        e =>
                        {
                            remotegame_con.textBox1.AppendText(e + Environment.NewLine);
                            remotegame_con.textBox1.ScrollToCaret();
                        };


                    remotegame_con.HandleFormClosing = false;
                    remotegame_con.PopupInsteadOfClosing();
                };
            #endregion


            var sprites_events = new BindingListWithEvents<ApplicationSprite>();
            var sprites = sprites_events.Source;

            sprites_events.Added +=
                (fsprite, i) =>
                {
                    Console.WriteLine(i + "# Console ready!");

                    fsprite.InitializeConsoleFormWriter(
                        Console_Write: x => Console.Write(x),
                        Console_WriteLine: x =>
                            {
                                var lines = x.Split(Environment.NewLine);

                                foreach (var item in lines)
                                {
                                    Console.WriteLine(i + "# " + item);
                                }
                            }
                    );

                    #region lets do two way binding here.



                    // fsprite -> sprite
                    fsprite.context_onmessage += xml =>
                    {
                        // script: error JSC1000: No implementation found for this native method, please implement [static System.Linq.Enumerable.Except(System.Collections.Generic.IEnumerable`1[[FlashHeatZeekerWithStarlingB2.ApplicationSprite, FlashHeatZeekerWithStarlingB2.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Collections.Generic.IEnumerable`1[[FlashHeatZeekerWithStarlingB2.ApplicationSprite, FlashHeatZeekerWithStarlingB2.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]])]

                        sprites.WithEach(
                            x =>
                            {
                                // prevent echo
                                if (x == fsprite)
                                    return;

                                x.game_postMessage(xml);
                            }
                        );
                    };

                    #endregion
                };


            sprites.Add(sprite);

            #region game_InitializeFrameDiagnostics
            sprite.game_InitializeFrameDiagnostics(
                __FrameDiagnostics =>
                {
                    Console.WriteLine("new FrameDiagnostics");

                    var x = new FrameDiagnostics();

                    x.Show();

                    Console.WriteLine("new FrameDiagnostics Show, can you see it?");


                    Native.Window.onresize +=
                      delegate
                      {
                          x.Left = Native.Window.Width - x.Width;
                          x.Top = Native.Window.Height - x.Height;
                      };


                    x.Initialize(__FrameDiagnostics);

                    // Error	8	'Abstractatech.ConsoleFormPackage.Library.ConsoleForm' does not contain a definition for 'PopupInsteadOfClosing' and no extension method 'PopupInsteadOfClosing' accepting a first argument of type 'Abstractatech.ConsoleFormPackage.Library.ConsoleForm' could be found (are you missing a using directive or an assembly reference?)	X:\jsc.svn\examples\actionscript\svg\FlashHeatZeeker\FlashHeatZeekerWithStarlingB2\Application.cs	85	17	FlashHeatZeekerWithStarlingB2
                    // wtf?
                    x.PopupInsteadOfClosing();
                    x.Opacity = 0.7;

                    // can we pop it up?


                    x.JoinMultiplayer.Click +=
                        delegate
                        {
                            var f = new Form();
                            // make it small
                            f.Height = 200;

                            var fsprite = new ApplicationSprite();
                            fsprite.src_fixup();
                            fsprite.wmode();


                            var fspriteelement = fsprite.AttachSpriteTo(
                                f.GetHTMLTargetContainer()
                            );

                            #region ClientSizeChanged / PopupInsteadOfClosing has a bug
                            f.ClientSizeChanged +=
                                delegate
                                {
                                    var cs = f.ClientSize;

                                    fspriteelement.style.SetSize(cs.Width,
                                        cs.Height
                                    );
                                };
                            #endregion

                            f.Show();
                            f.PopupInsteadOfClosing();

                            // do events break if popup mode is changed?
                            fsprite.fps +=
                                  (fps, nid) =>
                                  {
                                      new { fps, nid }.ToString().ToTitle(f);
                                  };




                            sprites.Add(fsprite);
                            // what if we have more of these?
                        };
                }
            );
            #endregion








        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="document">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp document)
        {
            // 
            //document.body.AsXElement().Elements("script").Remove();
            //document.body.AsXElement().Elements("script").WithEach(k => k.Remove());

            var f = new Form { Text = "Visual Editor" };

            f.PopupInsteadOfClosing(HandleFormClosing: true);

            f.Width = 600;

            var diagnostics = new IHTMLDiv().AttachTo(document.body.parentNode);
            //var diagnostics = new IHTMLBody().AttachTo(Native.document.body.parentNode);

            diagnostics.style.backgroundColor = "rgba(0, 0, 0, 0)";
            diagnostics.style.position = IStyle.PositionEnum.absolute;
            diagnostics.style.overflow = IStyle.OverflowEnum.hidden;

            diagnostics.style.left = "0px";
            diagnostics.style.top = "-100%";
            diagnostics.style.width = "100%";
            diagnostics.style.height = "100%";



            f.Show();
            f.GetHTMLTarget().AttachTo(diagnostics);

            //Uncaught TypeError: Cannot call method 'write' of null 
            var editor = new TextEditor(f.GetHTMLTargetContainer());

            var snd = new HTML.Audio.FromAssets.SAMPLES036();
            snd.load();

            var snd2 = new HTML.Audio.FromAssets.Hammertime();
            snd2.load();


            Action reverse = delegate { };

            Action Hide =
                delegate
                {
                    //
                    (document.body.style as dynamic).webkitFilter = "";

                    diagnostics.style.top = "-100%";
                    diagnostics.style.backgroundColor = "rgba(0, 0, 0, 0)";

                    snd2.play();
                    snd2 = new HTML.Audio.FromAssets.Hammertime();
                    snd2.load();

                    reverse();
                };

            Action Show =
                delegate
                {
                    if (diagnostics.style.top != "-100%")
                        return;

                    // { -webkit-filter: grayscale(0.5) blur(10px);
                    (document.body.style as dynamic).webkitFilter = "grayscale(0.5) blur(2px)";

                    diagnostics.style.top = "0%";
                    diagnostics.style.backgroundColor = "rgba(0, 0, 0, 0.5)";


                    snd.play();
                    snd = new HTML.Audio.FromAssets.SAMPLES036();
                    snd.load();


                    // using undo context? save load and store ops to revert them
                    editor.InnerHTML = document.body.innerHTML;

                    reverse = delegate
                    {
                        document.body.innerHTML = editor.InnerHTML;

                        reverse = delegate { };
                    };
                };



            Hide();

            // http://www.w3schools.com/css3/css3_transitions.asp
            diagnostics.style.transition = "all 0.2s ease-in-out";




            Action Toggle =
                delegate
                {
                    if (diagnostics.style.top != "-100%")
                    {
                        Hide();

                    }
                    else
                    {
                        Show();

                    }
                };

            diagnostics.onclick +=
                e =>
                {
                    if (e.Element == diagnostics)
                        Hide();

                };

            Action<IEvent> AtKeyCode =
               e =>
               {
                   var KeyCode = e.KeyCode;

                   new { KeyCode }.ToString().ToDocumentTitle();

                   if (KeyCode == 27)
                   {
                       e.preventDefault();
                       e.stopPropagation();

                       Hide();

                   }


                   // e
                   if (KeyCode == 69)
                   {
                       e.preventDefault();
                       e.stopPropagation();

                       Show();

                   }

                   // US
                   if (KeyCode == 222)
                   {
                       e.preventDefault();
                       e.stopPropagation();


                       Toggle();
                   }
                   // EE
                   if (KeyCode == 192)
                   {
                       e.preventDefault();
                       e.stopPropagation();


                       Toggle();
                   }
               };

            // rosyln could pick up change requests from comments
            // should not see this event for popup action
            //f.FormClosing +=
            //    (s, e) =>
            //    {
            //        e.Cancel = true;

            //        //Hide();
            //    };

            Native.document.onkeyup +=
                e =>
                {
                    AtKeyCode(e);
                };

            // what if it is reloaded? popup
            editor.Document.WhenContentReady(
                delegate
                {
                    editor.Document.onkeyup += e => AtKeyCode(e);
                }
            );


         
        }
        public ApplicationContent(
            IApp page,
            Abstractatech.JavaScript.FileStorage.IApplicationWebServiceX service,
            bool DisableBackground = false

            )
        {


            FormStyler.AtFormCreated = FormStylerLikeFloat.LikeFloat;

            if (!DisableBackground)
            {
                #region  I want animated background!

                WebGLClouds.Application.Loaded +=
                    a =>
                    {
                        Native.Document.body.parentNode.insertBefore(
                             a.container.Orphanize(),
                              Native.Document.body
                        );
                        a.container.style.position = IStyle.PositionEnum.@fixed;

                    };


                new WebGLClouds.Application();
                #endregion
            }

            //var minsize = new IHTMLDiv().AttachToDocument();

            //minsize.style.SetSize(4000, 2000);




            var f = new Form
            {
                Text = "My Files",
                StartPosition = FormStartPosition.Manual,
                SizeGripStyle = SizeGripStyle.Hide
            };

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

            };

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

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


                    if (Native.window.Width < 1024)
                        // docked?
                        if (ff.GetHTMLTarget().parentNode != null)
                            Native.window.scrollTo(ff.Left - 8, ff.Top - 8, TimeSpan.FromMilliseconds(300));

                };



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

                        Native.window.scrollTo(0, 0, TimeSpan.FromMilliseconds(200));

                        ff.Text = "...";

                        "Web Files".ToDocumentTitle();

                        return;
                    }

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

                    ff.Text.ToDocumentTitle();


                };

            ff.FormClosing +=
                (sender, e) =>
                {
                    Console.WriteLine(new { e.CloseReason });

                    if (e.CloseReason == CloseReason.UserClosing)
                    {
                        e.Cancel = true;

                        w.Navigate("about:blank");
                    }

                };
            #endregion



            var content = f.GetHTMLTargetContainer();




            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)";


            #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, 64).SizeTo(hh.LeftContainer.clientWidth - 32, Native.window.Height - 128);


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

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

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


            //hh.Split.LeftScrollable = new IHTMLDiv { className = "SidebarForButtons" };


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

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160108
            //f.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);
            //ff.PopupInsteadOfClosing(SpecialNoMovement: true, HandleFormClosing: false, NotifyDocked: AtResize);


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

            layout.Container.AttachTo(content);

            Abstractatech.JavaScript.FileStorage.ApplicationContent.Target = "view";


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







            "Web Files".ToDocumentTitle();
        }
        /// <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();
        }
        public static void InitializeContent()
        {
            #region tutorial step 2
            #region arena
            var map = new Point(2000, 2000);

            var arena = new ArenaControl();

            arena.Layers.Canvas.style.backgroundColor =
                Color.FromGray(0xc0);
            arena.SetLocation(
                Rectangle.Of(0, 0, Native.window.Width, Native.window.Height));

            arena.SetCanvasSize(map);

            arena.Control.AttachToDocument();


            arena.DrawTextToInfo(Title, new Point(8, 8), Color.Blue);

            Native.window.onresize +=
                delegate
                {
                    arena.SetLocation(
                        Rectangle.Of(0, 0, Native.window.Width, Native.window.Height));

                    arena.SetCanvasPosition(
                        arena.CurrentCanvasPosition
                        );
                };
            #endregion
            #endregion


            var pending = default(Dude2);

            #region arsenal
            var arsenal = new Dictionary<string, DudeAnimationInfo>
            {
                {"Soldier", 
                    new DudeAnimationInfo 
                    { 
                        Frames_Stand = Frames.WolfSoldier,
                        Frames_Walk = Frames.WolfSoldier_Walk
                    }
                },
                {"Imp", 
                    new DudeAnimationInfo 
                    { 
                        Frames_Stand = Frames.DoomImp,
                        Frames_Walk = Frames.DoomImp_Walk
                    }
                }
            };
            #endregion


            #region tutorial step 3

            Func<DudeAnimationInfo, Point, Dude2> CreateActor =
                (_frames, _coords) =>
                {
                    var actor = new Dude2();

                    actor.Frames = _frames.Frames_Stand;
                    actor.AnimationInfo.Frames_Stand = _frames.Frames_Stand;
                    actor.AnimationInfo.Frames_Walk = _frames.Frames_Walk;
                    actor.Zoom.DynamicZoomFunc = a => 1;
                    actor.SetSize(48, 72);
                    actor.TeleportTo(_coords.X, _coords.Y);
                    actor.Zoom.StaticZoom = DefaultActiorZoom;
                    actor.Direction = Math.PI * 0.5;
                    actor.Control.AttachTo(arena.Layers.Canvas);
                    //actor.HasShadow = _frames.Frames_Stand.Length > 1;
                    if (_frames.Frames_Stand.Length == 1)
                        actor.Shadow.style.Opacity = 0.4;
                    actor.AnimationInfo.WalkAnimationInterval = 1000 / 30;
                    return actor;
                };

            var actors = new List<Dude2>
            {

            };

            var selection = from i in actors
                            where i.IsSelected
                            select i;

            arena.ApplySelection +=
                (rect, ev) =>
                {
                    if (pending != null)
                        return;

                    foreach (var v in actors)
                        v.IsSelected = rect.Contains(v.CurrentLocation.ToInt32());
                };

            var Argh = new Argh();
            var Affirmative = new Affirmative();
            var ghoullaugh = new ghoullaugh();
            var sheep = new sheep();
            var pig = new pig();
            var click = new click().AttachToDocument();

            arena.SelectionClick +=
                (p, ev) =>
                {
                    if (pending != null)
                        return;

                    foreach (var v in selection)
                    {
                        if (v.AnimationInfo.Frames_Stand[0].Source == MyFrames.ManWithHorns.Frames_Stand[0].Source)
                        {
                            ghoullaugh.play();
                            ghoullaugh = new ghoullaugh();
                        }
                        else if (v.AnimationInfo.Frames_Stand[0].Source == MyFrames.ThePig.Frames_Stand[0].Source)
                        {
                            pig.play();
                            pig = new pig();
                        }
                        else if (v.AnimationInfo.Frames_Stand[0].Source == MyFrames.TheSheep.Frames_Stand[0].Source)
                        {
                            sheep.play();
                            sheep = new sheep();
                        }
                        else if (v.AnimationInfo.Frames_Stand[0].Source == Frames.WolfSoldier[0].Source)
                        {
                            Affirmative.play();
                            Affirmative = new Affirmative();
                        }
                        else
                        {
                            Argh.play();
                            Argh = new Argh();
                        }



                        v.WalkTo(p.ToDouble());

                        // move in group formation
                        p.X += 16;
                        p.Y += 16;
                    }
                };


            #endregion

            #region tutorial step 4



            #region CreateDialogAt
            var CreateDialogAt =
                new
                {
                    //Dialog = default(IHTMLDiv),
                    Content = default(IHTMLDiv),
                    Width = default(string)
                }
                .ToFunc(
                (Point pos, string width) =>
                {
                    var f = new Form();

                    f.Show();

                    f.SizeTo(200, 200);


                    // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20151115/audio
                    //f.PopupInsteadOfClosing();

                    f.MoveTo(pos.X, pos.Y);
                    //f.SizeTo(


                    //var dialog = new IHTMLDiv();

                    //dialog.style.SetLocation(pos.X, pos.Y);

                    //dialog.style.backgroundColor = Color.Gray;
                    //dialog.style.padding = "1px";

                    //var caption = new IHTMLDiv().AttachTo(dialog);

                    //caption.style.backgroundColor = Color.Blue;
                    //caption.style.width = width;
                    //caption.style.height = "0.5em";
                    //caption.style.cursor = IStyle.CursorEnum.move;

                    //var drag = new DragHelper(caption);

                    //drag.Position = pos;
                    //drag.Enabled = true;
                    //drag.DragMove +=
                    //    delegate
                    //    {
                    //        dialog.style.SetLocation(drag.Position.X, drag.Position.Y);
                    //    };

                    var _content = new IHTMLDiv().AttachTo(f.GetHTMLTargetContainer());

                    _content.style.textAlign = IStyle.TextAlignEnum.center;
                    _content.style.backgroundColor = Color.White;
                    _content.style.padding = "1px";

                    //dialog.AttachToDocument();

                    return new
                    { //Dialog = dialog,
                        Content = _content,
                        Width = width
                    };
                }
            );
            #endregion

            #region dialog
            var toolbar = CreateDialogAt(new Point(2, 2), "8em");

            var combo = new IHTMLSelect();
            var build = new IHTMLButton();

            build.style.SetSize(72, 72);
            build.style.padding = "0px";

            var avatar = new IHTMLImage().AttachTo(build);
            var remove = new IHTMLButton("Remove");


            combo.AttachTo(toolbar.Content);
            new IHTMLBreak().AttachTo(toolbar.Content);
            build.AttachTo(toolbar.Content);
            new IHTMLBreak().AttachTo(toolbar.Content);
            remove.AttachTo(toolbar.Content);
            new IHTMLBreak().AttachTo(toolbar.Content);
            #endregion


            #region GetSelectedArsenal
            Func<DudeAnimationInfo> GetSelectedArsenal =
                () =>
                {
                    if (arsenal.ContainsKey(combo[combo.selectedIndex].value))
                        return arsenal[combo[combo.selectedIndex].value];

                    return null;
                };
            #endregion

            Action Refresh =
                delegate
                {
                    var i = GetSelectedArsenal();

                    if (i != null)
                        avatar.src = i.Images.Random().src;
                };

            combo.Add(arsenal.Keys.ToArray());
            Refresh();

            combo.onchange +=
                delegate
                {
                    Refresh();



                    click.play();
                    click = new click().AttachToDocument();
                };

            #region pending actor

            arena.MouseMove +=
                p =>
                {
                    if (pending == null)
                        return;

                    pending.TeleportTo(p.X, p.Y);
                };

            arena.Layers.User.oncontextmenu +=
                e =>
                {
                    e.preventDefault();

                    if (pending != null)
                    {
                        pending.Control.Orphanize();
                        pending = null;
                        arena.ShowSelectionRectangle = true;

                        return;
                    }

                    actors.ForEach(
                        k => k.IsSelected = false
                            );
                };

            arena.SelectionClick +=
                (p, ev) =>
                {
                    if (pending == null)
                    {

                        return;
                    }

                    pending.TeleportTo(p.X, p.Y);

                    actors.Add(pending);

                    pending.IsHot = false;


                    var x = GetSelectedArsenal();
                    pending = CreateActor(x,
                       new Point(
                           Native.window.Width / 2,
                           Native.window.Height / 2
                           )
                   );

                    pending.IsHot = true;


                    click.play();
                    click = new click().AttachToDocument();
                };

            build.onclick +=
                delegate
                {
                    if (pending != null)
                    {
                        pending.Control.Orphanize();
                        pending = null;

                        return;
                    }

                    var x = GetSelectedArsenal();

                    pending = CreateActor(x,
                        new Point(
                            Native.window.Width / 2,
                            Native.window.Height / 2
                            )
                    );

                    pending.IsHot = true;
                    arena.ShowSelectionRectangle = false;

                    click.play();
                    click = new click().AttachToDocument();
                };
            #endregion

            remove.onclick +=
                delegate
                {
                    foreach (var v in selection.ToArray())
                    {
                        v.Control.Orphanize();
                        actors.Remove(v);
                    }


                    click.play();
                    click = new click().AttachToDocument();
                };

            #endregion

            if (FilterToImpAndSoldier)
            { }
            else
            {
                #region step 6

                {
                    var n = "NPC";

                    arsenal.Add(n, MyFrames.NPC3);
                    combo.Add(n);
                }

                #endregion


                {
                    var n = "ManWithHorns";

                    arsenal.Add(n, MyFrames.ManWithHorns);
                    combo.Add(n);
                }
                {
                    var n = "TheSheep";

                    arsenal.Add(n, MyFrames.TheSheep);
                    combo.Add(n);
                }
                {
                    var n = "ThePig";

                    arsenal.Add(n, MyFrames.ThePig);
                    combo.Add(n);
                }

                {
                    var n = "TheCactus";

                    arsenal.Add(n, MyFrames.TheCactus);
                    combo.Add(n);
                }
            }


            if (BeforeAddingDebris != null)
                BeforeAddingDebris(arena.Layers.Canvas);

            3.Times(
              delegate()
              {
                  new DebrisImages().Images.ForEach(
                      img => img.AttachTo(arena.Layers.Canvas).style.SetLocation(map.X.Random(), map.Y.Random())
                  );
              }
      );

            16.Times(
                delegate()
                {
                    actors.Add(
                        CreateActor(arsenal.Random().Value, new Point(map.X.Random(), map.Y.Random()))
                        );
                }
            );
        }
        /// <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);

        }
            public a(IBeforeLogin ee)
            {
                //FormStyler.AtFormCreated = FormStyler.LikeVisualStudioMetro;
                //FormStyler.AtFormCreated = FormStylerLikeFloat.LikeFloat;

                var ff = new Form { FormBorderStyle = FormBorderStyle.None };


                var ScrollArea = new App().ScrollArea.AttachTo(ff.GetHTMLTargetContainer());



                //ScrollArea.style.backgroundColor = "#185D7B";
                //ScrollArea.style.backgroundColor = "#185D7B";
                ScrollArea.style.backgroundColor = "#105070";

                var SidebarWidth = 172;

                ff.MoveTo(SidebarWidth, 0);

                Action AtResize = delegate
                {

                    ff.SizeTo(Native.window.Width - SidebarWidth, Native.window.Height);
                };

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

                    };

                AtResize();
                var iii = global::CSSMinimizeFormToSidebar.ApplicationExtension.InitializeSidebarBehaviour(
                  ff,

                  // should be handle close instead!
                  HandleClosed: true,
                  HandleDragToLeft: false
                );

                iii.SidebarText.className = "AppPreviewText";
                //iii.SidebarText.innerText = "My Appz";
                //iii.SidebarText.innerText = "Synchronizing...";
                //var finish = iii.SidebarText.ToASCIIStyledLoadAnimation("My Appz");


                //Native.Document.body.style.backgroundColor = "#105070";
                Native.document.body.style.backgroundColor = "#185D7B";

                Native.window.onresize +=
                    delegate
                    {
                        // lets not centerize
                        //ff.Show();
                    };


                //var page = new App();

                //page.ScrollArea.AttachToDocument();

                var count = 0;

                var yield_BringToFront = false;

                var icon_throttle = 0;

                #region yield
                yield_ACTION_MAIN yield = (
                            packageName,
                            name,
                            __IsCoreAndroidWebServiceActivity,
                            label
                        ) =>
                {

                    if (string.IsNullOrEmpty(label))
                        label = packageName;

                    var IsCoreAndroidWebServiceActivity = System.Convert.ToBoolean(__IsCoreAndroidWebServiceActivity);

                    count++;

                    var a = new AppPreview();

                    #region icon
                    if (packageName != "foo")
                    {
                        // see also: X:\jsc.svn\examples\javascript\ImageCachedIntoLocalStorageExperiment\ImageCachedIntoLocalStorageExperiment\Application.cs

                        // extension to the system
                        // data.icon[packageName].With

                        Action loadicon = delegate
                        {
                            new ScriptCoreLib.JavaScript.Runtime.Timer(
                                delegate
                                {
                                    new IHTMLImage { src = "/icon/" + packageName }.InvokeOnComplete(
                                        i =>
                                        {
                                            var dataURL = i.toDataURL();

                                            // Uncaught QuotaExceededError: An attempt was made to add something to storage that exceeded the quota. 
                                            // http://stackoverflow.com/questions/6276282/how-can-i-request-an-increase-to-the-html5-localstorage-size-on-ipad-like-the-f

                                            //message: "An attempt was made to add something to storage that exceeded the quota."
                                            //name: "QuotaExceededError"



                                            a.Icon.src = dataURL;

                                            try
                                            {
                                                Native.window.localStorage[new { packageName }] = dataURL;
                                            }
                                            catch (Exception err)
                                            {
                                                Console.WriteLine(new { packageName, error = new { err.Message } });
                                            }
                                        }
                                    );
                                }
                            ).StartTimeout(icon_throttle);
                        };

                        // VirtualDictionary?
                        Native.window.localStorage[new { packageName }].With(
                            dataURL =>
                            {
                                Console.WriteLine("load from localstorage: " + new { packageName });

                                a.Icon.src = dataURL;

                                loadicon = delegate { };
                            }
                        );

                        loadicon();

                        icon_throttle += 900;

                    }
                    #endregion


                    //a.Icon.src = "/icon/" + packageName;

                    //a.Icon.src = "data:image/png;base64," + icon_base64;
                    a.Label.innerText = label;

                    if (yield_BringToFront)
                    {
                        Console.WriteLine("yield_BringToFront " + new { packageName });

                        ScrollArea.insertBefore(a.Container, ScrollArea.firstChild);
                    }
                    else
                    {
                        a.Container.AttachTo(ScrollArea);
                    }


                    //(page.gauge_layer1.style as dynamic).webkitTransition = "-webkit-transform 0.7s ease-in";

                    //-webkit-transition: filter 0.3s linear;
                    __Form __ff = ff;
                    (__ff.HTMLTarget.style as dynamic).webkitTransition = "-webkit-filter 0.7s ease-in";


                    #region onclick
                    Action<bool> onclick =
                        CanAutoLaunch =>
                        {


                            Console.WriteLine(new { label });
                            var content = new windows.ApplicationControl();


                            var f = new Form { Text = label, ShowIcon = false };
                            f.ClientSize = content.Size;

                            f.FormClosed +=
                                delegate
                                {
                                    (__ff.HTMLTarget.style as dynamic).webkitFilter = "blur(0px) brightness(1.0)";
                                };

                            f.Shown += delegate
                            {
                                ;
                                (__ff.HTMLTarget.style as dynamic).webkitFilter = "blur(4px) brightness(0.8)";
                            };

                            f.Show();


                            //FormAsPopupExtensionsForConsoleFormPackage.PopupInsteadOfClosing(
                            //    f,
                            //    HandleFormClosing: false,

                            //    NotifyDocked:
                            //        delegate
                            //        {
                            //            (__ff.HTMLTarget.style as dynamic).webkitFilter = "blur(4px) brightness(0.8)";
                            //        },

                            //        NotifyFloat:
                            //         delegate
                            //         {
                            //             (__ff.HTMLTarget.style as dynamic).webkitFilter = "blur(0px)  brightness(1.0)";
                            //         },
                            //    SpecialCloseOnLeft: delegate
                            //    {
                            //        Console.WriteLine("SpecialCloseOnLeft");

                            //        service.Launch(
                            //            packageName,
                            //            name,
                            //            DisableCallbackToken: "true"
                            //        );

                            //        //f.Close();
                            //    }
                            //);

                            if (CanAutoLaunch && IsCoreAndroidWebServiceActivity)
                            {

                                f.Opacity = 0.5;

                                var w = new WebBrowser();
                                w.Dock = DockStyle.Fill;

                                f.Controls.Add(w);

                                service.Launch(
                                    packageName,
                                    name,

                                    yield_port:
                                    // we should remember the port
                                    // to launch it offline via AppCache
                                        port =>
                                        {
                                            Console.WriteLine(new { port });

                                            // close to left sidebar!
                                            // broken?
                                            //ff.Close();


                                            f.Opacity = 1.0;

                                            var uri = Native.document.location.protocol
                                                + "//"
                                                + Native.document.location.host.TakeUntilIfAny(":")
                                                + ":" + port;

                                            //w.Navigated +=
                                            //    delegate
                                            //    {
                                            //        Console.WriteLine("WebBrowser Navigated " + new { packageName, uri, Abstractatech.JavaScript.FormAsPopup.FormAsPopupExtensionsForConsoleFormPackageMediator.InternalPopupHasFrame });

                                            //        // FormAsPopupExtensionsForConsoleFormPackageMediator

                                            //        if (Abstractatech.JavaScript.FormAsPopup.FormAsPopupExtensionsForConsoleFormPackageMediator.InternalPopupHasFrame)
                                            //        {

                                            //        }
                                            //    };

                                            w.Navigate(uri);

                                            f.ClientSize = content.Size;
                                        }
                                );
                            }
                            else
                            {
                                f.Controls.Add(content);
                                content.Dock = DockStyle.Fill;




                                content.Label.Text = label;
                                content.Package.Text = packageName;

                                //a.Icon.cloneNode(true).AttachTo(

                                //    ScriptCoreLib.JavaScript.Windows.Forms.Extensions.GetHTMLTargetContainer(content.Icon)

                                //);

                                content.Uninstall.Click +=
                                    delegate
                                    {
                                        service.Remove(
                                           packageName,
                                           name
                                        );

                                        //f.Hide();

                                        // http://www.w3schools.com/cssref/pr_text_text-decoration.asp
                                        a.Label.style.textDecoration = "line-through";

                                        f.Close();
                                    };

                                content.Launch.Click +=
                                    delegate
                                    {
                                        // level 1
                                        // run on android

                                        // level 2
                                        // run as float

                                        // level 3 
                                        // run here as iframe

                                        // level 4
                                        // run here as js import

                                        service.Launch(
                                            packageName,
                                            name,

                                            yield_port:
                                                port =>
                                                {
                                                    Console.WriteLine(new { port });
                                                    // close to left sidebar!
                                                    ff.Close();


                                                    var uri = Native.Document.location.protocol
                                                        + "//"
                                                        + Native.Document.location.host.TakeUntilIfAny(":")
                                                        + ":" + port;

                                                    var w = new WebBrowser();

                                                    f.Controls.Add(w);
                                                    w.Dock = DockStyle.Fill;
                                                    w.Navigate(uri);

                                                    f.ClientSize = content.Size;
                                                }
                                        );

                                    };
                            }
                        };
                    #endregion

                    a.Clickable.oncontextmenu +=
                       e =>
                       {
                           e.preventDefault();

                           onclick(false);
                       };

                    a.Clickable.onclick +=
                        e =>
                        {
                            e.preventDefault();

                            onclick(true);
                        };

                };
                #endregion


                #region more
                var skip = 0;
                var take = 32;



                {


                    Action done = delegate { };


                    Action MoveNext = delegate
                    {
                        icon_throttle = 0;

                        //more.disabled = true;
                        //more.innerText = "checking for more...";

                        Console.WriteLine("MoveNext: " + new { skip, take });

                        service.queryIntentActivities(
                            yield,
                            skip: "" + skip,
                            take: "" + take,
                            yield_done: done

                        );


                        //service.File_list("",
                        //    ydirectory: ydirectory,
                        //    yfile: yfile,
                        //    sskip: skip.ToString(),
                        //    stake: take.ToString(),
                        //    done: done
                        //);

                        skip += take;

                    };

                    done = delegate
                    {
                        //more.innerText = getmore;
                        //more.disabled = false;

                        if (count == skip)
                        {
                            //Native.Document.body.With(
                            //     body =>
                            //     {
                            //         if (more.disabled)
                            //             return;

                            //         if (body.scrollHeight - 1 <= Native.Window.Height + body.scrollTop)
                            //         {
                            MoveNext();
                            //          }

                            //      }
                            //);
                        }
                        else
                        {
                            //finish();
                            yield_BringToFront = true;

                            service.oninstall(yield);

                        }
                    };



                    MoveNext();

                    //more.onclick += delegate
                    //{
                    //    MoveNext();
                    //};



                    //Native.Window.onscroll +=
                    //      e =>
                    //      {

                    //          Native.Document.body.With(
                    //              body =>
                    //              {
                    //                  if (more.disabled)
                    //                      return;

                    //                  if (body.scrollHeight - 1 <= Native.Window.Height + body.scrollTop)
                    //                  {
                    //                      MoveNext();
                    //                  }

                    //              }
                    //        );

                    //      };
                }
                //);
                #endregion


            }