public RedNumberDisplay(int Digits, int value, Assets MyAssets)
        {
            this.MyAssets = MyAssets;
            this.Digits = Digits;

            this.Control.style.SetSize(Width, Height);
            this.Control.style.backgroundColor = Color.Black;
            this.Control.style.position = IStyle.PositionEnum.relative;

            DigitControls = Enumerable.Range(0, Digits).Select(
                i =>
                {
                    var d = new IHTMLDiv();

                    d.style.SetLocation(i * DigitX, 0, DigitX, DigitY);
                    d.style.SetBackground(MyAssets.red_numbers[0]);

                    d.AttachTo(this.Control);

                    return d;
                }
                ).ToArray();


            this.Value = value;
        }
			public XRectangle()
			{
				var aelement = new IHTMLDiv();



				// WPF: Rectangle, Image or Label
				var acontent = new IHTMLDiv();

				acontent.style.backgroundColor = "#ff0000";

				this.Rotor = new IHTMLDiv();

				//this.Rotor.style.backgroundColor = "#ffd0d0";

				this.Rotor.style.border = "1px solid black";

				//this.Rotor.style.paddingRight = "10px";

				this.Rotor.AttachTo(aelement);

				acontent.AttachTo(this.Rotor);

				aelement.AttachToDocument();

				Element = aelement;
				Content = acontent;
			}
        /// <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(IDefault page)
        {
            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.getExternalStoragePublicDirectory(
                "",
                root =>
                {
                    Action<string, IHTMLElement> listFiles = null;

                    listFiles =
                        (xroot, xcontainer) =>
                        {
                            if (!xroot.EndsWith("/"))
                                xroot += "/";

                            new IHTMLPre { innerText = xroot }.AttachTo(xcontainer);

                            service.listFiles(xroot,
                                f =>
                                {
                                    var ch = new IHTMLDiv();

                                    ch.style.marginLeft = "1em";


                                    new IHTMLButton { innerText = f }.AttachTo(xcontainer).With(
                                        btn =>
                                        {
                                            btn.style.display = IStyle.DisplayEnum.block;

                                            btn.onclick +=
                                                delegate
                                                {
                                                    if (f.EndsWith("/"))
                                                    {
                                                        listFiles(xroot + f, ch);
                                                    }
                                                };
                                        }
                                    );

                                    ch.AttachTo(xcontainer);

                                }
                            );
                        };


                    listFiles(root, Native.Document.body);
                }
            );
        }
        /// <summary>
        /// Creates a new control
        /// </summary>
        public TextScreenSaver(Qoutes.DocumentList list = null)
        {
            if (list == null)
                list = DefaultData;

            var type = typeof(TextScreenSaver);

            var name = type.Name;

            Console.WriteLine("type: " + name);

            //try
            //{
            //    //IStyleSheet.Default.AddRule("*", "cursor: url('assets/TextScreenSaver/images/cursor.cur'), auto;", 0);

            //IStyleSheet.Default.AddRule("html",
            //    r =>
            //    {
            //        r.style.overflow = IStyle.OverflowEnum.hidden;
            //    }
            //);
            //}
            //catch (Exception exc)
            //{
            //    //new IHTMLElement(IHTMLElement.HTMLElementEnum.div, "error: " + exc.Message.Replace(",", ", ")).AttachToDocument().style.width = "80em";
            //}

            Action<Qoutes.DocumentRef, Action<Qoutes.Document>> PrepareDocument =
                (doc, done) =>
                {
                    if (doc.Document == null)
                    {
                        Native.Document.title = "loading...";

                        //Console.WriteLine("loading: " + doc.Source);

                        doc.Source.DownloadToXML<Qoutes.Document>(Qoutes.Settings.KnownTypes,
                            newdoc =>
                            {

                                doc.Document = newdoc;
                                done(newdoc);
                            }
                        );
                    }
                    else
                        done(doc.Document);
                };


            var current = list.Documents.Random();

            var abort = default(Action);
            var kbd = new KeyboardEvents();

            var reset = default(Action);

            kbd.left +=
                ev =>
                {
                    kbd.Enabled = false;
                    ev.PreventDefault();

                    if (abort != null)
                        abort();
                    current = list.Documents.Previous(i => i == current);
                    reset();
                };

            kbd.right +=
                ev =>
                {
                    kbd.Enabled = false;
                    ev.PreventDefault();

                    if (abort != null)
                        abort();

                    current = list.Documents.Next(i => i == current);
                    reset();
                };

            Native.Document.onkeydown += kbd;


            reset =
                () =>
                PrepareDocument(current,
                doc =>
                {
                    Native.Document.title = doc.Topic.Trim();

                    var body = Native.Document.body;

                    body.style.overflow = IStyle.OverflowEnum.hidden;
                    body.style.width = "100%";
                    body.style.height = "100%";
                    body.style.fontFamily = IStyle.FontFamilyEnum.Verdana;
                    //body.style.backgroundImage = "url(assets/TextScreenSaver/powered_by_jsc.png)";
                    body.style.backgroundRepeat = "no-repeat";


                    //("BackgroundColor: " + doc.Style.BackgroundColor).ToConsole();
                    //("Color: " + doc.Style.Color).ToConsole();

                    doc.Style.ApplyTo(body.style);



                    var lines = doc.Lines();

                    var timer_handler = new Action<Timer>(delegate { });
                    var timer_ref = 100.AsTimer(timer_handler);

                    var vectors = new List<IHTMLDiv>();

                    var abort_me = default(Action);

                    abort_me =
                        delegate
                        {
                            abort -= abort_me;

                            Console.WriteLine("aborting...");

                            timer_ref.Stop();

                            vectors.ForEach(v => v.Orphanize());

                            abort_me = null;
                        };

                    abort += abort_me;

                    Action<Action> SpawnVector =
                        done =>
                        {
                            // we have been aborted
                            if (abort_me == null)
                                return;

                            var z = 0.5d.Random() + 0.5d;

                            var v = new IHTMLDiv { innerText = lines.Random() };

                            v.style.whiteSpace = IStyle.WhiteSpaceEnum.nowrap;

                            vectors.Add(v);

                            Action ApplyZ =
                                () =>
                                {
                                    v.style.fontSize = (z * 3) + "em";
                                    v.style.Opacity = z;
                                    v.style.zIndex = (z * 1000).Floor();
                                };


                            ApplyZ();

                            var x = 100d;
                            var y = 80.Random();

                            v.style.position = IStyle.PositionEnum.absolute;

                            Action UpdatePosition =
                                () =>
                                {
                                    v.style.left = x + "%";
                                    v.style.top = y + "%";
                                };

                            UpdatePosition();

                            v.AttachTo(body);


                            var handler = default(Action<Timer>);


                            Action DisposeThisVector =
                                delegate
                                {
                                    timer_handler -= handler;
                                    v.FadeOut();

                                    done();
                                };

                            v.ondblclick +=
                                ev =>
                                {

                                    DisposeThisVector();
                                };

                            var IsHover = false;

                            v.onmousedown +=
                                ev =>
                                {
                                    ev.PreventDefault();
                                };

                            v.onmouseover +=
                                delegate
                                {
                                    v.style.color = doc.Style.HoverColor;
                                    IsHover = true;
                                };

                            v.onmouseout +=
                                delegate
                                {
                                    v.style.color = Color.None;
                                    IsHover = false;
                                };

                            v.onmousewheel +=
                                ev =>
                                {
                                    z = (z + 0.02 * ev.WheelDirection).Max(0.5).Min(1.0);

                                    ApplyZ();
                                };

                            var drag = new DragHelper(v);

                            drag.Enabled = true;
                            drag.DragMove +=
                                delegate
                                {
                                    var w = Native.window.Width;
                                    var h = Native.window.Height;


                                    x = (drag.Position.X * 100 / w);
                                    y = (drag.Position.Y * 100 / h);

                                    UpdatePosition();

                                    // v.style.SetLocation(drag.Position.X, drag.Position.Y);

                                };

                            handler =
                                timer =>
                                {
                                    if (drag.IsDrag)
                                        return;

                                    if (IsHover)
                                        return;


                                    x -= 0.4 * z;

                                    UpdatePosition();

                                    drag.Position = new Point(v.offsetLeft, v.offsetTop);

                                    if (v.GetOffsetRight() < 0)
                                    {
                                        DisposeThisVector();
                                    }
                                };

                            timer_handler += handler;
                        };

                    var SpawnNextVector = SpawnVector.AsCyclic();


                    var SpawnRandom = default(Action<int, int, Action>);

                    SpawnRandom =
                        (counter, max, h) =>
                        {
                            max.Random().Delayed(
                                () =>
                                {
                                    h();

                                    counter--;

                                    if (counter > 0)
                                        SpawnRandom(counter, max, h);
                                }
                            );
                        };


                    SpawnRandom(doc.Count.ToInt32(), 3000, SpawnNextVector);

                    kbd.Enabled = true;
                }
            );

            reset();
        }
Beispiel #5
0
        public void Initialize()
        {
            Native.Document.body.style.padding = "0";
            Native.Document.body.style.margin = "0";

            var Images = new Dictionary<string, IHTMLImage>();
            var ImagesLoaded = default(Action);
            Func<string, IHTMLImage> CloneImage = name => (IHTMLImage)Images[name].cloneNode(false);

            var Zoom = Data.Zoom.ToDouble();

            var ControlSize = new ZoomedPoint
            {
                Z = Zoom,
                X = Data.ControlSize.Xint,
                Y = Data.ControlSize.Yint
            };

            Control.style.SetSize(ControlSize.ZoomedXint, ControlSize.ZoomedYint);
            Control.style.backgroundColor = Data.BackgroundColor;
            Control.style.color = Data.TextColor;
            Control.AttachAsNextOrToDocument(null);
            Control.style.position = IStyle.PositionEnum.relative;

            Action LoadImages =
                delegate
                {
                    Data.Sprites.ForEach(
                        i =>
                        {
                            Images[i.Value] = i.ImageValue;
                        }
                    );

                    ImagesLoaded();
                };

            ImagesLoaded =
                delegate
                {
                    var ClientRectPos = new ZoomedPoint
                    {
                        Z = Zoom,
                        X = Data.ClientRect.From.Xint,
                        Y = Data.ClientRect.From.Yint
                    };

                    var ClientRectSize = new ZoomedPoint
                    {
                        Z = Zoom,
                        X = Data.ClientRect.Size.Xint,
                        Y = Data.ClientRect.Size.Yint
                    };

                    var ContentLayer = new IHTMLDiv();

                    ContentLayer.style.backgroundColor = Data.ClientRectColor;
                    ContentLayer.style.overflow = IStyle.OverflowEnum.hidden;

                    ContentLayer.style.SetLocation(
                        ClientRectPos.ZoomedXint,
                        ClientRectPos.ZoomedYint,
                        ClientRectSize.ZoomedXint,
                        ClientRectSize.ZoomedYint
                        );
                    ContentLayer.AttachTo(Control);


                    //var r1 = CloneImage("room 001").AttachTo(ContentLayer);

                    //r1.style.SetLocation(0, 0, ClientRectSize.ZoomedXint, ClientRectSize.ZoomedYint);

                    Func<string, IHTMLImage> CreateRoomImage =
                        name =>
                        {
                            var r2 = CloneImage(name);
                            
                            r2.AttachTo(ContentLayer);

                            var r2_Zoom = new ZoomedPoint
                            {
                                Z = Zoom,
                                X = Images[name].width,
                                Y = Images[name].height
                            };

                            r2.Hide();
                            r2.style.SetLocation(0, 0, r2_Zoom.ZoomedXint, r2_Zoom.ZoomedYint);

                            return r2;
                        };

                    var KnownRooms = new List<IHTMLImage>();

                    KnownRooms.AddRange(
                        new [] 
                        {
                            CreateRoomImage("room 001"),
                            CreateRoomImage("room 002"),
                            CreateRoomImage("room 024"),
                            CreateRoomImage("room 031"),
                            CreateRoomImage("room 032"),
                        }
                    );

                    var CurrentRoom = KnownRooms.Random();

                    CurrentRoom.Show();

                    Action<double> SetClipTo =
                        percentage =>
                        {
                            var x = (ClientRectSize.ZoomedX * percentage / 2).ToInt32();
                            var y = (ClientRectSize.ZoomedY * percentage / 2).ToInt32();

                            var clip = new CSSClip
                            {
                                Left = x,
                                Top = y,
                                Right = (ClientRectSize.ZoomedX - x).ToInt32(),
                                Bottom = (ClientRectSize.ZoomedY - y).ToInt32()
                            };

                            Console.WriteLine(percentage + " clip: " + clip);

                            ContentLayer.style.clip = clip;

                        };

                    //ContentLayer.style.clip = "rect(15px auto auto 15px)";

                    //var timer = new ScriptCoreLib.JavaScript.Runtime.Timer(
                    //    delegate
                    //    {
                    //        var p = (Math.Sin(DateTime.Now.Ticks) + 1) / 2;

                    //        Console.WriteLine("p: " + p);
                    //        SetClipTo(p);
                    //    }
                    //    , 0, 200);

                    //var pc = 50;
                    //var px = 200;

                    //Action<double> pChange = i => { px += (i * pc).ToInt32(); timer.StartInterval(px); };

                    Action<Action, Action> FadeOut =
                        (Starting, Stopping) =>
                            new LinearTimeTween
                            {
                                Length = 300,
                                Starting = Starting,
                                Stopping = Stopping,
                                Changed = t => SetClipTo(t),
                                Percision = 20
                            }.Start();

                    Action<Action, Action> FadeIn =
                                  (Starting, Stopping) =>
                                      new LinearTimeTween
                                      {
                                          Length = 300,
                                          Starting = Starting,
                                          Stopping = Stopping,
                                          Changed = t => SetClipTo(1d - t),
                                          Percision = 20
                                      }.Start();

                    var kbd = new KeyboardEvents { Enabled = true };

                    kbd.left += ev =>
                        FadeOut(
                            () => kbd.Enabled = false,
                            () =>
                            {
                                CurrentRoom.Hide();
                                CurrentRoom = KnownRooms.Previous(i => CurrentRoom == i);
                                CurrentRoom.Show();

                                //r1.Hide();
                                //r2.Show();

                                FadeIn(null, () => kbd.Enabled = true);
                            }
                        );

                    kbd.right += ev =>
                         FadeOut(
                            () => kbd.Enabled = false,
                            () =>
                            {
                                CurrentRoom.Hide();
                                CurrentRoom = KnownRooms.Next(i => CurrentRoom == i);
                                CurrentRoom.Show();

                                FadeIn(null, () => kbd.Enabled = true);
                            }
                        );


                    Native.Document.onkeydown += kbd;

                    Native.Document.onmousedown +=
                       ev =>
                         FadeOut(
                            () => kbd.Enabled = false,
                            () =>
                            {
                                CurrentRoom.Hide();
                                CurrentRoom = KnownRooms.Next(i => CurrentRoom == i);
                                CurrentRoom.Show();

                                FadeIn(null, () => kbd.Enabled = true);
                            }
                        );

                    /*
                    var div1 = SpawnDiv(Images, false);

                    div1.style.backgroundColor = Color.Yellow;
                    div1.AttachTo(ClientRect);
                    div1.style.SetLocation(4, 4, 100, 100);

                    var div2 = SpawnDiv(Images, true);

                    div2.style.backgroundColor = Color.Gray;
                    div2.AttachTo(ClientRect);
                    div2.style.SetLocation(100, 4, 100, 100);

                    */

                };

            LoadImages();
        }
        private static IHTMLDiv AddNamespace(IHTMLDiv parent, IHTMLDiv NextNamespaceOrDefault, string Namespace, Action<string> UpdateLocation)
        {
            var div = new IHTMLDiv();

            if (NextNamespaceOrDefault == null)
                div.AttachTo(parent);
            else
                NextNamespaceOrDefault.insertPreviousSibling(div);

            div.style.marginTop = "0.1em";
            div.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
            div.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;


            var i = new Namespace().AttachTo(div);

            i.style.verticalAlign = "middle";
            i.style.marginRight = "0.5em";

            if (Namespace == "")
                Namespace = "<Module>";

            var s = new IHTMLAnchor { innerText = Namespace }.AttachTo(div);


            s.href = "#";
            s.style.textDecoration = "none";
            s.style.color = JSColor.System.WindowText;

            Action onclick = delegate
            {

            };

            s.onclick +=
                e =>
                {
                    e.PreventDefault();

                    s.focus();

                    UpdateLocation(Namespace);

                    onclick();
                };

            s.onfocus +=
                delegate
                {

                    s.style.backgroundColor = JSColor.System.Highlight;
                    s.style.color = JSColor.System.HighlightText;
                };

            s.onblur +=
                delegate
                {

                    s.style.backgroundColor = JSColor.None;
                    s.style.color = JSColor.System.WindowText;
                };

            var children = new IHTMLDiv().AttachTo(div);

            children.style.paddingLeft = "1em";
            children.Hide();


            var NextClickHide = default(Action);
            var NextClickShow = default(Action);

            NextClickHide =
                delegate
                {
                    children.Hide();

                    onclick = NextClickShow;
                };

            NextClickShow =
                delegate
                {
                    children.Show();

                    onclick = NextClickHide;
                };


            onclick = NextClickShow;

            return children;
        }
        /// <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)
        {
            content.AttachControlToDocument();


          

            var ss = new DataGridView
                {
                    DataSource = Book1.GetDataSet(),
                    DataMember = "Assets"
                };
            content.Controls.Add(ss);

            var x = new IHTMLDiv();

            x.style.backgroundColor = "rgba(255,255,255,1.0)";
            x.style.position = IStyle.PositionEnum.absolute;
            x.style.height = "auto";
            x.style.width = "100%";
            x.style.top = "100%";
            x.style.zIndex = 999;
            var temp = ss.Rows[1];
            var sss = temp.Cells[0].AsHTMLElementContainer();
            sss.style.backgroundColor = "red";
            new TheOtherOption { }.With(
               o =>
               {
                   o.BackColor = Color.White;

                   o.GetHTMLTarget().With(
                       div =>
                       {
                           div.AttachTo(x);


                           div.style.position = IStyle.PositionEnum.absolute;
                       }
                   );

               }
           );


            x.AttachTo(sss.parentNode);
            x.Hide();

            sss.onmouseover += delegate
            {
                x.Show();
            };

            sss.onmouseout += delegate
            {
                x.Hide();
            };



            //that.GotFocus += delegate
            //{
            //    x.Show();
            //};

            //that.Leave += delegate
            //{
            //    x.Hide();
            //};

           
            
        }
        public static IHTMLDiv ConvertToImageReflection(ReflectionSetup rs)
        {

            var Control = new IHTMLDiv();

            Control.style.SetLocation(rs.Position.X, rs.Position.Y, +rs.Size.X, +rs.Size.Y);

            rs.Image.style.SetLocation(0, 0, rs.Size.X, rs.Size.Y);
            rs.Image.AttachTo(Control);

            #region drag

            if (rs.Drag)
            {
                rs.Image.onmousedown += Native.DisabledEventHandler;
                rs.Image.style.cursor = ScriptCoreLib.JavaScript.DOM.IStyle.CursorEnum.move;

                var drag = new DragHelper(rs.Image);

                drag.Enabled = true;
                drag.Position = rs.Position;
                drag.DragMove +=
                    delegate
                    {
                        Control.style.SetLocation(drag.Position.X, drag.Position.Y);
                    };


            }

            #endregion

            #region GetRect
            Func<int, int, int, int, string> GetRect =
                (left, top, width, height) =>
                {
                    // rect (top, right, bottom, left)
                    var x = string.Format("rect({0}px, {1}px, {2}px, {3}px)", top, width + left, height + top, left);
                    return x;
                };
            #endregion


            #region CopyLineY
            Action<ReflectionFrameInfo> CopyLineY =
                i =>
                {
                    var clone = (IHTMLImage)rs.Image.cloneNode(true);

                    clone.style.SetLocation(0, i.Offset + i.To, rs.Size.X, i.Size);
                    clone.style.clip = GetRect(0, i.From, rs.Size.X, 1);
                    clone.style.Opacity = i.Opacity;
                    clone.AttachTo(i.Owner);
                };
            #endregion



            #region y
            var YMax = (rs.Size.Y * rs.ReflectionZoom).ToInt32();

            if (rs.Bottom >= 0)
            {
                var _bottom = new IHTMLDiv();
                _bottom.style.SetLocation(0, rs.Size.Y - 1 + rs.Bottom, rs.Size.X, YMax);
                _bottom.AttachTo(Control);
                _bottom.style.overflow = ScriptCoreLib.JavaScript.DOM.IStyle.OverflowEnum.hidden;

                for (int y = 0; y < YMax; y++)
                {
                    CopyLineY(
                        new ReflectionFrameInfo
                        {
                            From = y,
                            To = YMax - y * 2,
                            Opacity = y / YMax,
                            Size = YMax,
                            Offset = 0,
                            Owner = _bottom
                        }
                    );
                }
            }

            if (rs.Top >= 0)
            {
                var _top = new IHTMLDiv();
                _top.style.SetLocation(0, -YMax - rs.Top, rs.Size.X, YMax);
                _top.AttachTo(Control);
                _top.style.overflow = ScriptCoreLib.JavaScript.DOM.IStyle.OverflowEnum.hidden;


                for (int y = 0; y < YMax; y++)
                {
                    CopyLineY(
                        new ReflectionFrameInfo
                        {
                            From = y,
                            To = YMax - y * 2,
                            Opacity = (1 - (y / (YMax))),
                            Size = YMax,
                            Offset = 0,
                            Owner = _top
                        }
                    );
                }
            }
            #endregion

            var XMax = (rs.Size.X * rs.ReflectionZoom).ToInt32();




            #region CopyLineX
            Action<ReflectionFrameInfo> CopyLineX =
                i =>
                {
                    var clone = (IHTMLImage)rs.Image.cloneNode(true);

                    clone.style.SetLocation(i.Offset + i.To, 0, i.Size, rs.Size.Y);
                    clone.style.clip = GetRect(i.From, 0, 1, rs.Size.Y);
                    clone.style.Opacity = i.Opacity;


                    clone.AttachTo(i.Owner);
                };
            #endregion

            #region x

            if (rs.Right >= 0)
            {
                var _right = new IHTMLDiv();
                _right.style.SetLocation(rs.Size.X - 1 + rs.Right, 0, XMax, rs.Size.Y);
                _right.AttachTo(Control);
                _right.style.overflow = ScriptCoreLib.JavaScript.DOM.IStyle.OverflowEnum.hidden;

                for (int x = 0; x < XMax; x++)
                {
                    CopyLineX(
                          new ReflectionFrameInfo
                          {
                              From = x,
                              To = XMax - x * 2,
                              Opacity = (x / (XMax)),
                              Size = XMax,
                              Offset = 0,
                              Owner = _right
                          }
                      );
                }
            }

            if (rs.Left >= 0)
            {
                var _left = new IHTMLDiv();
                _left.style.SetLocation(-XMax - rs.Left, 0, XMax, rs.Size.Y);
                _left.AttachTo(Control);
                _left.style.overflow = ScriptCoreLib.JavaScript.DOM.IStyle.OverflowEnum.hidden;

                for (int x = 0; x < XMax; x++)
                {
                    CopyLineX(
                          new ReflectionFrameInfo
                          {
                              From = x,
                              To = XMax - x * 2,
                              Opacity = (1 - (x / (XMax))),
                              Size = XMax,
                              Offset = 0,
                              Owner = _left
                          }
                      );
                }
            }
            #endregion

            return Control;
        }
        /// <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(IDefault page)
        {
            @"Hello world".ToDocumentTitle();

            var output = new IHTMLTextArea().AttachToDocument();

            var gexf = new XElement("gexf");

            gexf.Add(
                new XElement("meta",
                    new XElement("creator", "jsc"),
                    new XElement("description", "NASDAQSNA")
                )
            );

            var graph = new XElement("graph",
                new XAttribute("mode", "static"),
                new XAttribute("defaultedgetype", "directed")
            );

            gexf.Add(graph);

            var nodes = new XElement("nodes");

            graph.Add(nodes);

            var edges = new XElement("edges");

            graph.Add(edges);

            output.value = gexf.ToString();
            output.onfocus +=
                delegate
                {
                    output.value = gexf.ToString();
                };
            output.onmouseover +=
             delegate
             {
                 output.value = gexf.ToString();
             };

            var NumericNodeIdLookup = new List<string>();

            Func<string, int> GetNumericNodeId =
                k =>
                {
                    if (!NumericNodeIdLookup.Contains(k))
                        NumericNodeIdLookup.Add(k);


                    return NumericNodeIdLookup.IndexOf(k);
                };

            #region AddRelatedCompanies
            Func<IHTMLDiv, string, Action, Task> AddRelatedCompanies = null;

            AddRelatedCompanies =
                (c, qid, done) =>
                {
                    var nqid = GetNumericNodeId(qid).ToString();
                    var cc = new IHTMLDiv();

                    cc.style.marginLeft = "2em";



                    var service = new ApplicationWebService
                    {
                        qid = qid,
                        yield = (id, CompanyName, Price) =>
                        {
                            var nid = GetNumericNodeId(id).ToString();

                            if (nodes.Elements().Any(k => k.Attribute("id").Name.LocalName == nid))
                            {
                            }
                            else
                            {
                                nodes.Add(
                                    new XElement("node",
                                     new XAttribute("id", nid),
                                     new XAttribute("label", CompanyName)
                                    )
                                );
                            }



                            var btn = new IHTMLButton
                            {
                                innerText = id + " " + CompanyName + " " + Price
                            };

                            btn.style.display = IStyle.DisplayEnum.block;

                            if (qid == id)
                            {
                                btn.disabled = true;

                                if (c == null)
                                {
                                    btn.AttachToDocument();
                                    cc.AttachToDocument();
                                }
                                else
                                {
                                    //btn.AttachTo(c);
                                    cc.AttachTo(c);
                                }

                                if (done != null)
                                    done();
                            }
                            else
                            {
                                edges.Add(
                                    new XElement("edge",
                                     new XAttribute("source", nqid),
                                     new XAttribute("target", nid)
                                    )
                                );

                                btn.AttachTo(cc);

                                var ccc = new IHTMLDiv();

                                ccc.AttachTo(cc);

                                int cx = 0;

                                ccc.ToggleVisible();



                                btn.WhenClicked(
                                    async delegate
                                    {
                                        if (cx == 0)
                                        {
                                            btn.style.color = JSColor.Red;

                                            await AddRelatedCompanies(ccc, id,
                                                delegate
                                                {
                                                    btn.style.color = JSColor.Blue;

                                                }
                                            );
                                        }


                                        cx++;

                                        ccc.ToggleVisible();

                                    }
                                );

                            }
                        }
                    };



                    return service.GetRelatedCompanies();
                };
            #endregion

            AddRelatedCompanies(null, "NASDAQ:FB", null);
            AddRelatedCompanies(null, "NASDAQ:GOOG", null);
        }
        public void __Application(IApplicationLoader app)
        {
            //app.LoadingAnimation.FadeOut();

            var DefaultTitle = "jsc solutions";


            Native.Document.title = DefaultTitle;

            StringActionAction GetTitleFromServer = new UltraWebService().GetTitleFromServer;



            GetTitleFromServer(
                n => Native.Document.title = n
            );

            var MyPagesBackground = new IHTMLDiv
            {

            };

            MyPagesBackground.style.overflow = IStyle.OverflowEnum.hidden;
            MyPagesBackground.style.position = IStyle.PositionEnum.absolute;
            MyPagesBackground.style.width = "100%";
            MyPagesBackground.style.height = "100%";
            MyPagesBackground.AttachToDocument();

            var MyPages = new IHTMLDiv
            {

            };

            MyPages.style.overflow = IStyle.OverflowEnum.auto;
            MyPages.style.position = IStyle.PositionEnum.absolute;
            MyPages.style.width = "100%";
            MyPages.style.height = "100%";
            MyPages.AttachToDocument();

            var MyPagesInternal = new IHTMLDiv();

            MyPagesInternal.style.margin = "4em";
            MyPagesInternal.AttachTo(MyPages);

            // http://www.google.com/support/forum/p/Google+Analytics/thread?tid=486a963e463df665&hl=en
            var gapathname = Native.Document.location.pathname;
            var gasearch = Native.Document.location.search;
            var gahash = Native.Window.escape(Native.Document.location.hash);
            var gapageview = gapathname + gasearch + gahash;

            var hash = Native.Document.location.hash;

            Action<string> Analytics = delegate { };

        #region logo
            {
                var IsStudio = Native.Document.location.hash.StartsWith("#/studio");

                if (Native.Document.location.host.StartsWith("studio."))
                {
                    IsStudio = true;
                }

                if (IsStudio)
                {
                    new StudioView(AddSaveButton).Content.AttachToDocument();
                }
                else if (Native.Document.location.hash.StartsWith("#/docs"))
                {
                    var view = new DocumentationCompilationViewer();

                    view.TouchTypeSelected +=
                        type =>
                        {
                            Native.Document.location.hash = "#/docs/" + type.FullName;

                            Analytics("#/docs/" + type.FullName);
                        };

                }
                else if (Native.Document.location.hash.StartsWith("#/warehouse"))
                {
                    new UltraWebService().ThreeDWarehouse(
                        y =>
                        {
                            Func<string, IHTMLAnchor> Build =
                                mid =>
                                {
                                    var a = new IHTMLAnchor { href = "http://sketchup.google.com/3dwarehouse/details?ct=hppm&mid=" + mid }.AttachTo(MyPagesInternal);
                                    var img = new IHTMLImage { src = "http://sketchup.google.com/3dwarehouse/download?rtyp=st&ctyp=other&mid=" + mid }.AttachTo(a);

                                    return a;
                                };

                            var imgs = Enumerable.ToArray(
                                from k in y.Elements()
                                select Build(k.Value)

                            );
                        }
                    );

                }

                else if (Native.Document.location.hash == "#/source")
                {

                    var sln = new TreeNode(() => new VistaTreeNodePage());

                    sln.Text = "Solution";
                    sln.IsExpanded = true;

                    Action<TreeNode> AddReferences =
                        p =>
                        {
                            var r = p.Add("References", new References());

                            r.Add("System", new Assembly());
                            r.Add("System.Core", new Assembly());
                            r.Add("ScriptCoreLib", new Assembly());
                            r.Add("ScriptCoreLib.Ultra", new Assembly());
                            r.Add("ScriptCoreLib.Ultra.Library", new Assembly());
                            r.Add("ScriptCoreLib.Ultra.Controls", new Assembly());
                            r.Add("ScriptCoreLibJava", new Assembly());
                            r.Add("jsc.meta", new Assembly());
                        };

                    Action<TreeNode> AddUltraSource =
                        p =>
                        {
                            var my = p.Add("My.UltraSource");
                            my.Add("Default.htm", new HTMLDocument());
                            my.Add("jsc.png", new ImageFile());

                        };

                    {
                        var p = sln.Add("Visual C# Project", new VisualCSharpProject());


                        AddReferences(p);
                        AddUltraSource(p);



                        p.Add("Application.cs", new VisualCSharpCode());
                        p.Add("WebService.cs", new VisualCSharpCode());
                        p.Add("Program.cs", new VisualCSharpCode());
                    }

                    {
                        var p = sln.Add("Visual Basic Project", new VisualBasicProject());

                        AddReferences(p);
                        AddUltraSource(p);

                        p.Add("Application.vb", new VisualBasicCode());
                        p.Add("WebService.vb", new VisualBasicCode());
                        p.Add("Program.vb", new VisualBasicCode());
                    }


                    {
                        var p = sln.Add("Visual F# Project", new VisualFSharpProject());

                        AddReferences(p);
                        AddUltraSource(p);


                        p.Add("Application.fs", new VisualFSharpCode());
                        p.Add("WebService.fs", new VisualFSharpCode());
                        p.Add("Program.fs", new VisualFSharpCode());
                    }

                    sln.Container.style.Float = IStyle.FloatEnum.right;
                    sln.Container.AttachTo(MyPagesInternal);

                    new SourceEditorHeader().Container.AttachTo(MyPagesInternal);

                    //new IHTMLElement(IHTMLElement.HTMLElementEnum.h1, "Create your own Ultra Application project template").AttachTo(MyPagesInternal);

                    var n = new TextEditor(MyPagesInternal);

                    n.Width = 600;
                    n.Height = 400;

                    //n.InnerHTML = "<p>Create your own <b>Ultra Application</b> Project Template</p>";


                    new DefaultPage1().Container.AttachTo(n.Document.body);

                    var m1 = new SimpleCodeView();

                    m1.Container.AttachTo(MyPagesInternal);
                    //m1.SelectType.onchange +=
                    //    delegate
                    //    {
                    //        m1.TypeName.innerText = m1.SelectType.value;
                    //    };

                    //m1.RunJavaScript.onclick +=
                    //    delegate
                    //    {
                    //        m1.RunJavaScript.style.color = JSColor.Blue;

                    //        try
                    //        {
                    //            Native.Window.eval(m1.Code1.value);

                    //            1000.AtDelay(
                    //                delegate
                    //                {
                    //                    m1.RunJavaScript.style.color = JSColor.None;
                    //                }
                    //            );
                    //        }
                    //        catch
                    //        {
                    //            m1.RunJavaScript.style.color = JSColor.Red;

                    //            1000.AtDelay(
                    //                delegate
                    //                {
                    //                    m1.RunJavaScript.style.color = JSColor.None;
                    //                }
                    //            );
                    //        }
                    //    };
                    new Compilation().GetArchives().SelectMany(k => k.GetAssemblies()).First(k => k.Name == "ScriptCoreLib").WhenReady(
                        ScriptCoreLib =>
                        {
                            // we do not have reflection in place for native wrappers :/

                            m1.SelectEvent.Clear();

                            var Element = ScriptCoreLib.GetTypes().Single(k => k.FullName == "ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement");
                            //var Element = ScriptCoreLib.GetTypes().Single(k => k.HTMLElement == "ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement");

                            Action<CompilationEvent> Add =
                                SourceEvent =>
                                {
                                    m1.SelectEvent.Add(
                                        new IHTMLOption { innerText = SourceEvent.Name }
                                    );
                                };

                            Element.GetEvents().ForEach(Add);

                        }
                    );


                    m1.SelectEvent.onchange +=
                        delegate
                        {
                            m1.EventName.innerText = m1.SelectEvent.value;
                        };




                }
                else if (Native.Document.location.hash == "#/UltraApplicationWithAssets")
                {
                    new UltraApplicationWithAssets().Container.AttachToDocument();
                }
                else
                    if (Native.Document.location.hash == "#/audio")
                    {
                        Action AtTimer = delegate { };

                        (1000 / 15).AtInterval(
                            tt =>
                            {
                                AtTimer();
                            }
                        );

                        new SoundCloudBackground().Container.AttachTo(MyPagesBackground);
                        new SoundCloudHeader().Container.AttachTo(MyPagesInternal);

                        var page = 1;

                        var Tracks = new IHTMLDiv().AttachTo(MyPagesInternal);
                        Tracks.style.margin = "1em";

                        var More = new SoundCloudMore();

                        var AudioLinks = default(AudioLink);

                        var LoadCurrentPage = default(Action);

                        LoadCurrentPage = delegate
                        {
                            var loading = new SoundCloudLoading();

                            loading.Container.AttachTo(Tracks);


                            new UltraWebService().SoundCloudTracksDownload(
                                System.Convert.ToString(page),
                                ee =>
                                {
                                    if (loading != null)
                                    {
                                        loading.Container.Orphanize();
                                        loading = null;
                                    }

                                    var t = new SoundCloudTrack();

                                    t.Content.ApplyToggleConcept(t.HideContent, t.ShowContent).Hide();

                                    t.Title.innerHTML = ee.trackName;
                                    t.Waveform.src = ee.waveformUrl;

                                    t.Audio.src = ee.streamUrl;
                                    t.Audio.autobuffer = true;


                                    AudioLinks = new AudioLink
                                    {
                                        Audio = t.Audio,
                                        Prev = AudioLinks
                                    };

                                    var _AudioLinks = AudioLinks;

                                    if (AudioLinks.Prev != null)
                                        AudioLinks.Prev.Next = AudioLinks;
                                    else
                                        // we are the first  :)
                                        t.Audio.play();

                                    t.MoreButton.onclick +=
                                        delegate
                                        {
                                            t.Audio.pause();

                                            if (_AudioLinks.Next != null)
                                            {
                                                _AudioLinks.Next.Audio.currentTime = 0;
                                                _AudioLinks.Next.Audio.play();

                                                if (_AudioLinks.Next.Next == null)
                                                {
                                                    page++;
                                                    LoadCurrentPage();
                                                }
                                            }
                                        };

                                    t.Audio.onended +=
                                        delegate
                                        {
                                            if (_AudioLinks.Next != null)
                                            {
                                                _AudioLinks.Next.Audio.currentTime = 0;
                                                _AudioLinks.Next.Audio.play();

                                                if (_AudioLinks.Next.Next == null)
                                                {
                                                    page++;
                                                    LoadCurrentPage();
                                                }
                                            }
                                        };

                                    t.Identity.innerText = ee.uid;

                                    t.Play.onclick += eee => { eee.PreventDefault(); t.Audio.play(); };
                                    t.Pause.onclick += eee => { eee.PreventDefault(); t.Audio.pause(); };

                                    t.Title.style.cursor = IStyle.CursorEnum.pointer;
                                    t.Title.onclick += eee =>
                                        {
                                            eee.PreventDefault();

                                            var playing = true;

                                            if (t.Audio.paused)
                                                playing = false;

                                            if (t.Audio.ended)
                                                playing = false;

                                            if (!playing)
                                                t.Audio.play();
                                            else
                                                t.Audio.pause();
                                        };

                                    DoubleAction SetProgress1 = p =>
                                    {

                                        t.Gradient3.style.width = System.Convert.ToInt32(800 * p) + "px";
                                        t.Gradient4.style.width = System.Convert.ToInt32(800 * p) + "px";
                                    };

                                    t.Gradient5.style.Opacity = 0.4;
                                    t.Gradient6.style.Opacity = 0.4;

                                    DoubleAction SetProgress2 = p =>
                                    {

                                        t.Gradient5.style.width = System.Convert.ToInt32(800 * p) + "px";
                                        t.Gradient6.style.width = System.Convert.ToInt32(800 * p) + "px";
                                    };

                                    AtTimer +=
                                        delegate
                                        {
                                            if (t.Audio.duration == 0)
                                            {
                                                t.Play.Hide();
                                                t.Pause.Hide();
                                                return;
                                            }
                                            else
                                            {

                                                var playing = true;

                                                if (t.Audio.paused)
                                                    playing = false;

                                                if (t.Audio.ended)
                                                    playing = false;

                                                if (!playing)
                                                    t.Title.style.color = Color.None;
                                                else
                                                    t.Title.style.color = Color.Blue;

                                                t.Play.Show(!playing);
                                                t.Pause.Show(playing);
                                            }

                                            var p = t.Audio.currentTime / t.Audio.duration;
                                            SetProgress1(p);
                                        };

                                    t.Waveform.onmouseout +=
                                        delegate
                                        {
                                            SetProgress2(0);
                                        };

                                    t.Waveform.onmousemove +=
                                        eee =>
                                        {
                                            SetProgress2(eee.OffsetX / 800.0);
                                        };

                                    t.Waveform.onclick +=
                                        eee =>
                                        {
                                            t.Audio.currentTime = t.Audio.duration * (eee.OffsetX / 800.0);
                                            t.Audio.play();
                                        };

                                    t.Waveform.style.cursor = IStyle.CursorEnum.pointer;

                                    SetProgress1(0);
                                    SetProgress2(0);

                                    t.Container.AttachTo(Tracks);
                                }
                            );


                            10000.AtDelay(
                                delegate
                                {
                                    More.MoreButton.FadeIn(0, 1000, null);
                                }
                            );
                        };


                        More.MoreButton.Hide();
                        More.Container.AttachTo(MyPagesInternal);

                        More.MoreButton.onclick += eee =>
                            {
                                eee.PreventDefault();
                                More.MoreButton.FadeOut(1, 300,
                                    delegate
                                    {
                                        page++;
                                        LoadCurrentPage();
                                    }
                                );
                            };

                        LoadCurrentPage();

                    }
                    else
                    {
                        //new PromotionWebApplication1.HTML.Audio.FromAssets.Track1 { controls = true }.AttachToDocument();
                        //new PromotionWebApplication1.HTML.Audio.FromWeb.Track1 { controls = true, autobuffer = true }.AttachToDocument();

                        var IsAvalonJavaScript = hash == "#/avalon.js";
                        var IsAvalonActionScript = hash == "#/avalon.as";
                        var IsAvalon = IsAvalonActionScript || IsAvalonJavaScript;

                        //if (IsAvalon)
                        //{

                        //{
                        //    var ccc = new IHTMLDiv();

                        //    ccc.style.position = IStyle.PositionEnum.absolute;
                        //    ccc.style.left = "15%";
                        //    ccc.style.right = "15%";
                        //    ccc.style.top = "15%";


                        //    var Now = DateTime.Now;

                        //    var CountDown = new CountDownGadgetConcept(CountDownGadget.Create)
                        //    {
                        //        ShowOnlyDays = true,
                        //        Event = new DateTime(2010, 5, 24, 23, 59, 50),

                        //    };

                        //    CountDown.Element.GadgetContainer.style.color = "#808080";
                        //    CountDown.Element.GadgetContainer.style.textShadow = "#E0E0E0 1px 1px 1px";


                        //    CountDown.Element.GadgetContainer.AttachTo(ccc);
                        //    CountDown.Element.GadgetContainer.FadeIn(3000, 2000, null);

                        //    ccc.AttachToDocument();
                        //}

                        {
                            var ccc = new IHTMLDiv();

                            ccc.style.position = IStyle.PositionEnum.absolute;
                            ccc.style.left = "50%";
                            ccc.style.top = "50%";
                            ccc.style.marginLeft = (-JSCSolutionsNETCarouselCanvas.DefaultWidth / 2) + "px";
                            ccc.style.marginTop = (-JSCSolutionsNETCarouselCanvas.DefaultHeight / 2) + "px";

                            ccc.style.SetSize(JSCSolutionsNETCarouselCanvas.DefaultWidth, JSCSolutionsNETCarouselCanvas.DefaultHeight);

                            ccc.AttachToDocument();

                            if (IsAvalonActionScript)
                            {
                                var alof = new UltraSprite();
                                alof.ToTransparentSprite();
                                alof.AttachSpriteTo(ccc);
                            }
                            else
                            {
                                var alo = new JSCSolutionsNETCarouselCanvas();
                                alo.Container.AttachToContainer(ccc);

                                alo.AtLogoClick +=
                                    delegate
                                    {
                                        //Native.Window.open("http://sourceforge.net/projects/jsc/", "_blank");
                                        Native.Window.open("/download", "_blank");
                                    };

                            }
                        }
                        //}
                        //else
                        //{
                        //    var cc = new HTML.Pages.FromAssets.Controls.Named.CenteredLogo_Kamma();

                        //    cc.Container.AttachToDocument();

                        //    // see: http://en.wikipedia.org/wiki/Perl_control_structures
                        //    // "Unless" == "if not"  ;)

                        //    IsMicrosoftInternetExplorer.YetIfNotThen(cc.TheLogoImage.BeginPulseAnimation).ButIfSoThen(cc.TheLogoImage.HideNowButShowAtDelay);
                        //}

                        var aa = new About();
                        aa.Service.innerText = gapageview;
                        aa.Container.AttachToDocument();

                    }
            }
        #endregion


            Analytics =
                __hash =>
                {
                    var __gahash = Native.Window.escape(__hash);
                    var __gapageview = gapathname + gasearch + __gahash;


                    "UA-13087448-1".ToGoogleAnalyticsTracker(
                        pageTracker =>
                        {
                            pageTracker._setDomainName(".jsc-solutions.net");
                            pageTracker._trackPageview(__gapageview);


                        }
                    );
                };

            Analytics(Native.Document.location.hash);


        }
        /// <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)
        {
            content.AttachControlToDocument();

            var x = new IHTMLDiv();

            x.style.backgroundColor = "rgba(255,255,255,1.0)";
            x.style.position = IStyle.PositionEnum.absolute;
            x.style.height = "auto";
            x.style.width = "100%";
            x.style.top = "100%";
            x.style.zIndex = 999;


            x.AttachTo(content.textBox1.GetHTMLTarget());

            x.Hide();
            Action close = delegate
            {
                x.Hide();
            };

            Action<string> add = name =>
                new Option { name = name }.With(
                    o =>
                    {

                        o.AttachTo(x);

                        o.div.css.hover.style.backgroundColor = "green";

                        o.div.onclick +=
                            delegate
                            {
                                Console.WriteLine(o.name.innerText);
                                content.textBox1.Text = o.name.innerText;
                                close();
                                //content.textBox1.Text = o.name;
                            };
                    }
                );


            //content.checkBox1.CheckedChanged += delegate { x.Show(content.checkBox1.Checked); };
            content.textBox1.GotFocus += delegate
            {
                x.Show();
            };


            add("foo");
            add("Marge Simpson");

            new TheOtherOption { }.With(
                o =>
                {
                    o.BackColor = Color.Transparent;

                    o.GetHTMLTarget().With(
                        div =>
                        {
                            div.AttachTo(x);


                            div.style.position = IStyle.PositionEnum.relative;
                        }
                    );

                }
            );

            add("bar");

            var ls = new Option { name = "Lisa Simpson EUR" }.With(o =>
            {
                o.div.css.hover.style.backgroundColor = "rgba(118, 207, 140, 0.7)";

                o.div.onclick +=
                    delegate
                    {
                        content.textBox1.Text = o.name.innerText;
                        close();
                    };
            });

            content.textBox2.AddDropDownOptions(
                new Option { name = "hello" },
                new TheOtherOption { },
                new Option { name = "world" },
                ls

            );

        }
        public static IHTMLDiv AddDropDownOptions(this TextBox that, params object[] e)
        {
            var x = new IHTMLDiv();

            x.style.backgroundColor = "rgba(255,255,255,1.0)";
            x.style.position = IStyle.PositionEnum.absolute;
            x.style.height = "auto";
            x.style.width = "100%";
            x.style.top = "100%";
            x.style.zIndex = 999;

            var c = that.GetHTMLTarget();

            x.AttachTo(c);

            x.Hide();

            that.GotFocus += delegate
            {
                x.Show();
            };

            that.Leave += delegate
            {
                x.Hide();
            };

            e.AsEnumerable().WithEach(
                k =>
                {
                    {
                        //var o = k as UserControl;
                        var o = k as Control;
                        if (o != null)
                        {
                            o.BackColor = Color.Transparent;

                            o.GetHTMLTarget().With(
                                div =>
                                {
                                    div.AttachTo(x);

                                    div.style.width = "auto";
                                    div.style.position = IStyle.PositionEnum.relative;
                                }
                            );

                            return;
                        }
                    }

                    {
                        var o = (INodeConvertible<IHTMLDiv>)k;
                        {
                            o.AttachTo(x);
                         
                            //o.div.css.hover.style.backgroundColor = "yellow";
                        }
                    }
                }
            );

            return x;
        }
		private void RenderWriteHistory(Dictionary<SolutionFileTextFragment, Color> Lookup, SolutionFile f, IHTMLElement Container)
		{
			Func<SolutionFileTextFragment, Color> LookupOrDefault =
				ff =>
				{
					if (this.Colors.ContainsKey(ff))
						return this.Colors[ff];

					return this.Colors[SolutionFileTextFragment.None];
				};

			var Content = new IHTMLDiv().AttachTo(Container);


			Content.style.position = IStyle.PositionEnum.relative;

			var ViewBackground = new IHTMLDiv().AttachTo(Content);

			ViewBackground.style.position = IStyle.PositionEnum.absolute;
			ViewBackground.style.left = "0px";
			ViewBackground.style.top = "0px";
			ViewBackground.style.width = "4em";
			ViewBackground.style.borderRight = "1px dotted gray";
			ViewBackground.style.paddingRight = "0.5em";

			var ViewTrap = new IHTMLDiv().AttachTo(Content);

			ViewTrap.style.position = IStyle.PositionEnum.absolute;
			ViewTrap.style.left = "0px";
			ViewTrap.style.top = "0px";
			ViewTrap.style.right = "0px";
			ViewTrap.style.bottom = "0px";
			//ViewTrap.style.backgroundColor = Color.White;

			var ViewTrapContainer = new IHTMLDiv().AttachTo(ViewTrap);

			ViewTrapContainer.style.cursor = IStyle.CursorEnum.text;
			ViewTrapContainer.style.position = IStyle.PositionEnum.relative;
			ViewTrapContainer.style.paddingLeft = "5em";

			var View = new IHTMLDiv().AttachTo(ViewTrapContainer);



			var ContentHeightDummy = new IHTMLDiv().AttachTo(Content);

			var RegionStack = new Stack<List<Action<bool>>>();
			var RegionGlobal = new List<Action<bool>>();
			RegionStack.Push(RegionGlobal);

			var Lines = new List<IHTMLDiv>();

			var CurrentLineDirty = false;
			var CurrentLine = default(IHTMLDiv);
			var CurrentLineContent = default(IHTMLDiv);

			Action NextLine = delegate
			{
				CurrentLineDirty = false;

				var c = new IHTMLDiv();
				var cc = new IHTMLDiv();
				var cb = new IHTMLDiv();

				CurrentLine = c.AttachTo(View);
				CurrentLineContent = cc.AttachTo(c);

				var CurrentRegion = RegionStack.Peek();

				RegionStack.WithEach(
					k =>
					{
						k.Add(
							IsActive =>
							{
								// should we react when in a global region
								if (k == RegionGlobal)
									return;

								if (IsActive)
								{
									cc.style.backgroundColor = Color.FromGray(0xf9);
									cb.style.backgroundColor = Color.FromGray(0xf9);
								}
								else
								{
									cc.style.backgroundColor = Color.None;
									cb.style.backgroundColor = Color.None;
								}
							}
						);
					}
				);

				CurrentLine.onmouseover +=
					delegate
					{
						CurrentRegion.Invoke(true);
						cc.style.backgroundColor = Color.FromGray(0xf0);
						cb.style.backgroundColor = Color.FromGray(0xf0);
					};

				CurrentLine.onmouseout +=
					delegate
					{
						CurrentRegion.Invoke(false);
						cc.style.backgroundColor = Color.None;
						cb.style.backgroundColor = Color.None;
					};


				Lines.Add(CurrentLine);
				//CurrentLineContent.style.marginLeft = "5em";

				var BCurrentLine = cb.AttachTo(ViewBackground);

				BCurrentLine.style.textAlign = IStyle.TextAlignEnum.right;

				var span = new IHTMLCode { innerText = "" + Lines.Count };
				span.style.color = Lookup[SolutionFileTextFragment.Type];
				span.AttachTo(BCurrentLine);

				//Content.style.height = Lines.Count + "em";

				new IHTMLDiv { new IHTMLCode { innerText = Environment.NewLine } }.AttachTo(ContentHeightDummy);
			};



			foreach (var item in f.WriteHistory.ToArray())
			{
				if (item is SolutionFileWriteArguments.BeginRegion)
				{
					RegionStack.Push(new List<Action<bool>>());
				}

				if (item is SolutionFileWriteArguments.EndRegion)
				{
					RegionStack.Pop();
				}

				if (CurrentLine == null)
					NextLine();



				var innerText = item.Text;
				innerText = innerText.TakeUntilLastIfAny(Environment.NewLine);

				if (!string.IsNullOrEmpty(innerText))
				{
					var span = new IHTMLCode { innerText = innerText };

					if (item.Fragment == SolutionFileTextFragment.Indent)
					{
						span.style.width = "2em";
						span.style.display = IStyle.DisplayEnum.inline_block;

						if (CurrentLineDirty)
							span.style.borderLeft = "1px dotted #afafaf";
					}


					span.style.color = LookupOrDefault(item.Fragment);

					CurrentLineDirty = true;
					span.AttachTo(CurrentLineContent);

					if (item.Tag != null)
					{
						span.style.cursor = ScriptCoreLib.JavaScript.DOM.IStyle.CursorEnum.pointer;
						span.onmouseover +=
							delegate
							{
								span.style.textDecoration = "underline";
							};

						span.onmouseout +=
							delegate
							{
								span.style.textDecoration = "";
							};



						var Type = item.Tag as SolutionProjectLanguageType;
						if (Type != null)
						{
							span.title = Type.FullName;
						}

						var Method = item.Tag as SolutionProjectLanguageMethod;
						if (Method != null)
						{
							span.title = Method.Name;
						}


						var Uri = item.Tag as Uri;
						if (Uri != null)
						{
							var a = new IHTMLAnchor();
							a.style.color = LookupOrDefault(item.Fragment);

							a.href = Uri.ToString();
							a.target = "_blank";
							a.Add(span);
							a.AttachTo(CurrentLineContent);

							a.onclick +=
								e =>
								{
                                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151103
									e.preventDefault();

									if (LinkCommentClick != null)
										LinkCommentClick(Uri);
								};
						}
					}
				}

				if (item.Text.EndsWith(Environment.NewLine))
				{
					if (!CurrentLineDirty)
					{
						var span = new IHTMLCode { innerText = " " };
						span.AttachTo(CurrentLineContent);
					}

					CurrentLine = null;
				}
			}
		}
		private static void CreateRotor(double _angle, IHTMLElement _container)
		{

			var shadow = new IHTMLDiv();
			shadow.style.position = IStyle.PositionEnum.absolute;
			shadow.style.left = "0px";
			shadow.style.top = "0px";
			shadow.style.width = "600px";
			shadow.style.height = "400px";
			shadow.style.backgroundColor = "black";
			shadow.style.Opacity = 0.3;
			shadow.AttachTo(_container);

			var borders = new IHTMLDiv();
			borders.style.position = IStyle.PositionEnum.absolute;
			borders.style.left = "0px";
			borders.style.top = "0px";
			//borders.style.width = "400px";
			//borders.style.height = "300px";
			borders.style.border = "4px solid black";
			borders.style.Opacity = 0.1;
			borders.AttachTo(_container);

			var a = new IHTMLDiv();

			// we can specify rotation origin within red area!

			a.style.backgroundColor = "red";

			a.style.marginTop = "-200px";
			a.style.marginLeft = "-300px";
			a.style.paddingLeft = "300px";
			a.style.paddingTop = "200px";

			var c = new IHTMLDiv();

			var z = new IHTMLButton("hi");


			z.AttachTo(c);
			c.AttachTo(a);

			//a.style.width = "300px";
			//a.style.height = "200px";

			c.style.width = "300px";
			c.style.height = "200px";
			//c.style.position = IStyle.PositionEnum.relative;
			//c.style.SetLocation(0, 0);
			//c.style.clip = "rect(0px,60px,200px,0px)";

			c.appendChild("hello world");
			c.appendChild(new IHTMLButton("click me"));

			var xx = new IHTMLButton("xx");

			xx.style.SetLocation(32, 32);

			c.appendChild(xx);
			c.appendChild("hello world");

			new IHTMLDiv
			{
				innerText =
					@"As it seems we can use apng files but 
we cannot have absolute children. This means we will be able to support
non container objects."
			}.AttachTo(c);


			c.style.SetBackground("assets/MatrixTransformExample/bg.png", true);

			var t = new IHTMLDiv();

			c.appendChild(t);

			//a.style.width = "400px";
			//a.style.height = "300px";


			
			var angle = _angle;
			ApplyRotation2(a, angle, 1, 200, 0);

			new Timer(
				delegate
				{
					t.innerHTML = "" + angle;
					angle -= 2;
					ApplyRotation2(a, angle, 1, 200, 0);

					borders.style.SetSize(a.offsetWidth, a.offsetHeight);

					borders.style.SetLocation((a.clientWidth - a.offsetWidth) / 2, (a.clientHeight - a.offsetHeight) / 2);
					a.style.SetLocation((a.clientWidth - a.offsetWidth) / 2, (a.clientHeight - a.offsetHeight) / 2);

				}
				, 0, 250
			);


			a.AttachTo(_container);
		}
		public static void ExposedFunctions_AddData1(Data1 e)
		{

			if (e == null)
			{
				new IHTMLDiv { innerText = "yay, no data..." }.AttachTo(instructions);
				return;
			}

			Func<string> GetString = () => new { e.text, e.index }.ToString();

			// this function can now be used by external API
			e.GetString = IFunction.OfDelegate(GetString);

			var div = new IHTMLDiv
			{
				// using a real anonymous type, we get a nice key value string for display
				innerText = GetString()
			};

			#region attach events
			if (e.onclick != null)
			{
				div.style.cursor = IStyle.CursorEnum.pointer;
				div.onclick +=
					delegate
					{
						e.onclick.apply(e, div);
					};
			}

			if (e.onmouseover != null)
			{
				div.style.cursor = IStyle.CursorEnum.pointer;
				div.onmouseover +=
					delegate
					{
						e.onmouseover.apply(e, div);
					};
			}

			if (e.onmouseout != null)
			{
				div.style.cursor = IStyle.CursorEnum.pointer;
				div.onmouseout +=
					delegate
					{
						e.onmouseout.apply(e, div);
					};
			}
			#endregion

			div.AttachTo(instructions);
		}
        public __SplitContainer()
        {
            //InternalElement.style.backgroundColor = "red";

            this.Panel1 = new SplitterPanel(this);
            this.Panel2 = new SplitterPanel(this);

            this.Controls.Add(this.Panel1);
            this.Controls.Add(this.Panel2);



            var TheSplitter = new IHTMLDiv { };

            TheSplitter.css.hover.style.backgroundColor = "blue";
            TheSplitter.css.active.style.backgroundColor = "blue";

            TheSplitter.style.cursor = DOM.IStyle.CursorEnum.move;


            TheSplitter.AttachTo(
                InternalElement
            );

            this.SplitterDistance = 200;



            var h = new DragHelper(TheSplitter);

            h.Enabled = true;
            //h.Position.X = this.SplitterDistance;

            h.DragMove +=
                delegate
                {
                    //this.SplitterDistance = h.Position.X;

                    if (this.InternalOrientation == global::System.Windows.Forms.Orientation.Horizontal)
                    {

                        TheSplitter.style.SetLocation(0, h.Position.Y);
                    }
                    else
                    {

                        TheSplitter.style.SetLocation(h.Position.X, 0);
                    }

                };

            // X:\jsc.svn\examples\javascript\forms\FormsSplitter\FormsSplitter\ApplicationControl.cs



            TheSplitter.style.position = DOM.IStyle.PositionEnum.absolute;


            Action AtUpdate = delegate
            {
                __Panel p1 = this.Panel1;
                __Panel p2 = this.Panel2;


                if (this.InternalOrientation == global::System.Windows.Forms.Orientation.Horizontal)
                {
                    h.Position.Y = this.SplitterDistance;




                    p1.InternalElement.style.position = DOM.IStyle.PositionEnum.absolute;
                    p1.InternalElement.style.left = "0px";
                    p1.InternalElement.style.top = "0px";
                    p1.InternalElement.style.width = "";
                    p1.InternalElement.style.bottom = "";
                    p1.InternalElement.style.right = "0px";
                    p1.InternalElement.style.height = (this.SplitterDistance - 4) + "px";



                    p2.InternalElement.style.position = DOM.IStyle.PositionEnum.absolute;
                    p2.InternalElement.style.left = "0px";
                    p2.InternalElement.style.top = (this.SplitterDistance + 4) + "px";
                    p2.InternalElement.style.width = "";
                    p2.InternalElement.style.bottom = "0px";
                    p2.InternalElement.style.right = "0px";
                    p2.InternalElement.style.height = "";




                    TheSplitter.style.left = "0px";
                    TheSplitter.style.top = (this.SplitterDistance - 4) + "px";
                    TheSplitter.style.right = "0px";
                    TheSplitter.style.height = "8px";


                    TheSplitter.style.width = "";
                    TheSplitter.style.bottom = "";
                }
                else
                {
                    h.Position.X = this.SplitterDistance;

                    // dock left?


                    p1.InternalElement.style.position = DOM.IStyle.PositionEnum.absolute;
                    p1.InternalElement.style.left = "0px";
                    p1.InternalElement.style.top = "0px";
                    p1.InternalElement.style.width = (this.SplitterDistance - 4) + "px";
                    p1.InternalElement.style.bottom = "0px";
                    p1.InternalElement.style.right = "";
                    p1.InternalElement.style.height = "";



                    p2.InternalElement.style.position = DOM.IStyle.PositionEnum.absolute;
                    p2.InternalElement.style.left = (this.SplitterDistance + 4) + "px";
                    p2.InternalElement.style.top = "0px";
                    p2.InternalElement.style.width = "";
                    p2.InternalElement.style.bottom = "0px";
                    p2.InternalElement.style.right = "0px";
                    p2.InternalElement.style.height = "";


                    TheSplitter.style.left = (this.SplitterDistance - 4) + "px";
                    TheSplitter.style.top = "0px";
                    TheSplitter.style.width = "8px";
                    TheSplitter.style.bottom = "0px";

                    TheSplitter.style.right = "";
                    TheSplitter.style.height = "";

                }


                p1.InternalClientSizeChanged0();
                p2.InternalClientSizeChanged0();
            };


            h.DragStop +=
                delegate
                {
                    if (this.InternalOrientation == global::System.Windows.Forms.Orientation.Horizontal)
                    {
                        this.SplitterDistance = h.Position.Y;
                    }
                    else
                    {
                        this.SplitterDistance = h.Position.X;

                    }

                    //AtUpdate();

                };




            this.InternalSplitterDistanceChanged +=
                delegate
                {
                    AtUpdate();
                };

            this.InternalOrientationChanged +=
                delegate
                {
                    Console.WriteLine(
                        "InternalOrientationChanged " + new
                        {
                            this.Name,
                            this.Orientation
                        }
                    );

                    AtUpdate();
                };

            this.SizeChanged +=
                delegate
                {
                    //Console.WriteLine("__SplitContainer SizeChanged");


                    AtUpdate();
                };


            AtUpdate();
        }
        public TipRotator(TipDocument _Data)
        {
            this.Data = _Data;

            if (this.Data == null)
                this.Data = DefaultData;

            var div = new IHTMLDiv();

            var header = new IHTMLElement(IHTMLElement.HTMLElementEnum.h3, this.Data.Topic).AttachTo(div);

            var randomized = this.Data.Tips.Randomize();

            var current = randomized.First();

            var content = new IHTMLElement(IHTMLElement.HTMLElementEnum.p).AttachTo(div);

            var next = new IHTMLButton("Next Tip").AttachTo(div);

            var src = "assets/ClickOnce/Button_19.gif";

            
            var img = new IHTMLImage(this.Data.Location + src).AttachTo(next);

            img.style.verticalAlign = "middle";

            Action GoNext =
                delegate
                {
                    current = randomized.Next(i => i == current);

                    content.innerText = current.Content;
                    content.style.color = current.Color;
                };

            GoNext();

            next.onclick +=
                delegate
                {
                    GoNext();
                };

            div.AttachTo(Native.Document.body);
        }
Beispiel #18
0
        public Tycoon4(Action<Tycoon4> yield)
        {


            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;
            Native.Document.body.style.color = Color.White;
            Native.Document.body.style.backgroundColor = Color.Black;

            //var info_text =
            //    ((ApplicationDescriptionAttribute)typeof(Tycoon4).GetCustomAttributes(typeof(ApplicationDescriptionAttribute), false).Single()).Description;

            var infoc = new IHTMLDiv();
            new fullbox().AttachTo(infoc);
            var info = new IHTMLCode().AttachTo(infoc);



            infoc.style.SetLocation(4, 4, Native.window.Width - 8, 0);
            infoc.style.height = "auto";
            info.style.Float = IStyle.FloatEnum.right;


            var paused = false;

            var ZeroPoint = new Point<double>();

            // http://en.wikipedia.org/wiki/Isometric_projection
            // http://en.wikipedia.org/wiki/Dimetric_projection
            // http://en.wikipedia.org/wiki/Axonometric_projection
            // http://en.wikipedia.org/wiki/First_angle_projection
            // http://en.wikipedia.org/wiki/3/4_perspective

            var RotationA = 45.ToRadians();
            var RotationB = 0.5;
            var Zoom = 1;
            var Dot = 4;

            var MapSize = new Rectangle
            {
                Left = -12,
                Width = 24,
                Top = -12,
                Height = 24
            };

            var MapMargins = new Point
            (
                4,
                4
            );

            var bg_size = new
            {
                w = (64 * Zoom).ToInt32(),
                h = (32 * Zoom).ToInt32()
            };

            Func<Point<double>> GetCenter = () => new Point<double>
            {
                X = bg_size.w * (MapSize.Width + MapMargins.X) / 2 /*Native.Window.Width / 2*/,
                Y = bg_size.h * (MapSize.Height + MapMargins.Y) / 2 /*Native.Window.Height / 2*/
            };

            var arena = new ArenaControl();

            arena.Control.AttachToDocument();

            arena.Layers.Canvas.style.backgroundColor = Color.FromRGB(0, 0, 0);

            //arena.SetCanvasViewCenter();


            arena.SetCanvasSize(new Point(
                ((MapSize.Width + +MapMargins.X) * bg_size.w).ToInt32(),
                ((MapSize.Height + +MapMargins.Y) * bg_size.h).ToInt32()
                ));

            var PauseFog = new IHTMLDiv().AttachTo(arena.Layers.Info);

            PauseFog.style.backgroundColor = Color.Black;
            PauseFog.style.Opacity = 1;

            PauseFogTween = new TweenDataDouble(
                delegate
                {
                }
            ) { Value = 1 };

            PauseFogTween.ValueChanged +=
                    () => PauseFog.style.Opacity = PauseFogTween.Value;

            #region onresize
            Action onresize =
                delegate
                {
                    infoc.style.SetLocation(4, 4, Native.window.Width - 8, 0);
                    infoc.style.height = "auto";

                    var rect = Rectangle.Of(0, 0, Native.window.Width, Native.window.Height);

                    arena.SetLocation(rect);
                    PauseFog.style.SetLocation(rect);
                };

            Native.window.onresize +=
                ev =>
                {
                    onresize();
                };

            onresize();
            #endregion

            infoc.AttachTo(arena.Layers.Info);

            #region TileResources
            var TileResources = new
                {
                    Grass = new { Source = new _0_192x95().src, Height = 32 },
                    //Rocks = new { Source = new _1().src, Height = 32 },
                    TileSelector = new { Source = new _3().src, Height = 32 },
                    RoughLand = new { Source = new _2x192x95().src, Height = 32 },
                    Dirt = new { Source = new _4_192x95().src, Height = 32 },
                    //DirtDirtGrass = new { Source = new _5().src, Height = 32 },
                    //DirtGrassGrass = new { Source = new _6().src, Height = 32 },

                    Track1 = new { Source = new r2_192x95().src, Height = 32 },

                    Road2 = new { Source = new r1_192x95().src, Height = 32 },
                    Road2_Track1 = new { Source = new r3_192x95().src, Height = 32 },
                    Road1 = new { Source = new r4_192x95().src, Height = 32 },
                    Road1_Road2 = new { Source = new r5_192x95().src, Height = 32 },

                    Tree = new { Source = new t1_192x192().src, Height = 64 },
                    Tree2 = new { Source = new t2_192x192().src, Height = 128 },

                    House1a = new { Source = new h1a_192x384().src, Height = 128 },
                    House1b = new { Source = new h1b_192x384().src, Height = 128 },
                    House1x = new { Source = new h1x_192x384().src, Height = 128 },

                    //House2 = new { Source = new h2().src, Height = 96 },
                    //House3 = new { Source = new h3().src, Height = 50 },
                    //House4 = new { Source = new h4().src, Height = 53 },
                    //House5a = new { Source = new h5a().src, Height = 33 },
                    //House5b = new { Source = new h5b().src, Height = 40 },
                    //House5c = new { Source = new h5c().src, Height = 40 },
                    //House5 = new { Source = new h5().src, Height = 40 },

                    //House11a = new { Source = new h11a().src, Height = 89 },
                    //House11b = new { Source = new h11b().src, Height = 89 },
                    //House11c = new { Source = new h11c().src, Height = 89 },
                    //House11x = new { Source = new h11x().src, Height = 89 }
                };

            var TileResourcesList = new[]
                {
                    TileResources.Grass,
                    //TileResources.Rocks,
                    TileResources.TileSelector,
                    TileResources.RoughLand ,
                    TileResources.Dirt ,
                    //TileResources.DirtDirtGrass ,
                    //TileResources.DirtGrassGrass,
                    TileResources.Track1 ,
                    TileResources.Road2 ,
                    TileResources.Road2_Track1 ,
                    TileResources.Road1 ,
                    TileResources.Road1_Road2,

                    TileResources.Tree ,
                    TileResources.Tree2 ,

                    TileResources.House1a,
                    TileResources.House1b,
                    TileResources.House1x,

                    //TileResources.House2,
                    //TileResources.House3 ,
                    //TileResources.House4 ,
                    //TileResources.House5a ,
                    //TileResources.House5b ,
                    //TileResources.House5c ,
                    //TileResources.House5 ,
                    //TileResources.House11a ,
                    //TileResources.House11b ,
                    //TileResources.House11c ,
                    //TileResources.House11x ,
                };
            #endregion

            var MyFrames_Soldier = new DudeAnimationInfo
                {
                    Frames_Stand = Frames.WolfSoldier,
                    Frames_Walk = Frames.WolfSoldier_Walk
                };

            var MyFrames_Imp = new DudeAnimationInfo
                {
                    Frames_Stand = Frames.DoomImp,
                    Frames_Walk = Frames.DoomImp_Walk
                };


            var MyFrames_TwinClone = new DudeAnimationInfo
                {
                    Frames_Stand = DoomImp,
                    Frames_Walk = DoomImp_Walk
                };



            #region Preloading
            Action AllImagesLoaded = delegate { };

            var ImagesThatAreCurrentlyLoading = new List<IHTMLImage>();
            var ImagesThatAreCurrentlyLoadingCounter = 0;

            //Action<IHTMLImage> LoadingSingleImageDone = img =>
            //{
            //    ImagesThatAreCurrentlyLoading.Remove(img);

            //    Console.WriteLine("loaded: " + img.src);

            //    if (ImagesThatAreCurrentlyLoading.Count == 0)
            //        AllImagesLoaded();
            //    else
            //        info.innerText = "Loading images... (" + ImagesThatAreCurrentlyLoading.Count + ")";
            //};


            info.innerText = "Loading images...";

            #region StartLoadingSingleImage
            Action<IHTMLImage> StartLoadingSingleImage = Image =>
                {
                    ImagesThatAreCurrentlyLoading.Add(Image);

                    Image.InvokeOnComplete(img => { ImagesThatAreCurrentlyLoadingCounter++; }, 30);
                    //LoadingSingleImageDone(Image);
                };
            #endregion

            #region StartLoadingDudeAnimationInfo
            Action<DudeAnimationInfo> StartLoadingDudeAnimationInfo =
                a =>
                {
                    a.Frames_Stand.ForEach(i => StartLoadingSingleImage(i.Image));
                    a.Frames_Walk.ForEach(j => j.ForEach(i => StartLoadingSingleImage(i.Image)));
                };
            #endregion

            var Argh = new Argh();
            var CloneAffirmative = new EN_000002();
            var Affirmative = new Affirmative();
            var click = new click();
            var Hammertime = new SAMPLES234 { volume = 0.1 };
            var Sawtime = new SAMPLES216 { volume = 0.1 };
            var StoneHammerTime = new SAMPLES233 { volume = 0.1 };


            #endregion

            #region AllImagesLoaded
            AllImagesLoaded +=
                delegate
                {
                    Console.WriteLine("AllImagesLoaded");

                    info.innerText = "Loading images... done!";

                    #region Translate
                    Func<double, double, Point<double>> Translate =
                        (_x, _y) =>
                        {
                            var _r = ZeroPoint.GetRotation(_x, _y) + RotationA;
                            var _d = ZeroPoint.GetDistance(_x, _y) * bg_size.h * 2d.Sqrt();

                            _x = Math.Cos(_r) * _d;
                            _y = Math.Sin(_r) * _d * RotationB;

                            return new Point<double> { X = _x, Y = _y };
                        };
                    #endregion

                    #region Translator
                    var Translator = new CoordTranslatorBase
                    {
                        ConvertMapToCanvas = map_coords =>
                        {
                            var canvas_coords = Translate(map_coords.X, map_coords.Y);
                            var c = GetCenter();

                            canvas_coords.X += c.X;
                            canvas_coords.Y += c.Y;

                            return canvas_coords;

                        },
                        ConvertCanvasToMap = canvas =>
                        {
                            var c = GetCenter();

                            var offset = new Point<double> { X = canvas.X - c.X, Y = (canvas.Y - c.Y) / RotationB };

                            var d = ZeroPoint.GetDistance(offset) / (bg_size.h * 2d.Sqrt());
                            var r = ZeroPoint.GetRotation(offset) - RotationA;

                            var realoffset = new Point<double>
                            {
                                X = Math.Cos(r) * d,
                                Y = Math.Sin(r) * d
                            };

                            return realoffset;
                        }
                    };
                    #endregion





                    #region ApplyPosition
                    Action<double, double, IHTMLDiv> ApplyPosition =
                        (_x, _y, _div) =>
                        {
                            try
                            {
                                var _pos = GetCenter();

                                var p = Translate(_x, _y);



                                var _dot = (Zoom * Dot).ToInt32();

                                _div.style.SetLocation(
                                    (_pos.X + p.X).ToInt32() - _dot / 2,
                                    (_pos.Y + p.Y).ToInt32() - _dot / 2,
                                    _dot,
                                    _dot
                                );

                                _div.AttachToDocument();

                                _div.onmouseover +=
                                    delegate
                                    {
                                        Native.Document.title = new { _x, _y }.ToString();

                                    };

                            }
                            catch (Exception ex)
                            {
                                ex.ToConsole();
                            }
                        };
                    #endregion


                    #region CreateDiv
                    Func<double, double, IHTMLDiv> CreateDiv =
                        (_x, _y) =>
                        {

                            var _div = new IHTMLDiv();

                            _div.style.backgroundColor = Color.Red;

                            ApplyPosition(_x, _y, _div);

                            return _div;
                        };
                    #endregion


                    var TileColor = Color.Gray;
                    var TileColor2 = Color.White;
                    var TileColorHouse1 = Color.FromRGB(41, 0, 0);
                    //var TileColorHouse2 = Color.FromRGB(42, 0, 0);
                    //var TileColorHouse3 = Color.FromRGB(43, 0, 0);
                    //var TileColorHouse11 = Color.FromRGB(44, 0, 0);

                    var TileColorTree1 = Color.FromRGB(51, 0, 0);
                    var TileColorTree2 = Color.FromRGB(52, 0, 0);
                    var TileColorTree3 = Color.FromRGB(53, 0, 0);


                    var TileColorRoad1 = Color.FromRGB(61, 0, 0);
                    var TileColorRoad2 = Color.FromRGB(62, 0, 0);
                    var TileColorRoad3 = Color.FromRGB(63, 0, 0);

                    var TileColorTrack1 = Color.FromRGB(70, 0, 0);
                    var TileColorRoadTrack1 = Color.FromRGB(71, 0, 0);


                    var data = new[] {
                        new { x = -0.5, y = -0.5, color = Color.Red },
                        new { x = 0.5, y = -0.5, color = Color.Green },
                        new { x = 0.5, y = 0.5, color = Color.Blue },
                        new { x = -0.5, y = 0.5, color = Color.Yellow },
                    };

                    #region IsDefined
                    Func<double, double, bool> IsDefined =
                        (x, y) => data.Any(
                            i =>
                            {
                                if (i.x != x) return false;
                                if (i.y != y) return false;

                                return true;
                            }
                    );
                    #endregion


                    data = data.Concat(
                        from x in Enumerable.Range(MapSize.Left, MapSize.Width + 1)
                        from y in Enumerable.Range(MapSize.Top, MapSize.Height + 1)
                        select new { x = (double)x, y = (double)y, color = TileColor }
                           ).ToArray();


                    #region CreateNewItemsRandomly
                    Action<int, Color> CreateNewItemsRandomly =
                        (x, c) =>
                            x.Times(
                                     delegate
                                     {
                                         var loc = data.Where(i => i.color == TileColor).Random();

                                         data = data.ConcatSingle(
                                                new { x = loc.x, y = loc.y, color = c }
                                         ).ToArray();
                                     }
                             );
                    #endregion


                    #region ApplyTileToCanvas
                    Action<double, double, IHTMLImage, double> ApplyTileToCanvas =
                        (x, y, bg, height) =>
                        {
                            height *= Zoom;

                            var c = GetCenter();

                            var p = Translate(x, y);

                            c.X += p.X.ToInt32(bg_size.w / 2);
                            c.Y += p.Y.ToInt32(bg_size.h / 2);

                            var _x = (c.X - bg_size.w / 2);
                            var _y = (c.Y - bg_size.h / 2 - (height - bg_size.h));



                            bg.style.SetLocation(
                                _x.ToInt32(),
                                _y.ToInt32(),
                                bg_size.w, height.ToInt32()
                            );


                            if (height > bg_size.h)
                            {
                                bg.style.zIndex = (_y + height - bg_size.h / 2).ToInt32();
                            }
                            else
                            {
                                bg.style.zIndex = (_y).ToInt32();
                            }
                        };
                    #endregion

                    // http://wiki.openttd.org/index.php/Enhanced_GFX_replacement

                    var KnownTileElements = new List<TileElement>();
                    var KnownDirtTileElements = new List<TileElement>();

                    #region SpawnItems
                    Action<Color, Func<string>, double> SpawnItems =
                        (c, src, h) =>
                        {
                            var tiles_query =
                                 from point in data
                                 where point.color == c
                                 let img = new IHTMLImage(src())
                                 let update = (Action)(() => ApplyTileToCanvas(point.x, point.y, img, h))
                                 let img2 = img.Aggregate(
                                    i =>
                                    {
                                        update();
                                    }).AttachTo(arena.Layers.Canvas)
                                 select
                                    new TileElement
                                    {
                                        Position = new Point<double> { X = point.x, Y = point.y },
                                        Image = img,
                                        Source = src()
                                        //, update 
                                    };

                            var aa0 = tiles_query.ToArray();
                            var aa1 = aa0;
                            var aa2 = aa1;
                            KnownTileElements.AddRange(aa2);//.ForEach(i => i.update());
                        };
                    #endregion


                    CreateNewItemsRandomly(12, TileColorHouse1);
                    //CreateNewItemsRandomly(4, TileColorHouse2);
                    //CreateNewItemsRandomly(5, TileColorHouse3);
                    //CreateNewItemsRandomly(5, TileColorHouse11);
                    CreateNewItemsRandomly(20, TileColorTree1);
                    CreateNewItemsRandomly(10, TileColorTree2);
                    CreateNewItemsRandomly(5, TileColorTree3);

                    CreateNewItemsRandomly(2, TileColorRoad1);
                    CreateNewItemsRandomly(1, TileColorRoad2);

                    CreateNewItemsRandomly(1, TileColorTrack1);

                    // expand the random roads through the map
                    #region expand



                    data.Where(i => i.color == TileColorRoad1).ToArray().ForEach(
                        road =>
                        {
                            data = data.Concat(
                                    from y in Enumerable.Range(MapSize.Top, MapSize.Height + 1)
                                    select new { x = road.x, y = (double)y, color = TileColorRoad1 }
                            ).ToArray();
                        }
                    );

                    data.Where(i => i.color == TileColorRoad2).ToArray().ForEach(
                        road =>
                        {
                            data = data.Concat(
                                    from x in Enumerable.Range(MapSize.Left, MapSize.Width + 1)
                                    select new { x = (double)x, y = road.y, color = TileColorRoad2 }
                            ).ToArray();
                        }
                    );

                    data.Where(i => i.color == TileColorTrack1).ToArray().ForEach(
                       road =>
                       {
                           data = data.Concat(
                                   from x in Enumerable.Range(MapSize.Left, MapSize.Width + 1)
                                   select new { x = (double)x, y = road.y, color = TileColorTrack1 }
                           ).ToArray();
                       }
                   );

                    #endregion

                    // remove buildings on the roads
                    #region clean road1
                    {
                        var AllRoads = data.Where(i => i.color == TileColorRoad1).ToArray();

                        data = data.Where(
                            v =>
                            {
                                if (v.color == TileColor)
                                    return true;

                                if (v.color == TileColorRoad1)
                                    return true;

                                if (v.color == TileColorRoad2)
                                    return true;

                                if (v.color == TileColorTrack1)
                                    return true;

                                return !AllRoads.Any(i => i.x == v.x && i.y == i.y);
                            }
                        ).ToArray();
                    }

                    {

                        var query = from a in data
                                    where a.color == TileColorRoad1
                                    let b = data.FirstOrDefault(i =>
                                        {
                                            var SameColor = i.color == TileColorRoad2;
                                            var SameLocation = i.x == a.x && i.y == a.y;

                                            return SameColor && SameLocation;
                                        })
                                    where b != null
                                    let c = new { a.x, a.y, color = TileColorRoad3 }
                                    select new { a, b, c };

                        foreach (var v in query)
                        {

                            var data0 = data.Where(i =>
                                    {
                                        if (i == v.a) return false;
                                        if (i == v.b) return false;

                                        return true;
                                    });

                            data = data0.ConcatSingle(v.c)
                                .ToArray();


                        }
                    }

                    {

                        var query = from a in data
                                    where a.color == TileColorRoad1
                                    let b = data.FirstOrDefault(i =>
                                    {
                                        var SameColor = i.color == TileColorTrack1;
                                        var SameLocation = i.x == a.x && i.y == a.y;

                                        return SameColor && SameLocation;
                                    })
                                    where b != null
                                    let c = new { a.x, a.y, color = TileColorRoadTrack1 }
                                    select new { a, b, c };

                        foreach (var v in query)
                        {

                            var data0 = data.Where(i =>
                            {
                                if (i == v.a) return false;
                                if (i == v.b) return false;

                                return true;
                            });

                            data = data0.ConcatSingle(v.c)
                                .ToArray();


                        }
                    }


                    {
                        var AllRoads = data.Where(i => i.color == TileColorRoad2).ToArray();

                        data = data.Where(
                            v =>
                            {
                                if (v.color == TileColor)
                                    return true;

                                if (v.color == TileColorRoad1)
                                    return true;

                                if (v.color == TileColorRoad2)
                                    return true;

                                return !AllRoads.Any(i => i.x == v.x && i.y == v.y);
                            }
                        ).ToArray();
                    }
                    #endregion



                    info.innerText = "Loading items...";

                    Timer.DoAsync(
                        delegate
                        {
                            SpawnItems(TileColor,
                                () =>
                                {
                                    //if (0.05.ByChance()) return new _1().src;
                                    if (0.33.ByChance()) return new _2x192x95().src;

                                    return new _0_192x95().src;
                                }, 32);

                            SpawnItems(TileColorRoad1, () => new r1_192x95().src, 32);
                            SpawnItems(TileColorRoad2, () => new r4_192x95().src, 32);
                            SpawnItems(TileColorRoad3, () => new r5_192x95().src, 32);

                            SpawnItems(TileColorTrack1, () => new r2_192x95().src, 32);
                            SpawnItems(TileColorRoadTrack1, () => new r3_192x95().src, 32);

                            SpawnItems(TileColorHouse1, () => new h1x_192x384().src, 128);
                            //SpawnItems(TileColorHouse11, () => new h11x().src, 89);
                            //SpawnItems(TileColorHouse2, () => new h2().src, 96);
                            //SpawnItems(TileColorHouse3, () => new h3().src, 50);

                            SpawnItems(TileColorTree1, () => new t1_192x192().src, 65);
                            SpawnItems(TileColorTree2, () => new t2_192x192().src, 128);
                            SpawnItems(TileColorTree3, () => new t3_192x192().src, 128);





                            Func<bool> IsDoneRotatingA = () => RotationA.ToDegrees() == 45;


                            #region SpawnLookingDude
                            Func<FrameInfo[], int, int, Dude2> SpawnLookingDude =
                                       (f, x, y) =>
                                       {
                                           var r = new Dude2
                                           {
                                               Frames = f,
                                           };

                                           r.AnimationInfo.Frames_Stand = f;

                                           r.Zoom.DynamicZoomFunc = a => 1;
                                           r.Zoom.StaticZoom = 1;

                                           r.SetSize(48, 72);
                                           r.TeleportTo(x, y);


                                           r.Control.AttachTo(arena.Layers.Canvas);

                                           r.Direction = Math.PI.Random() * 2;

                                           return r;
                                       };
                            #endregion








                            var Dudes = new List<Dude2>();
                            var RoadVehicles = new List<Dude2>();


                            #region GetRandomCanvasPosition
                            Func<Point> GetRandomCanvasPosition =
                                () =>
                                {
                                    var x = (MapSize.Width - 1).Random() + MapSize.Left + 1;
                                    var y = (MapSize.Height - 1).Random() + MapSize.Top + 1;


                                    var target = Translate(
                                        x, y
                                    );

                                    var c = GetCenter();

                                    var p = new Point(
                                        (target.X + c.X).ToInt32(),
                                        (target.Y + c.Y).ToInt32()
                                    );

                                    return p;
                                }
                            ;
                            #endregion


                            #region CreateDude
                            Func<DudeAnimationInfo, IdleBehaviour, double, Dude2> CreateDude =
                                (ani, idle, dudezoom) =>
                                {
                                    var w2c = GetRandomCanvasPosition();
                                    var w2 = SpawnLookingDude(ani.Frames_Stand, w2c.X.ToInt32(), w2c.Y.ToInt32());
                                    w2.Zoom.StaticZoom = dudezoom;
                                    w2.AnimationInfo.Frames_Walk = ani.Frames_Walk;
                                    w2.TargetLocationDistanceMultiplier = 1;

                                    Action<Action> GoSomeWhere =
                                        done =>
                                        {
                                            w2.DoneWalkingOnce += done;
                                            w2.WalkTo(GetRandomCanvasPosition().ToDouble());
                                        };

                                    #region WaitSomeAndGoSomeWhere
                                    Action WaitSomeAndGoSomeWhere = null;

                                    WaitSomeAndGoSomeWhere =
                                        () => 5000.Random().AtTimeout(
                                            t =>
                                            {
                                                if (paused)
                                                {
                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }

                                                var CurrentlyWalking = Dudes.Count(i => i.IsWalking);

                                                if (w2.IsWalking)
                                                {
                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }

                                                // if we've been selected, then wait for orders
                                                if (w2.IsSelected)
                                                {
                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }

                                                if (w2.IsHot)
                                                {
                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }

                                                // dont make them all walk at the same time
                                                if (CurrentlyWalking > 3)
                                                {
                                                    w2.Direction = (Math.PI * 2).Random();

                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }


                                                if (idle == IdleBehaviour.Scout)
                                                    GoSomeWhere(WaitSomeAndGoSomeWhere);
                                                else
                                                    WaitSomeAndGoSomeWhere();
                                            }
                                        );

                                    // make only imps wander on their own
                                    if (idle != IdleBehaviour.None)
                                        WaitSomeAndGoSomeWhere();
                                    #endregion

                                    return w2;
                                };
                            #endregion



                            info.innerHTML = "Creating dudes...";

                            1.Times(() => Dudes.Add(CreateDude(MyFrames_Soldier, IdleBehaviour.Look, 0.5)));
                            4.Times(() => Dudes.Add(CreateDude(MyFrames_Soldier, IdleBehaviour.Scout, 0.5)));

                            1.Times(() => Dudes.Add(CreateDude(MyFrames_Imp, IdleBehaviour.Look, 0.5)));
                            4.Times(() => Dudes.Add(CreateDude(MyFrames_Imp, IdleBehaviour.Scout, 0.5)));

                            1.Times(() => Dudes.Add(CreateDude(MyFrames_TwinClone, IdleBehaviour.Look, 0.5)));
                            4.Times(() => Dudes.Add(CreateDude(MyFrames_TwinClone, IdleBehaviour.Scout, 0.5)));








                            Func<Point, Point<double>> GetNearestMapPosition =
             p => Translator.ConvertCanvasToMap(p.ToDouble()).Round().BoundTo(MapSize);

                            #region GetNearestMapRect
                            Func<Rectangle, Rectangle> GetNearestMapRect =
                                rect =>
                                {
                                    var from = GetNearestMapPosition(new Point(rect.Left, rect.Top));
                                    var to = GetNearestMapPosition(new Point(rect.Right, rect.Bottom));

                                    return new Rectangle
                                    {
                                        Left = from.X.ToInt32(),
                                        Top = from.Y.ToInt32(),
                                        Right = to.X.ToInt32(),
                                        Bottom = to.Y.ToInt32()
                                    };
                                };
                            #endregion

                            #region GetTileElementsAt
                            Func<Point<double>, IEnumerable<TileElement>> GetTileElementsAt =
                                map_coords =>
                                    from i in KnownTileElements
                                    where i != null
                                    where i.Position.X == map_coords.X && i.Position.Y == map_coords.Y
                                    select i;
                            #endregion



                            #region AddTileElement
                            Func<Point<double>, string, int, TileElement> AddTileElement =
                                (map_coords, source, height) =>
                                {
                                    var n = new TileElement
                                    {
                                        Position = map_coords,
                                        Image = new IHTMLImage(source),
                                        Source = source,
                                        Height = height
                                    };


                                    KnownTileElements.Add(n);
                                    ApplyTileToCanvas(map_coords.X, map_coords.Y, n.Image, height);
                                    n.Image.AttachTo(arena.Layers.Canvas);



                                    return n;
                                };
                            #endregion

                            #region RemoveAllTilesAt
                            Action<Point<double>> RemoveAllTilesAt =
                                map_coords =>
                                {
                                    foreach (var t in GetTileElementsAt(map_coords).ToArray())
                                    {
                                        t.Image.Orphanize();

                                        t.RemoveFrom(KnownTileElements);
                                        t.RemoveFrom(KnownDirtTileElements);



                                    }
                                };
                            #endregion


                            #region ReplaceTileWithDirt
                            Func<Point<double>, TileElement> ReplaceTileWithDirt =
                                map_coords =>
                                {
                                    RemoveAllTilesAt(map_coords);

                                    var r = AddTileElement(map_coords, TileResources.Dirt.Source, TileResources.Dirt.Height);

                                    r.AddTo(KnownDirtTileElements);

                                    return r;

                                };
                            #endregion

                            #region ReplaceTileWithNewBuilding
                            Func<Point<double>, TileElement> ReplaceTileWithNewBuilding =
                                map_coords =>
                                {
                                    var n = ReplaceTileWithDirt(map_coords);

                                    n.DirtAge = -200 - (3 + 5.Random());

                                    return n;
                                };
                            #endregion


                            #region interesting predicates
                            var IsGrass =
                                new[]
                                 {
                                     TileResources.Grass.Source,
                                     TileResources.Dirt.Source,
                                     //TileResources.DirtDirtGrass.Source,
                                     //TileResources.DirtGrassGrass.Source,
                                     //TileResources.Rocks.Source,
                                     TileResources.RoughLand.Source,
                                 }.ToEqualsAny();
                            var IsGrassStrict = TileResources.Grass.Source.ToEquals();
                            var IsRoad1 = TileResources.Road1.Source.ToEquals();
                            var IsRoad2 = TileResources.Road2.Source.ToEquals();
                            var IsTrack1 = TileResources.Track1.Source.ToEquals();
                            var IsTree = TileResources.Tree.Source.ToEquals();
                            var IsTileSelector = TileResources.TileSelector.Source.ToEquals();
                            #endregion



                            // create a draggable toolbar
                            #region creating the toolbar

                            var toolbar_color = Color.FromRGB(0x40, 0x40, 0x40);

                            var infotoolbar = ToolbarDialog.CreateToolbar(
                                new Point(64, 64),
                                new Point(200, 64), toolbar_color
                                );

                            var infotoolbar_content = new IHTMLDiv().AttachTo(infotoolbar.Control);

                            infotoolbar_content.style.SetLocation(2, 8, infotoolbar.Size.X - 6, infotoolbar.Size.Y - 12);
                            infotoolbar_content.SetDialogColor(infotoolbar.Color, false);
                            infotoolbar_content.onmousedown += Native.DisabledEventHandler;

                            Action<IStyle> SetInfoAnchorStyle =
                                style =>
                                {
                                    style.display = IStyle.DisplayEnum.block;
                                    style.textDecoration = "none";
                                    style.color = Color.White;
                                    style.textAlign = IStyle.TextAlignEnum.center;
                                };

                            new IHTMLAnchor("http://zproxy.wordpress.com", "zproxy.wordpress.com").AttachTo(infotoolbar_content).style.Aggregate(SetInfoAnchorStyle);
                            new IHTMLAnchor("http://jsc.sf.net", "jsc.sf.net").AttachTo(infotoolbar_content).style.Aggregate(SetInfoAnchorStyle);


                            var toolbar_size = new Point(96, 32);
                            var toolbar_pos = new Point(8, Native.window.Height - toolbar_size.Y - 8);

                            Console.WriteLine("toolbar!");
                            var toolbar = ToolbarDialog.CreateToolbar(toolbar_pos, toolbar_size, toolbar_color);

                            Native.window.onresize +=
                                delegate
                                {
                                    infotoolbar.ApplyPosition();
                                    toolbar.ApplyPosition();
                                };

                            infotoolbar.Control.Hide();
                            infotoolbar.Control.AttachToDocument();
                            toolbar.Control.AttachToDocument();

                            toolbar_btn_pause = new ToolbarButton(
                               toolbar, new btn_pause().src
                               )
                           {
                               Title = "Pause"
                           };

                            var aww = new aww();
                            var gong = new gong();

                            toolbar_btn_pause.Clicked +=
                                btn =>
                                {
                                    paused = btn.IsActivated;


                                    Dudes.ForEach(i => i.Paused = paused);
                                };

                            #region toolbar_btn_demolish
                            var toolbar_btn_demolish = new ToolbarButton(
                                toolbar, new btn_demolish().src
                            )
                            {
                                Title = "Demolish"
                            };



                            var ShowingTileSelector = default(Func<bool>);


                            #endregion


                            var toolbar_btn_track1 = new ToolbarButton(
                               toolbar, new btn_track1().src
                            ) { Title = "Build rail tracks" };

                            // var toolbar_btn_road2 = new ToolbarButton(
                            //   toolbar, new btn_road2().src
                            //) { Title = "Build road" };

                            // var toolbar_btn_road1 = new ToolbarButton(
                            //  toolbar, new btn_road1().src
                            // ) { Title = "Build road" };

                            var toolbar_btn_road1_road2 = new ToolbarButton(
                             toolbar, new btn_road1_road2().src
                            ) { Title = "Build road" };


                            /*
                            var toolbar_btn_sign = new ToolbarButton(
                               toolbar, "assets/ThreeDStuff/btn_sign.png"
                            );
                            */

                            var toolbar_btn_trees = new ToolbarButton(
                               toolbar, new btn_trees().src
                            ) { Title = "Build trees" };

                            var toolbar_btn_trees2 = new ToolbarButton(
                              toolbar, new btn_trees().src
                           ) { Title = "Build trees" };



                            var TileSelectorModes = new Dictionary<ToolbarButton, TileSelectorMode>
                            {
                                {toolbar_btn_demolish, TileSelectorMode.Rectangle},
                                {toolbar_btn_track1, TileSelectorMode.Horizontal},
                                //{toolbar_btn_road2, TileSelectorMode.Vertical},
                                //{toolbar_btn_road1, TileSelectorMode.Horizontal},
                                {toolbar_btn_road1_road2, TileSelectorMode.HorizontalOrVertical},
                                {toolbar_btn_trees, TileSelectorMode.Rectangle},
                                {toolbar_btn_trees2, TileSelectorMode.Rectangle},
                            };

                            var __before_error = "__before_error";

                            var __Keys = TileSelectorModes.Keys;
                            var __KeysArray = __Keys.ToArray();

                            var __after_error = "__after_error";


                            var toolbar_btngroup = new ToolbarButtonGroup
                            {
                                Buttons = __KeysArray
                            };




                            var toolbar_btn_city = new ToolbarButton(
                                toolbar, new btn_city().src
                            ) { Title = "Build city" };

                            var toolbar_btn_landinfo = new ToolbarButton(
                                toolbar, new btn_landinfo().src
                            ) { Title = "Show info" };

                            toolbar_btn_landinfo.Clicked +=
                                btn =>
                                {
                                    infotoolbar.Control.Show(btn.IsActivated);
                                };

                            ShowingTileSelector =
                                () => toolbar_btngroup.IsActivated;

                            var MultipleTileSelector = new List<TileElement>();


                            #region MultipleTileSelector_Clear
                            Action MultipleTileSelector_Clear =
                                delegate
                                {
                                    // framework bug: while iterating and the collection changes an exception sould be thrown
                                    foreach (var v in MultipleTileSelector.ToArray())
                                    {
                                        if (v.Image != null)
                                        {
                                            v.Image.Orphanize();
                                            v.Image = null;
                                        }

                                        v.RemoveFrom(KnownTileElements);
                                    }


                                    MultipleTileSelector.Clear();
                                };
                            #endregion

                            #region MultipleTileSelector_Add
                            Action<Point<double>> MultipleTileSelector_Add =
                                 p =>
                                 {
                                     AddTileElement(
                                         p,
                                         TileResources.TileSelector.Source,
                                         TileResources.TileSelector.Height
                                     ).AddTo(MultipleTileSelector);
                                 };
                            #endregion


                            // show tile selection
                            #region arena.MouseMove
                            arena.MouseMove +=
                               p =>
                               {
                                   if (paused)
                                       return;

                                   if (ShowingTileSelector())
                                   {
                                       if (arena.InSelectionMode)
                                           return;

                                       // get map coords from canvas coords
                                       var map_coords = GetNearestMapPosition(p);

                                       if (MultipleTileSelector.Count == 1)
                                       {
                                           var n = MultipleTileSelector.SingleOrDefault();

                                           ApplyTileToCanvas(map_coords.X, map_coords.Y, n.Image, n.Height);
                                       }
                                       else
                                       {
                                           MultipleTileSelector_Clear();
                                           MultipleTileSelector_Add(map_coords);
                                       }

                                       // must be on top of new dirt
                                       //SingleTileSelector.style.zIndex++;
                                   }
                               };
                            #endregion

                            #region GetActivatedTileSelectorMode
                            Func<TileSelectorMode> GetActivatedTileSelectorMode =
                                delegate
                                {
                                    if (toolbar_btngroup.ActivatedButton == null)
                                        return TileSelectorMode.Unknown;

                                    if (!TileSelectorModes.ContainsKey(toolbar_btngroup.ActivatedButton))
                                        return TileSelectorMode.Unknown;

                                    return TileSelectorModes[toolbar_btngroup.ActivatedButton];
                                };
                            #endregion


                            #region arena.SelectionPointsPreview - just apply the current TileSelectorMode
                            arena.SelectionPointsPreview +=
                                (from, to) =>
                                {
                                    if (paused)
                                        return;

                                    if (!ShowingTileSelector())
                                        return;

                                    //SingleTileSelector.Hide();

                                    var map_coords = new
                                        {
                                            from = GetNearestMapPosition(from),
                                            to = GetNearestMapPosition(to)
                                        };

                                    #region CurrentMode

                                    var CurrentMode = GetActivatedTileSelectorMode();

                                    if (CurrentMode == TileSelectorMode.Unknown)
                                        return;

                                    if (CurrentMode == TileSelectorMode.HorizontalOrVertical)
                                    {
                                        if ((map_coords.from.X - map_coords.to.X).Abs() > (map_coords.from.Y - map_coords.to.Y).Abs())
                                            CurrentMode = TileSelectorMode.Horizontal;
                                        else
                                            CurrentMode = TileSelectorMode.Vertical;
                                    }

                                    #endregion


                                    if (CurrentMode == TileSelectorMode.Horizontal)
                                    {
                                        MultipleTileSelector_Clear();

                                        foreach (var x in map_coords.from.X.ToInt32().RangeTo(map_coords.to.X.ToInt32()))
                                            MultipleTileSelector_Add(new Point<double> { X = x, Y = map_coords.from.Y });
                                    }


                                    if (CurrentMode == TileSelectorMode.Vertical)
                                    {
                                        MultipleTileSelector_Clear();

                                        foreach (var y in map_coords.from.Y.ToInt32().RangeTo(map_coords.to.Y.ToInt32()))
                                            MultipleTileSelector_Add(new Point<double> { X = map_coords.from.X, Y = y });
                                    }



                                    if (CurrentMode == TileSelectorMode.Rectangle)
                                    {
                                        MultipleTileSelector_Clear();

                                        foreach (var x in map_coords.from.X.ToInt32().RangeTo(map_coords.to.X.ToInt32()))
                                            foreach (var y in map_coords.from.Y.ToInt32().RangeTo(map_coords.to.Y.ToInt32()))
                                            {
                                                MultipleTileSelector_Add(new Point<double> { X = x, Y = y });
                                            }
                                    }
                                };
                            #endregion



                            #region UseCurrentToolAt
                            Action<Point<double>, TileSelectorMode> UseCurrentToolAt =
                                (map_coords, CurrentMode) =>
                                {
                                    //"UseCurrentToolAt".ToConsole();



                                    var Subject = GetTileElementsAt(map_coords).ToArray();
                                    var StatsQuery = Subject.Select(i => i.Source);


                                    if (toolbar_btn_demolish)
                                    {
                                        ReplaceTileWithDirt(map_coords);
                                    }

                                    #region toolbar_btn_trees
                                    if (toolbar_btn_trees)
                                    {
                                        Func<string, bool> IsOther = s =>
                                            !(IsGrass(s) || IsTileSelector(s));

                                        var Stats = new
                                        {
                                            GrassStrict = StatsQuery.Any(IsGrassStrict),
                                            Other = StatsQuery.Any(IsOther)
                                        };

                                        if (!Stats.Other)
                                        {
                                            if (!Stats.GrassStrict)
                                            {
                                                RemoveAllTilesAt(map_coords);
                                                AddTileElement(map_coords, TileResources.Grass.Source, TileResources.Grass.Height);
                                            }

                                            AddTileElement(map_coords, TileResources.Tree.Source, TileResources.Tree.Height);


                                        }
                                    }

                                    #endregion

                                    #region toolbar_btn_trees2
                                    if (toolbar_btn_trees2)
                                    {
                                        Func<string, bool> IsOther = s =>
                                            !(IsGrass(s) || IsTileSelector(s));

                                        var Stats = new
                                        {
                                            GrassStrict = StatsQuery.Any(IsGrassStrict),
                                            Other = StatsQuery.Any(IsOther)
                                        };

                                        if (!Stats.Other)
                                        {
                                            if (!Stats.GrassStrict)
                                            {
                                                RemoveAllTilesAt(map_coords);
                                                AddTileElement(map_coords, TileResources.Grass.Source, TileResources.Grass.Height);
                                            }

                                            AddTileElement(map_coords, TileResources.Tree2.Source, TileResources.Tree2.Height);


                                        }
                                    }

                                    #endregion

                                    #region toolbar_btn_track1
                                    if (toolbar_btn_track1)
                                    {
                                        #region Stats

                                        Func<string, bool> IsOther = s =>
                                            !(IsRoad2(s) || IsGrass(s) || IsTree(s) || IsTileSelector(s));

                                        var Stats = new
                                        {
                                            Grass = StatsQuery.Any(IsGrass),
                                            Road2 = StatsQuery.Any(IsRoad2),
                                            Other = StatsQuery.Any(IsOther)
                                        };
                                        #endregion

                                        if (!Stats.Other)
                                        {
                                            RemoveAllTilesAt(map_coords);

                                            if (!Stats.Road2)
                                                AddTileElement(map_coords, TileResources.Track1.Source, TileResources.Track1.Height);
                                            else
                                                AddTileElement(map_coords, TileResources.Road2_Track1.Source, TileResources.Road2_Track1.Height);
                                        }
                                        else
                                        {
                                            // should show that red error dialog now :)
                                            "Cannot build tracks!".ToConsole();
                                            foreach (var v in Subject)
                                            {
                                                v.Source.ToConsole();
                                            }
                                        }

                                    }

                                    #endregion

                                    bool ActiveIsRoad1 = false;
                                    bool ActiveIsRoad2 = false;

                                    if (toolbar_btn_road1_road2)
                                    {
                                        ActiveIsRoad1 = CurrentMode == TileSelectorMode.Horizontal;
                                        ActiveIsRoad2 = CurrentMode == TileSelectorMode.Vertical;
                                    }



                                    #region toolbar_btn_road1
                                    if (ActiveIsRoad1)
                                    {


                                        #region Stats

                                        Func<string, bool> IsOther = s =>
                                            !(IsRoad2(s) || IsTrack1(s) || IsGrass(s) || IsTree(s) || IsTileSelector(s));

                                        var Stats = new
                                        {
                                            Grass = StatsQuery.Any(IsGrass),
                                            Road2 = StatsQuery.Any(IsRoad2),
                                            Track1 = StatsQuery.Any(IsTrack1),
                                            Other = StatsQuery.Any(IsOther)
                                        };
                                        #endregion

                                        if (!Stats.Other)
                                        {
                                            RemoveAllTilesAt(map_coords);

                                            if (!Stats.Road2)
                                                AddTileElement(map_coords,
                                                    TileResources.Road1.Source,
                                                    TileResources.Road1.Height);
                                            else
                                                AddTileElement(map_coords, TileResources.Road1_Road2.Source, TileResources.Road1_Road2.Height);
                                        }
                                        else
                                        {
                                            // should show that red error dialog now :)
                                            "Cannot build tracks!".ToConsole();

                                        }

                                    }

                                    #endregion


                                    #region toolbar_btn_road2
                                    if (ActiveIsRoad2)
                                    {


                                        #region Stats

                                        Func<string, bool> IsOther = s =>
                                            !(IsRoad1(s) || IsTrack1(s) || IsGrass(s) || IsTree(s) || IsTileSelector(s));




                                        var Stats = new
                                        {
                                            Grass = StatsQuery.Any(IsGrass),
                                            Road1 = StatsQuery.Any(IsRoad1),
                                            Track1 = StatsQuery.Any(IsTrack1),
                                            Other = StatsQuery.Any(IsOther)
                                        };
                                        #endregion

                                        if (!Stats.Other)
                                        {
                                            RemoveAllTilesAt(map_coords);

                                            if (Stats.Road1)
                                                AddTileElement(map_coords, TileResources.Road1_Road2.Source, TileResources.Road1_Road2.Height);
                                            else if (!Stats.Track1)
                                                AddTileElement(map_coords, TileResources.Road2.Source, TileResources.Road2.Height);
                                            else
                                                AddTileElement(map_coords, TileResources.Road2_Track1.Source, TileResources.Road2_Track1.Height);
                                        }
                                        else
                                        {
                                            // should show that red error dialog now :)
                                            "Cannot build tracks!".ToConsole();

                                        }

                                    }

                                    #endregion
                                };
                            #endregion

                            #region arena.ApplyPointsSelection - using current tool
                            arena.ApplyPointsSelection +=
                                 (from, to, ev) =>
                                 {
                                     if (!ShowingTileSelector())
                                         return;

                                     if (paused)
                                         return;

                                     var map_coords = new
                                     {
                                         from = GetNearestMapPosition(from),
                                         to = GetNearestMapPosition(to)
                                     };



                                     #region CurrentMode

                                     var CurrentMode = GetActivatedTileSelectorMode();

                                     if (CurrentMode == TileSelectorMode.Unknown)
                                         return;

                                     if (CurrentMode == TileSelectorMode.HorizontalOrVertical)
                                     {
                                         if ((map_coords.from.X - map_coords.to.X).Abs() > (map_coords.from.Y - map_coords.to.Y).Abs())
                                             CurrentMode = TileSelectorMode.Horizontal;
                                         else
                                             CurrentMode = TileSelectorMode.Vertical;
                                     }

                                     #endregion

                                     Console.WriteLine("mode: " + CurrentMode);

                                     if (CurrentMode == TileSelectorMode.Vertical)
                                     {
                                         MultipleTileSelector_Clear();

                                         foreach (var y in map_coords.from.Y.ToInt32().RangeTo(map_coords.to.Y.ToInt32()))
                                         {
                                             UseCurrentToolAt(new Point<double> { X = map_coords.from.X, Y = y }, CurrentMode);

                                         }
                                     }

                                     if (CurrentMode == TileSelectorMode.Horizontal)
                                     {
                                         MultipleTileSelector_Clear();

                                         foreach (var x in map_coords.from.X.ToInt32().RangeTo(map_coords.to.X.ToInt32()))
                                             UseCurrentToolAt(new Point<double> { X = x, Y = map_coords.from.Y }, CurrentMode);
                                     }

                                     if (CurrentMode == TileSelectorMode.Rectangle)
                                     {
                                         MultipleTileSelector_Clear();

                                         foreach (var x in map_coords.from.X.ToInt32().RangeTo(map_coords.to.X.ToInt32()))
                                             foreach (var y in map_coords.from.Y.ToInt32().RangeTo(map_coords.to.Y.ToInt32()))
                                             {
                                                 UseCurrentToolAt(new Point<double> { X = x, Y = y }, CurrentMode);
                                             }
                                     }


                                     MultipleTileSelector_Clear();
                                     MultipleTileSelector_Add(map_coords.to);

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

                            #region arena.SelectionClick - just use the current tool
                            arena.SelectionClick +=
                             (p, ev) =>
                             {
                                 if (paused)
                                     return;

                                 if (!ShowingTileSelector())
                                     return;



                                 var map_coords = GetNearestMapPosition(p);

                                 #region CurrentMode
                                 var CurrentMode = GetActivatedTileSelectorMode();

                                 if (CurrentMode == TileSelectorMode.Unknown)
                                     return;

                                 if (CurrentMode == TileSelectorMode.HorizontalOrVertical)
                                 {
                                     var map_coords0 = Translator.ConvertCanvasToMap(p.ToDouble()).Wrap(1).Abs();

                                     if (map_coords0.X > map_coords0.Y)
                                         CurrentMode = TileSelectorMode.Horizontal;
                                     else
                                         CurrentMode = TileSelectorMode.Vertical;
                                 }
                                 #endregion


                                 UseCurrentToolAt(map_coords, CurrentMode);


                                 MultipleTileSelector_Clear();
                                 MultipleTileSelector_Add(map_coords);

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




                            #region toolbar_btngroup.Clicked - a tool has been selected
                            toolbar_btngroup.Clicked +=
                                btn =>
                                {
                                    arena.ShowSelectionRectangle = !ShowingTileSelector();

                                    if (!ShowingTileSelector())
                                        MultipleTileSelector_Clear();
                                };
                            #endregion



                            #endregion


                            #region arena.SelectionClick - move dudes
                            arena.SelectionClick +=
                                (p, ev) =>
                                {
                                    if (paused)
                                        return;

                                    if (ShowingTileSelector())
                                        return;

                                    var selection = Dudes.Where(i => i.IsSelected).ToArray();


                                    //KnownCanvasPosition = p;

                                    var target = Translator.ConvertCanvasToMap(p.ToDouble()).BoundTo(MapSize);

                                    if (selection.Length == 0)
                                    {
                                        // single select?

                                        return;
                                    }

                                    selection.WithEach(
                                        v =>
                                        {
                                            if (v.AnimationInfo.Frames_Stand[0].Source == Frames.WolfSoldier[0].Source)
                                            {
                                                CloneAffirmative.play();
                                                CloneAffirmative = new EN_000002();
                                            }
                                            else if (v.AnimationInfo.Frames_Stand[0].Source == MyFrames_TwinClone.Frames_Stand[0].Source)
                                            {
                                                CloneAffirmative.play();
                                                CloneAffirmative = new EN_000002();
                                            }
                                            else
                                            {
                                                Argh.play();
                                                Argh = new Argh();
                                            }

                                        }
                                    );

                                    if (selection.Length == 1)
                                    {

                                        var canvas = Translator.ConvertMapToCanvas(target);

                                        //canvas.X += GetCenter().X;
                                        //canvas.Y += GetCenter().Y;

                                        //new
                                        //{
                                        //    target = new { target.X, target.Y },
                                        //    canvas = new { canvas.X, canvas.Y }
                                        //}.ToConsole(); ;

                                        selection.ForEach(i => i.WalkTo(
                                            canvas
                                            ));
                                    }
                                    else
                                    {
                                        #region Circle

                                        var center = GetCenter();


                                        #region GetRotatedTargetPoint
                                        Func<double, double, Point<double>> GetRotatedTargetPoint =
                                            (direction, distance) =>
                                                new Point<double>
                                                {
                                                    X = target.X + (Math.Cos(direction) * distance),
                                                    Y = target.Y + (Math.Sin(direction) * distance),
                                                };
                                        #endregion

                                        Func<Point<double>, Point> OffsetToCenter =
                                            mcanvas =>
                                                new Point
                                                (
                                                    (mcanvas.X + center.X).ToInt32(),
                                                    (mcanvas.Y + center.Y).ToInt32()
                                                );

                                        var dest =
                                            from index in selection.Length.ToRange()
                                            let direction = (((double)index / (selection.Length)) * (Math.PI * 2)).ToConsole()
                                            let distance = 0.5
                                            let mtarget = GetRotatedTargetPoint(direction, distance)
                                            let mcanvas = Translate(mtarget.X, mtarget.Y)

                                            select new
                                            {
                                                index,
                                                canvas = OffsetToCenter(mcanvas)
                                            };

                                        foreach (var v in dest)
                                        {
                                            selection[v.index].WalkTo(v.canvas.ToDouble());
                                        }

                                        #endregion

                                    }
                                };
                            #endregion

                            #region arena.ApplySelection
                            arena.ApplySelection +=
                                (r, ev) =>
                                {
                                    if (paused)
                                        return;

                                    if (ShowingTileSelector())
                                        return;

                                    Console.WriteLine("ApplySelection " + new { ev.shiftKey });

                                    foreach (var v in Dudes)
                                    {
                                        // chrome always reports shiftKey?

                                        //if (ev.shiftKey)
                                        //    v.IsSelected |= r.Contains(v.CurrentLocation.ToInt32());
                                        //else
                                        v.IsSelected = r.Contains(v.CurrentLocation.ToInt32());
                                    }
                                };
                            #endregion


                            #region toolbar_btn_city.Clicked
                            var toolbar_btn_city_StopTimer = default(Action);

                            toolbar_btn_city.Clicked +=
                                delegate
                                {
                                    if (toolbar_btn_city_StopTimer != null)
                                    {
                                        Console.WriteLine("stopping city building");
                                        toolbar_btn_city_StopTimer();
                                        toolbar_btn_city_StopTimer = null;

                                        return;
                                    }

                                    #region TryBuildHere
                                    Func<Point<double>, bool> TryBuildHere =
                                        n =>
                                        {
                                            if (IsDefined(n.X, n.Y))
                                                if (GetTileElementsAt(n).All(i => IsGrassStrict(i.Source)))
                                                {
                                                    new IHTMLAudio[]
                                                                {
                                                                   Hammertime,
                                                                   Sawtime,
                                                                   StoneHammerTime
                                                                }.Random().With(
                                                       snd =>
                                                       {
                                                           snd.play();

                                                           Hammertime = new SAMPLES234 { volume = 0.1 };
                                                           Sawtime = new SAMPLES216 { volume = 0.1 };
                                                           StoneHammerTime = new SAMPLES233 { volume = 0.1 };
                                                       }
                                                   );

                                                    ReplaceTileWithNewBuilding(n);


                                                    return true;
                                                }

                                            return false;
                                        };
                                    #endregion


                                    var Query = from i in KnownTileElements
                                                let Road2 = IsRoad2(i.Source)
                                                let Road1 = IsRoad1(i.Source)
                                                where Road2 || Road1
                                                select new { i, Road1, Road2 };


                                    Console.WriteLine("starting city building");
                                    toolbar_btn_city_StopTimer = new Timer(
                                        t =>
                                        {
                                            if (paused)
                                                return;

                                            var v = Query.Random();
                                            Console.WriteLine("try building city at road {0}", new { v.i.Position.X, v.i.Position.Y });



                                            if (v.Road2)
                                            {
                                                if (0.5.ByChance())
                                                    TryBuildHere(v.i.Position.Round().WithOffset(-1, 0));
                                                else
                                                    TryBuildHere(v.i.Position.Round().WithOffset(1, 0));
                                            }
                                            else
                                                if (v.Road1)
                                                {
                                                    if (0.5.ByChance())
                                                        TryBuildHere(v.i.Position.Round().WithOffset(0, -1));
                                                    else
                                                        TryBuildHere(v.i.Position.Round().WithOffset(0, 1));
                                                }

                                        },
                                        3000, 20000

                                    ).Stop;

                                    //toolbar_btn_city.RaiseClicked
                                };
                            #endregion

                            toolbar_btn_city.RaiseClicked();

                            #region grass growth
                            1500.AtInterval(
                                t =>
                                {
                                    if (paused)
                                        return;

                                    //"got dirt?".ToConsole();

                                    #region KnownDirtTileElements
                                    foreach (var v in KnownDirtTileElements.ToArray())
                                    {
                                        new { v.DirtAge, v.Position.X, v.Position.Y }.ToConsole();

                                        if (v.DirtAge > 5)
                                        {
                                            v.RemoveFrom(KnownDirtTileElements);


                                        }

                                        #region House1a building animation
                                        if (v.Source == TileResources.House1a.Source)
                                            if (v.DirtAge > 3)
                                            {
                                                new IHTMLAudio[]
                                                                {
                                                                   Hammertime,
                                                                   Sawtime,
                                                                   StoneHammerTime
                                                                }.Random().With(
                                                    snd =>
                                                    {
                                                        snd.play();

                                                        Hammertime = new SAMPLES234 { volume = 0.1 };
                                                        Sawtime = new SAMPLES216 { volume = 0.1 };
                                                        StoneHammerTime = new SAMPLES233 { volume = 0.1 };
                                                    }
                                                );

                                                RemoveAllTilesAt(v.Position);
                                                AddTileElement(v.Position,
                                                    TileResources.House1b.Source,
                                                    TileResources.House1b.Height
                                                    )
                                                    .AddTo(KnownDirtTileElements);
                                            }

                                        if (v.Source == TileResources.House1b.Source)
                                            if (v.DirtAge > 3)
                                            {
                                                new IHTMLAudio[]
                                                                {
                                                                   Hammertime,
                                                                   Sawtime,
                                                                   StoneHammerTime
                                                                }.Random().With(
                                                    snd =>
                                                    {
                                                        snd.play();

                                                        Hammertime = new SAMPLES234 { volume = 0.1 };
                                                        Sawtime = new SAMPLES216 { volume = 0.1 };
                                                        StoneHammerTime = new SAMPLES233 { volume = 0.1 };
                                                    }
                                                );

                                                RemoveAllTilesAt(v.Position);
                                                AddTileElement(v.Position,
                                                    TileResources.House1x.Source,
                                                    TileResources.House1x.Height
                                                    )
                                                    .AddTo(KnownDirtTileElements);
                                            }

                                        #endregion


                                        #region make that dirt grow into grass over time
                                        if (v.Source == TileResources.Dirt.Source)
                                        {
                                            if (v.DirtAge == -200)
                                            {
                                                RemoveAllTilesAt(v.Position);


                                                var NewHouse = new[]
                                            {
                                                TileResources.House1a,
                                                //TileResources.House2,
                                                //TileResources.House3,
                                                //TileResources.House4,
                                                //TileResources.House5a,
                                                //TileResources.House5a

                                            }.Random();

                                                AddTileElement(v.Position,
                                                    NewHouse.Source,
                                                    NewHouse.Height
                                                    )
                                                    .AddTo(KnownDirtTileElements);
                                            }

                                            if (v.DirtAge > 3)
                                            {
                                                RemoveAllTilesAt(v.Position);

                                                v.RemoveFrom(KnownDirtTileElements);

                                                AddTileElement(v.Position, TileResources.Grass.Source, TileResources.Grass.Height)
                                                    .AddTo(KnownDirtTileElements);
                                            }
                                        }


                                        #endregion

                                        v.DirtAge++;
                                    }
                                    #endregion

                                }
                            );
                            #endregion


                            // wont work correctly on IE
                            //Native.Window.onblur +=
                            //    delegate
                            //    {
                            //        if (!toolbar_btn_pause.IsActivated)
                            //            toolbar_btn_pause.RaiseClicked();
                            //    };

                            Console.WriteLine("ready!");

                            info.innerHTML = "LBA Redux";

                            if (!paused)
                                PauseFogTween.Value = 0;


                            toolbar.Buttons.WithEach(
                              btn =>
                              {
                                  btn.Clicked +=
                                      delegate
                                      {
                                          click.play();
                                          click = new click(); ;
                                      };
                              }
                              );

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

                                };

                            yield(this);
                        });

                };
            #endregion


            StartLoadingDudeAnimationInfo(MyFrames_Soldier);
            StartLoadingDudeAnimationInfo(MyFrames_Imp);
            StartLoadingDudeAnimationInfo(MyFrames_TwinClone);

            TileResourcesList.ForEach(i => StartLoadingSingleImage(i.Source));



            new Timer(
                t =>
                {
                    info.innerHTML = ImagesThatAreCurrentlyLoadingCounter + " of " + ImagesThatAreCurrentlyLoading.Count;

                    if (ImagesThatAreCurrentlyLoading.Count == ImagesThatAreCurrentlyLoadingCounter)
                    {
                        t.Stop();
                        AllImagesLoaded();
                    }
                }
            ).StartInterval(1);
        }
Beispiel #19
0
        // vNext should be semi 3D - http://www.freeworldgroup.com/games/3dworm/index.html

        public Game()
        {
            //typeof(ConsoleWorm).ToWindowText();

            var canvas = new IHTMLDiv();

            canvas.style.overflow = IStyle.OverflowEnum.hidden;
            canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);
            canvas.style.backgroundColor = Color.Black;
            canvas.AttachToDocument();
            //canvas.style.position = IStyle.PositionEnum.relative;


            new HTML.Images.FromAssets.avatar14683_21().InvokeOnComplete(
                 scull =>
                 {
                     new global::ConsoleWorm.HTML.Audio.FromAssets.applause().play();

                     var zoom = 24;

                     Func<int> RoomWidth = () => (Native.window.Width / zoom).ToInt32();
                     Func<int> RoomHeight = () => ((Native.window.Height /*- scull.height - 16*/) / zoom).ToInt32();

                     var score = 0;
                     var status = new IHTMLDiv("0$");
                     var isdead = false;
                     var paused = true;


                     status.style.color = Color.Green;
                     status.style.fontFamily = IStyle.FontFamilyEnum.Consolas;


                     scull.AttachTo(canvas);
                     scull.style.SetLocation(
                         8,
                         Native.window.Height - scull.height - 8);


                     status.AttachTo(canvas);
                     status.style.SetLocation(
                         8 + scull.width + 8,
                         Native.window.Height - scull.height
                     );
                     Native.window.onresize +=
                         delegate
                         {
                             canvas.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);
                             scull.style.SetLocation(
                                  8,
                                  Native.window.Height - scull.height - 8);
                             status.style.SetLocation(
                                    8 + scull.width + 8,
                                    Native.window.Height - scull.height
                                );
                         };





                     Func<Point> GetRandomLocation =
                         () => new Point(
                                 (RoomWidth() - 1).Random(),
                                 (RoomHeight() - 1).Random()
                             );

                     var game_colors = new
                     {
                         worm = new
                         {
                             active = Color.FromRGB(0, 0xff, 0),
                             inactive = Color.FromRGB(0, 0x7F, 0),
                             excited = Color.FromRGB(0xff, 0xff, 0),
                         }

                     };

                     Func<Point, Point> Wrapper =
                         p => new Point((p.X + RoomWidth()) % RoomWidth(), (p.Y + RoomHeight()) % RoomHeight());


                     Func<Apple> CreateApple =
                         () => new Apple
                         {
                             GetRandomLocation = GetRandomLocation,
                             GetZoom = () => zoom,
                             Wrapper = Wrapper
                         }.MoveToRandomLocation();


                     var apples = new List<Apple>
                     {
                     };

                     10.Times(() =>
                         apples.Add(
                             CreateApple()
                         )
                     );

                     apples.ForEach(a => a.AttachTo(canvas));





                     var worm = new Worm
                     {
                         Wrapper = Wrapper,
                         Location = new Point(4, 8),
                         GetZoom = () => zoom,
                         Canvas = canvas,
                         Vector = new Point(0, 1),
                         Color = game_colors.worm.active
                     }
                     .Grow()
                     .GrowToVector()
                     .GrowToVector();



                     Action<int> AddScore = x =>
                     {
                         score += x;

                         if (isdead)
                             status.innerText = score + "$ - Game Over - Enter to continue";
                         else if (paused)
                             status.innerText = score + "$ - Paused - Zoom: " + zoom;
                         else
                             status.innerText = score + "$";

                         worm.Color = game_colors.worm.excited;
                         status.style.color = JSColor.Yellow;
                     };


                     100.AtInterval(
                         t =>
                         {
                             if (paused)
                             {
                                 // slowdown
                                 if (t.Counter % 4 == 0)
                                 {
                                     if (worm.Color == game_colors.worm.active)
                                     {
                                         worm.Color = game_colors.worm.inactive;
                                         status.style.color = game_colors.worm.inactive;
                                     }
                                     else
                                     {
                                         worm.Color = game_colors.worm.active;
                                         status.style.color = game_colors.worm.active;
                                     }

                                 }

                                 return;
                             }

                             if (worm.Parts.Any(i => i.Location.IsEqual(worm.NextLocation)))
                             {
                                 paused = true;
                                 isdead = true;

                                 AddScore(0);
                                 new global::ConsoleWorm.HTML.Audio.FromAssets.buzzer().play();

                                 return;
                             }

                             worm.Color = game_colors.worm.active;
                             status.style.color = Color.Green;
                             worm.GrowToVector();

                             // did we find an apple?
                             var a = apples.Where(i => i.Location.IsEqual(worm.Location)).ToArray();

                             if (a.Length > 0)
                             {
                                 foreach (var v in a)
                                 {
                                     v.MoveToRandomLocation();
                                 }

                                 new global::ConsoleWorm.HTML.Audio.FromAssets.tick().play();

                                 AddScore(1);
                             }
                             else
                             {
                                 worm.Shrink();
                             }
                         }
                     );

                     var map = new[]
                        {
                            new { KeyCode = 38, Point = new Point(0, -1)}, // up
                            new { KeyCode = 37, Point = new Point(-1, 0)}, // left
                            new { KeyCode = 39, Point = new Point(1, 0)}, // right
                            new { KeyCode = 40, Point = new Point(0, 1)}, // down,

                              new { KeyCode = (int)System.Windows.Forms.Keys.W, Point = new Point(0, -1)}, // up
                            new { KeyCode =  (int)System.Windows.Forms.Keys.A, Point = new Point(-1, 0)}, // left
                            new { KeyCode =  (int)System.Windows.Forms.Keys.D, Point = new Point(1, 0)}, // right
                            new { KeyCode =  (int)System.Windows.Forms.Keys.S, Point = new Point(0, 1)}, // down
                        };

                     Func<IEvent, bool> IsPauseKey =
                         ev => ev.IsKeyCode("pP") || ev.KeyCode == 8504;

                     var PreviousKeyCode = 40;

                     Native.Document.body.onselectstart +=
                        ev =>
                        {
                            ev.PreventDefault();
                            ev.StopPropagation();
                        };


                     Action<IEvent> AtClick =
                         ev =>
                         {

                             ev.PreventDefault();
                             ev.StopPropagation();
                             var KeyCode = PreviousKeyCode;

                             if (ev.CursorX < Native.window.Width / 2)
                             {
                                 if (KeyCode == 38) KeyCode = 37;
                                 else if (KeyCode == 37) KeyCode = 40;
                                 else if (KeyCode == 40) KeyCode = 39;
                                 else if (KeyCode == 39) KeyCode = 38;
                                 // turn left
                             }
                             else
                             {
                                 if (KeyCode == 38) KeyCode = 39;
                                 else if (KeyCode == 37) KeyCode = 38;
                                 else if (KeyCode == 40) KeyCode = 37;
                                 else if (KeyCode == 39) KeyCode = 40;


                                 // turn right
                             }


                             if (isdead)
                             {

                                 while (worm.Parts.Count > 2)
                                     worm.Shrink();

                                 paused = false;
                                 isdead = false;
                                 AddScore(-score);
                                 new global::ConsoleWorm.HTML.Audio.FromAssets.reveal().play();
                                 return;
                             }


                             if (paused)
                             {
                                 paused = !paused;

                                 if (!paused)
                                 {
                                     worm.Color = game_colors.worm.active;
                                     status.style.color = game_colors.worm.active;
                                 }

                                 canvas.requestFullscreen();

                                 AddScore(0);
                                 new global::ConsoleWorm.HTML.Audio.FromAssets.reveal().play();

                                 return;
                             }

                             if (!paused)
                             {
                                 var v = map.SingleOrDefault(i => i.KeyCode == KeyCode);

                                 if (v != null)
                                 {
                                     ev.PreventDefault();


                                     if ((worm.Vector + v.Point).IsZero())
                                         return;

                                     PreviousKeyCode = v.KeyCode;
                                     worm.Vector = v.Point;
                                 }

                             }
                         };

                     Native.Document.body.onclick += AtClick;


                     #region onkeyup
                     Native.Document.onkeyup +=
                         ev =>
                         {

                             if (isdead)
                                 if (ev.IsReturn)
                                 {

                                     while (worm.Parts.Count > 2)
                                         worm.Shrink();

                                     paused = false;
                                     isdead = false;
                                     AddScore(-score);
                                     new global::ConsoleWorm.HTML.Audio.FromAssets.reveal().play();
                                 }

                             if (!paused)
                             {
                                 var v = map.SingleOrDefault(i => i.KeyCode == ev.KeyCode);

                                 if (v != null)
                                 {
                                     ev.PreventDefault();


                                     if ((worm.Vector + v.Point).IsZero())
                                         return;

                                     worm.Vector = v.Point;
                                 }

                                 if (ev.IsReturn)
                                 {
                                     apples.Add(
                                         CreateApple().AttachTo(canvas)
                                     );
                                 }
                                 else
                                     if (ev.KeyCode == 33)
                                 {
                                     zoom--;
                                     zoom = zoom.Max(8);

                                     apples.ForEach(a => a.MoveToLocation());
                                     worm.Parts.ForEach(p => p.MoveToLocation());
                                 }
                                 else if (ev.KeyCode == 34)
                                 {
                                     zoom++;
                                     zoom = zoom.Min(64);
                                     apples.ForEach(a => a.MoveToLocation());
                                     worm.Parts.ForEach(p => p.MoveToLocation());
                                 }


                             }

                             if (!isdead)
                                 if (IsPauseKey(ev))
                                 {
                                     paused = !paused;

                                     if (!paused)
                                     {
                                         worm.Color = game_colors.worm.active;
                                         status.style.color = game_colors.worm.active;
                                     }

                                     AddScore(0);
                                 }

                         };
                     #endregion



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

            //page.body.css.after.contentImage = new HTML.Images.FromAssets.Anonymous_LogosSingle();

            var s = new ISVGSVGElement
            {

            };

            var f = new ISVGForeignObject().AttachTo(s);
            //requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">

            //f.setAttribute("requiredFeatures", "http://www.w3.org/TR/SVG11/feature#Extensibility");

            // http://starkravingfinkle.org/blog/2007/07/firefox-3-svg-foreignobject/
            // http://stackoverflow.com/questions/11194403/svg-foreignobject-not-showing-in-chrome
            var div = new IHTMLDiv
            {
            };

            var divbody = new IHTMLDiv
            {
                innerHTML = "I like <span style='color:white; text-shadow:0 2px 2px blue;'>cheese</span>"
            }.AttachTo(div);
            // https://groups.google.com/forum/#!topic/svg-edit/60HICxGWFNE
            // http://www.w3.org/TR/SVG11/extend.html#ForeignObjectElement

            // http://css.dzone.com/articles/securing-pixel-data-svg-and
            // view-source:http://starkravingfinkle.org/blog/wp-content/uploads/2007/07/foreignobject-transform.svg
            // http://stackoverflow.com/questions/6849192/what-can-be-rendered-in-foreignobject-element-when-svg-is-embedded-in-html5
            new StockToolboxImageForWebGLComponent().AttachTo(divbody);

            new Anonymous_LogosSingle().AttachTo(divbody);

            div.style.fontFamily = IStyle.FontFamilyEnum.Verdana;
            div.style.fontSize = "40px";
            div.style.display = IStyle.DisplayEnum.inline_block;

            div.AttachToDocument();

            //page.body.css.before.content = new { div.clientWidth, div.clientHeight }.ToString();



            #region do
            new IHTMLButton { "do" }.AttachToDocument().WhenClicked(
                button =>
                {
                    //div.querySelectorAll("img").WithEach(
                    div.ImageElements().WithEach(
                        q =>
                        {
                            q.src = q.toDataURL();

                        }
                    );

                    button.Orphanize();

                    //s.width
                    //s.setAttribute("width", div.clientWidth + 0);
                    //s.setAttribute("height", div.clientHeight + 0);

                    s.width = div.clientWidth;
                    s.height = div.clientHeight;

                    div.AttachTo(f);


                    //page.body.css.before.content = xmlstring;




                    // var data =
                    //"<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
                    //  "<foreignObject width='100%' height='100%'>" +
                    //    "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
                    //      "<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>cheese</span>" +
                    //    "</div>" +
                    //  "</foreignObject>" +
                    //"</svg>";

                    //                    var ss = @"<svg xmlns='http://www.w3.org/2000/svg' width='600' height='200'>
                    //<foreignObject width='100%' height='100%'>
                    //<HTML xmlns='http://www.w3.org/1999/xhtml'>
                    //<BODY style=' font-size: 30px;'>
                    //This is <span style='color: green'>HTML</span>.
                    //An img: <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABmJLR0QA/wD/AP+gvaeTAAAAB3RJTUUH2wUDABwN9r5HMgAAFv1JREFUaIG9mnlgVNXZ/z937txZk5kkk2SSTBZCNghJWMJi0FYioiioUGQXEF+1VWgrUvVV+kNcXgVXtIUCtYIbFOSt1gKFaJFFElYDhEAgK9n3ZSazz9z7/hEJ0Gor1P6ev+6cc8/zPN/7nPM833POCPwHJDcuNDJEr7zc4QpMbHUErE6frNZLqkCyRVOiAnePJ5ja4QpGuP2yWlEgK1ZvD8pyZ6hG/LzdL/53SW1P17XaFH4o53OsGE1Gw4ctjmBes90f5fDKqkt9Y5ONzBkRzqclPZxudJObYECnFrCZJTwBhd1lDsanhTDUpqfFEWitbPVs3F7S8wwgX2kjNzn8w4DXYzzV6J76HwFywwDTmFaHZ49RI5oDikJFm5ep2WaSLRpO1Ln52wUHggCCIGAxiuSnhhBvlrjQ5sXhlQnKkDfAQGOPn3PNHvLTQjnZ4KprcgSCKgHxhtvujX7gZ4u0sbGxDE4bKLv9sviDArkjFW2kOXyFVq16JMIomtt6A3gDCkFZoaHHT48niCxDU6+fTmeQmFA14QY1na4ALY4AAy0axqWGkBalZddZO0NidNR3+/hbuRO3vy8YTzzxBC+//DKiKNLY2EjqgIRvBaK+XhD/71Zrdm6S4f3ievews80eKju8HKtzEaYXGW7TMzrRwNsH2wnICgCSKCCpVQyJ0TIiPpwIvciFdi8fn+zm3SOdAJh0Il9eAQJg9uzZiGKf30ePHiVMr3Jf2f9vAfnlrXGJ2TZp6+fnHYO/uOAgxaIlNVLL6CQD3oDCiToXv/2qnXCDSHtvAAXwBxXqu3xkRGl5ZmcTADenhLBlXhJ/Ot3Dhye6CNGocP2dk5IkAeD1elm8eDExoeojTfbADwNklFX6VVGNa/CpRjf35YZzptnDn0p66HBeNqBVC9yUbGTyEBM7z9o52+yhrNXLoGgtZ1s8NNv9+IMKr+xtZfntMdw40MjvDnVgkK4Gc+7cObKysvjss8/obmuSQ6OkR67H53+QFyfHj/79zETP/FERSm6CQQEUUSUosSZJiTSqlYdusCjhelEBFECxmSVl2QSrcuSxNOX5iTHKcJteWXJzlCKJgrJ6ik1JDNcob9wTpyybYFU0akG5fZCpfyygaLVaZenSpQqgDLXp3/8uv651sQs7Hhp4vrDamebxy/woJQRriJqKDh8lTW7uHmJCr1HRosSw7NPzpFmNDI3V093dTk6MlhiTRE2njxHxep7Z2YRaFBifFsKvdzXzh1kJrCvsINIocqLezcVOX79RSRTItGrPnmr0ZH0D8B/kH1b/P5NXp2c8UdEtzXrnUD0DLVpuSQuhwxlkXWEHj/04Cp0kMWjuq6RMe5qmHjeWAVk8+9uPyL91EhUHt/ObA63MGxmOAqw91MHX9S7mj4zAG1TY8nUXT4+P5p4sM+F6kaIaF9GhagZF63huYiyThpjrcuO19Z+f7y3/t4DkgvT4mo0Hbrh3EZveWcfDeRb2VvRyssFNg92PxahhwuPv4E8cw649BYSEhLBq1SrcXh9ZY24mXg+P/343mVYdJY0ePj3TgwK0O4MsvimS9UWdfFXtJEwvMiHDxP2jwrl3aBg7ztpZX9RBqEYV+5Oc8Nk3DjSEfFpi//zv/VN9i8/fKr9fv2jd7iOlHCg8zN0jBwAgqQQiDCLP3GrlfKuPRtGKy+1mx44dRERE8JOf/IQ1a9YgaTTIA/IYmWDgQpuXHWft/XoPVvaiEQUe+3EkjT1+3jncSUO3D1EloFELRIX05aPdZXZKmtzCkBj9r9bPsD1zXRE5/uYDzxf22h5z+hUulJ5iZkwtfyzuIigrGLUiTfYAt6YbGTDhv9DoQyguLiY8PJzz588TGxvL8uXLKTh4hGcnxDImTiHOLBFUYLBVx8LREbT2BvHLEGeSKKxx0uEKkp8agkoQyEs28pdSO5IocP/oCHRqFRa9dOOASMMXX5bbG64pIqm3zH7GkphGZmYmVcUH6Xb5SY/SMnmImTC9yMSMUML0IuEGLZIkUVdXR35+PkajkYSEBF5//XW+2PslY2ctpd0ZYPX+Np6fGMPy26zcNDCEZ3c3o1cLjEsNAeBci4f1RR0AGCQVM4aFUdftp+abBKCVBJ3f73uSK5LVv6wjt+VYkxsrzskR4aniyfY/kBIXQaSxkxuSDH10w6lGo+7TF3S0c6T8LJs3byYQCPDCCy+gUqlobW3l7bffZs/WdzlaWoNBc/n7rS9s58cpRu7MNFHR7gX6stR9ueH977Q7A+QNMDLYqutvG2YzhF7p57+MSJTov3/fllckq8pFe/AES+4dhUoFFqMalQCDrlAedHbxox/9iM/2bOa1zXP57/+ZwzPPPMPRo0eJ1Mo8OjTAmCQD8WaJqg4fX1b08sHxLhaOjuj7+t8AbLb7qe/2AyArEG4Q0aoFNOLlapEYoZnw26m2+d8JZNWqVVchvXNIaERDj5/Fjy4kqWgYzUU7r1KouqISCYLA4cOH2V+zgj279pI4toOnnnqKnpY6RnX9hcp2Nw7BxB8em0G5J4bW3r650eroYwSxJom4b6j9B8f7tiR2T5Ctxd2kRWpptPsv2wJizJr/+k4gbrfbW1BQEHfpd6Pdnzo128z/3BKJrbUItXQ5PwT9Ms5uL64eD452F/VVVax6+SUq95tIGRxGT6mN5Y8/QuG2t3EakzjgTiMgmRgwMJlfvb2Zs8oAJI0GZ3gWqhArApCXZABgf2Uvaw+1E6YXGWjRICsKkYarV4IgoLn03N/z0ksvWW677baw3NzcqqKiIsOl9n3lvab6ZhcTB+pJTDbj9QQpP9+J7JeRAzIarRq300dbvYPi1meZFQWDrXpEUy4HTtfQ2etEiMtk4ortONwBHrkxko7TnxM6cQkb//gJt4wfjycqk4FjEmg5/EecwW4AfEGFkg4NA0bP4HHOsmD1J+TEGbkxWd8PxBqqHjFnbFjS5sLui+qHH35YysvLs1it1q7c3NzOkydPDjWbzbXHjx+PLfr1HTdFCcGY+EQTWoOEooAoQrTVSFuLC0EQ8PmCBFAR1OtoOXmRnCmZ7PVlMrymlPE5Gfx4QCvVtdUMuiWKrIRw0oflEWa2Emg4R6NLR2xsLJkjbsAw/i4Sh9+NeOh+hLNtKIrC9DkLMN/5GF1NmzAaP+eZ3e3sXjEdY+sxZCWI2ye3ZUcYboDui6oNGzb4Fy5c2BwTExNz7NixeJ1OV+f1ekPPbnph1qAozeYwozRQZ9QgCAKCAM3NHgIBmZBQCa/Lj1YvotGrCYvQogs3Uu1O4siRYkrM41l7qJM3dpbhkvXMmnI3w0bejEUlIkYlo4gasrOGEB8fz6lTp5C0enSxKUybMx9FUZAkifsXL0UdaqGmvgm7w4HT7abCchOZiz4kMjYDhzdY/vSOxu0A6pUrV5ozMjLC9Xq9prq62lVTUxOXmpQUItUdf8gn+NTRyZfToKwoGEMlQo0SLY29DBsTcxXt1CUMRdDoSR8xiC/L2pl05928ssnLwYCNLVvL8CoiQtCPSVfOgLSv0ZstfPLJJzzwwAP9OsZPuB2z2YzL5aK7u5uoqCjmzZvHG2+8gcViQRZEtMnDiX/kfYKbnxo76fhW086Sni61wWDQWK1Wv9Pp1CUlJaU7HA512eqFj0QZlcF+d18U+heUSiQlwYJaG4Ik1aMgI6nUREbEootIQhk1DdHVQ0RbLX4liD4jl8eWJLDpvfc5efYCDY1Nl5Xt/rL/8ZFH+rYYiqKwZs0aenp6AKisrCQtLY3Dhw8DYDKZuOOOOwAB0RhG4r3L1Unv/m8M0KX6xS9+0VZfX9/W1dXl8nq9wdDQ0IGDI413G3QG9Pr+pIBBqychZSSWkVNQjZrLwCm/xmKKJH7wOMyjZ6CZvAxN4ggaQ9KoCh+NJfPH6Lsv4vUFiLPFc+ToMZYvX86uXbs4dOgQI0aM6Nc9bdo0urq6EASBtrY2VKq+ZLp7925QFAoLC1EUheeee46oqKj+cSpDmLD2cMc5+IZrzZ07N85ms5l8Pp8SCAQ00Z7aGebk4UKoyYxZpybUHEXYwDHoMsehHZxPcYufQTffjXHgaFQRNtqtuTR09PDlwUMgSuQMH05YXBJelQadTkesLZ6SkhJSU1OxWCzYbDY6OjqYMmUK69ato7KyEo/bTU7WYO655x7mzr2PDRs2UFxczNSpU4mNjWXLli3MnDmTnJwc/H4/gUAAUdISFxf35Y4dOy6qt23bJvp8PlmW5V6/3094eHilMWlQ0JGUr96xfgNBn5oQKQRTs4zv9Am+qtrOr1auRBDVYE3nSGU7wbYabrzxRoYOG4bwzVwsKirC4/GQkJCAy+vH5XJRXV3NW2+9hTU6GrPJhMlkwmAwsHPnThYvXkxQUaEEZOwOB15vH1359NNPWbhwIQAaTd8MkSSJmpoae3t7+/vp6em5wAF1W1ubftGiRQ0A77zzTsSoUaMMsjmh3mRLHjDalkxCRAQIAucaGqjs6GDijBmkpqbicDior69n9Jgb0Ov1qFQqSktL2bVrF2azmby8PEaNHIlaVBEdZeGll1eh1+t59dVX0ev1dHR0sGTJEvbv38/ChQvJyckBQBRF9u7dC0BqaioZGRlER0djMBjQ6S7ToZiYGOOaNWveOH36dCuAatGiRb2XOgVB0LW0tOhPOELeVICSQICm5mZKKirYZbczfMECpsyY0ZehdDoGDx6M0WikoaGBtWvXUlRUxNw5c5g/bx7p6ekEZZl9Bw7idHlISUmhp6eH8PBw0tPTqaioQJZlysrKEEWxP5KlpaVs3bqVzMxMNm/ezO23344oikiSRE9PT38i0Ol04uTJk6cUFBQ44YrKvmLFCtXQoUO73W63Th0a+pkc8L/1wLJlfPjkk0Q4HAzx+YiL62Muvb29+Hw+nE4nHo8bv8/H3LlzMBiMCIJAZ2cn+/btQ6fTkZSUhNlsJj8/nzNnzlBdXU1SUhLTpk2joqKCuro6BgwYgEqlwuVyMXPmTEpLS/uypFqNXt9XyWVZxmw2o9VqaW5uJjw8nPj4+MnAm38PRKaPe9WsWLFCbm6ov6hSqZLmv/YaSxcswN7RwQM2G8gyRoOOEKMBo9HYn2Hq6+spLT3L+fPn0Wg0jBw+nJKPP2HP7gIWnT7JwoULyc/PJyEhAY/H802BFSgrK+PBBx+kvb2dJUuWUFpaysqVK9Hr9WRlZSGKIrfddhsOhwOLxYJOpyMmJoaWlhZKS0sbZ8+ebd2yZUsL3yUrV640l5aWLm9ubtp7+PCB7oSEeKWgoEC5Utxut1JZWalUV1crpaWlSlNTk9Lb26t88e4m5dTPHldOPfgL5dS8nykrZs1XsrOzlZ///OdKU1OT4na7lfr6emXSpEmKXq9XcnJylPj4eMVqtSrZ2dmKw+G4ys6zzz6rSJKkuN3uq9oPHjz4eP+y+E4kV8i5c9s3iaKyoKGhl/Lydpqbm4mOtlJTU87Bg8f53z++gNcu0/3STlCrUZmMBBqa0Fij8ba0UuuXmLZzE1nZ2ezfvx+TyYTf78fj8TB48GCOHTvGsmXLiI6O5sUXX0SlUvUfk7rdbvbt28eCBQtoamrqbwcoLy//W3p6+q3wPbe6W7dufTg01FKRnZ3BnDkPU1R0mrlz78dqTeTQoWK6PvmauPQYnN1t+C9eRPIHCA3I6LvtRCcm4m93MjEpi/b2dsxmM4FAoH9q6XQ6amtr2bhxI6tWrUKSpKucdTqdzJw5E4vFwoEDB/rbvV4vKpWqv6p+LyArVnzsKy7ufVsUNfh8bvLzJyAIBlyuvuHioRq89R0MuWkUiYlJpERGk5KaSnJsHPqAzMD4ZFw+7zf0oq8OSJLE+vXrqaqq4r333vsHm0ePHuXIkSM8+uijOBwOLly4wO9+97v+fq1Wi1qt7sfwvY+D3G5/RGjoUA4eLKSqqgqVSkVERAQaUY0mJBz501J8Lg8mkwm1y90/rtsVwGgM4XBLFZMmTbpK5/bt2wFYt24dJ0+eBPr4lizLvPXWW4wbN46PP/4Y6Mta48ePR5YvnwsbjUaV1WrVXxMQnU4XVKlEhgzJoaOjg/LycjQaDWNikpERCa1zoG3uRau5zM+a7L34gzo+rShGMuiZOHFif9+ZM2coL798aNjZ2Xe10NjYyHPPPceWLVvweDxX+eBwOGhubu4H093dfaalpcV5TUDi4+PH1tTUtISFhXHTTWMoLCzE6/VyR3I2Hd19NTU0NKT//RaHk/O1LkI0ZracP8r48eP7K/Pp06cZOnQowWCQ3/zmN8THx/fXi9WrV/P888+jKFcf8b755pt89dVXREdHU1dXhyzLmEymQUOGDNHANRyZhoSEhEyePHmKVqtVm0wBamtLKD52jgciMnF0e2h2dNDpctMcq6cRPxUnG8hMGcRfa87w+5IDrFq1ioyMDL744gtmz57N0qVL+eijj7j55puZOnUqZrMZWZaZP38+RqOR1NRUOjs7SUpKIj09nQ0bNhAbG0tKSgo6nY66ujqXIAgXNRpNcUFBQd33vh+56667Yru6uoJer7cyJibLcu+96rA5sxTa/1ZJ2M4AzlYVza09pM1LQ5RVaKvUuPx+Xjj8F8aOHUtOTg6yLLN9+3b27t2LJEn09vZiNptJTk6mra2N1157jZ6eHt577z3mzZvH008/jc1mIy8vD1EUyc/PB/rokUaj6V29evWEpKQk9TVFxGQypdrt9q8KCgoOZ2QMynjrrXejkjQ6lBA1Hq2AkGQi4oYkbBPS8fZ4UF9wsXjvR5R7unjjjTew2Wx8/fXXDB8+nPDw8GBXV1eDw+GoLS0tDf71r381rlq1yilJkpSbmyssW7YMQRDIy8vDaDSSnZ2NKIrIsozb7UaW5d76+vq/7N69u+iVV16pheu4DN28efOgsWPHfnTw4MERGzZswN3ehcfrpaapAZPBiFZUow2ALxgASygrVqwgMzOT5ORkNmzYwO233+632+0/HTdu3MZLOgsKCn5ZWFj40bBhw8alpaV90NjY+ITNZhsaHR09s7u7O1QURb/NZhMkSVK73W4OHTr0pwkTJky7Vt/75eGHHzbU1taeVxRFcTgcSiAQUDo7O5Xz588rZWVlSkNDg9LQ0KCcO3dOOXXqlFJdXa00NDQop06dUnw+n1JRUaGcPHnyt//Mxrp165679JyRkRG6Z8+elw4dOrRv27ZtE1pbW7tkWVZOnDix5rpBADz00EOjqqur7Zc4j8fjURobGxWv16s4nU7F7/f38yBZlpWurq6ruNHp06crjh8//vG12Jw+fbrm1VdfvQvgz3/+8/QLFy70bty48Zf/FhCAzz///JQsy4rb7Va8Xq/i9/sVt9utBAKBfof9fr/S2dmpeDye/rbCwsLPnnrqqdc3bdq09PXXXx9+vfa3bdu28V+/9T3kxIkTa2prax3BYLDfUbvd3h+FS9PuSnE6ncH333//TvqSi3D//ffPul77EyZMiPu29mu6QwQYNmyYMzo6Okan02X4/X5kWcbj8WAwGHA6nUBferxENfx+PwcOHNhTVlZWtnfv3hKA9vb2Srv9Wy7Lv4dUVVU5fhAgO3fuvJifn/+Qy+UKUxTlbCAQMDqdTpdWq9UEAgGVy+VClmXq6upaFEUJMZlM7Ny5c+OTTz7Zz/iuF8Q/k2sGAqhlWT4niuJJh8Pxjl6vnxUIBN7t7e319Pb2prjd7p66urrjLS0tF/1+v7uqqmpvVlaWae3atX/+oZ2/Uq77TzXjxo3T7du3z/PBBx88mJiYGKkoSk9VVdWYYDBYo9Foiuvr6y/a7Xaroiil06dPf23UqFHXvS7+v8ldd92VeN9992UAqp/+9Kcz/77/xRdfvOs/7cP/ATLDlgAd+zZTAAAAAElFTkSuQmCC'/>
                    //
                    //
                    //</BODY>
                    //</HTML>
                    //</foreignObject></svg>";



                    //var img = new IHTMLImage();
                    ////var url = "data:image/svg+xml;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(s.AsXElement().ToString()));
                    //var url = "data:image/svg+xml;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(xmlstring));
                    ////var url = "data:image/svg+xml;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(ss));
                    //img.src = url;

                    //img.InvokeOnComplete(
                    //    delegate
                    //    {
                    //        page.body.css.after.contentImage = img;
                    //        page.body.css.after.style.border = "1px solid red";

                    //    }
                    //);

                    page.body.css.after.contentImage = s;
                    //page.body.css.after.style.border = "1px solid red";

                }
            );
            #endregion


        }
        public MatrixTransformBExample()
        {
            var x = 400;
            var y = 200;
            var w = 200;
            var h = 200;

            var ro_matrix = new IHTMLDiv();

            ro_matrix.style.backgroundColor = "#8080ff";
            ro_matrix.style.SetLocation(x, y);
            ro_matrix.AttachToDocument();
            //ro_matrix.style.paddingLeft = w + "px";
            //ro_matrix.style.paddingTop = h + "px";
            var ro_matric_content = new IHTMLDiv();

            ro_matric_content.style.backgroundColor = "#0000ff";
            ro_matric_content.style.SetSize(w, h);
            ro_matric_content.AttachTo(ro_matrix);


            var r_matrix = new IHTMLDiv();

            r_matrix.style.backgroundColor = "#80ff80";
            r_matrix.style.SetLocation(x, y);
            r_matrix.AttachToDocument();

            //r_matrix.style.paddingLeft = w + "px";
            //r_matrix.style.paddingTop = h + "px";
            var r_matric_content = new IHTMLDiv();

            r_matric_content.style.backgroundColor = "#00ff00";
            r_matric_content.style.SetSize(w, h);
            r_matric_content.AttachTo(r_matrix);


            #region blue rotation
            var jo = new IHTMLDiv();

            jo.style.background = "blue";
            jo.style.SetLocation(x - w / 2 - 4, y - h / 2 - 1, 8, 2);

            jo.AttachToDocument();

            var joh = new IHTMLDiv();

            joh.style.background = "blue";
            joh.style.SetLocation(x - w / 2 - 1, y - h / 2 - 4, 2, 8);

            joh.AttachToDocument();

            jo.BlinkAt(400);
            joh.BlinkAt(400);
            #endregion

            #region black origin
            var zo = new IHTMLDiv();

            zo.style.background = "black";
            zo.style.SetLocation(x - 4, y - 1, 8, 2);

            zo.AttachToDocument();

            var zoh = new IHTMLDiv();

            zoh.style.background = "black";
            zoh.style.SetLocation(x - 1, y - 4, 2, 8);

            zoh.AttachToDocument();
            #endregion




            var ro = new IHTMLDiv();

            ro.style.background = "red";
            ro.style.SetLocation(x, y, w, h);
            ro.style.Opacity = 0.3;
            ro.AttachToDocument();



            var info = new IHTMLSpan { innerText = "MatrixTransform" };


            info.style.SetLocation(x, y + h, w, h);

            info.AttachToDocument();

            var at = new IHTMLDiv();

            at.style.background = "yellow";
            at.style.SetLocation(x - w / 2, y - h / 2, w * 2, h * 2);
            at.style.Opacity = 0.5;
            at.AttachToDocument();



            var r = new IHTMLDiv();

            r.style.background = "black";
            r.style.SetLocation(x, y, w, h);
            r.style.Opacity = 0.3;

            r.AttachToDocument();
            r.style.cursor = IStyle.CursorEnum.pointer;

            #region blue origin
            var o = new IHTMLDiv();

            o.style.background = "blue";
            o.style.SetLocation(x + w / 2 - 4, y + h / 2 - 1, 8, 2);

            o.AttachToDocument();

            var oh = new IHTMLDiv();

            oh.style.background = "blue";
            oh.style.SetLocation(x + w / 2 - 1, y + h / 2 - 4, 2, 8);

            oh.AttachToDocument();
            #endregion



            #region black rotation
            var jzo = new IHTMLDiv();

            jzo.style.background = "black";
            jzo.style.SetLocation(x - w / 2 - 4, y - h / 2 - 1, 8, 2);

            jzo.AttachToDocument();

            var jzoh = new IHTMLDiv();

            jzoh.style.background = "black";
            jzoh.style.SetLocation(x - w / 2 - 1, y - h / 2 - 4, 2, 8);

            jzoh.AttachToDocument();


            jzo.BlinkAt(400);
            jzoh.BlinkAt(400);
            #endregion


            var m = new MatrixModifiers();

            var InteractiveSetOrigin_x = 0;
            var InteractiveSetOrigin_y = 0;

            var InteractiveSetRotation_x = 0;
            var InteractiveSetRotation_y = 0;


            Action<int, int> InteractiveSetRotation = null;

            Action<int, int> SetPadding =
                (ox, oy) =>
                {
                    // -0 ... -w

                    ox += w / 2;
                    oy += h / 2;

                    info.innerText = "padding x: " + ox + " y:" + oy;

                    if (ox > 0)
                    {
                        ro_matrix.style.paddingLeft = ox * 2 + "px";
                        ro_matrix.style.paddingRight = 0 + "px";
                    }
                    else
                    {
                        ro_matrix.style.paddingLeft = 0 + "px";
                        ro_matrix.style.paddingRight = ox * -2 + "px";
                    }

                    if (oy > 0)
                    {
                        ro_matrix.style.paddingTop = oy * 2 + "px";
                        ro_matrix.style.paddingBottom = 0 + "px";
                    }
                    else
                    {
                        ro_matrix.style.paddingTop = 0 + "px";
                        ro_matrix.style.paddingBottom = oy * -2 + "px";
                    }



                    if (ox > 0)
                    {
                        r_matrix.style.paddingLeft = ox * 2 + "px";
                        r_matrix.style.paddingRight = 0 + "px";
                    }
                    else
                    {
                        r_matrix.style.paddingLeft = 0 + "px";
                        r_matrix.style.paddingRight = ox * -2 + "px";
                    }

                    if (oy > 0)
                    {
                        r_matrix.style.paddingTop = oy * 2 + "px";
                        r_matrix.style.paddingBottom = 0 + "px";
                    }
                    else
                    {
                        r_matrix.style.paddingTop = 0 + "px";
                        r_matrix.style.paddingBottom = oy * -2 + "px";
                    }
                };

            m.Visual1.CheckedChanged +=
                delegate
                {
                    r_matrix.Show(m.Visual1.Checked);
                };

            m.Visual2.CheckedChanged +=
                delegate
                {
                    ro_matrix.Show(m.Visual2.Checked);
                };

            m.Debug1.CheckedChanged +=
                delegate
                {
                    if (m.Debug1.Checked)
                    {
                        ro_matrix.style.backgroundColor = "#8080ff";
                        r_matrix.style.backgroundColor = "#80ff80";

                        return;
                    }

                    ro_matrix.style.backgroundColor = "";
                    r_matrix.style.backgroundColor = "";
                };

            Action<int, int> InteractiveSetOrigin =
                (ox, oy) =>
                {
                    var dx = InteractiveSetOrigin_x - ox;
                    var dy = InteractiveSetOrigin_y - oy;

                    InteractiveSetOrigin_x = ox;
                    InteractiveSetOrigin_y = oy;

                    SetPadding(ox, oy);

                    m.TranslateX.Text = "" + ox;
                    m.TranslateY.Text = "" + oy;

                    ro.style.SetLocation(x + ox, y + oy, w, h);
                    ro_matrix.style.SetLocation(x + ox, y + oy /*, w, h*/);
                    o.style.SetLocation(x - ox - 4, y - oy - 1, 8, 2);
                    oh.style.SetLocation(x - ox - 1, y - oy - 4, 2, 8);

                    InteractiveSetRotation(InteractiveSetRotation_x + dx, InteractiveSetRotation_y + dy);
                };

            InteractiveSetRotation =
                (ox, oy) =>
                {
                    InteractiveSetRotation_x = ox;
                    InteractiveSetRotation_y = oy;

                    var ax = x - w / 2 + ox;
                    var ay = y - h / 2 + oy;

                    var bx = x - InteractiveSetOrigin_x;
                    var by = y - InteractiveSetOrigin_y;

                    var dx = ax - bx;
                    var dy = ay - by;

                    var rotation = Extensions.GetRotation(dx, dy);
                    var rotation_degrees = rotation.RadiansToDegrees();

                    var costheta = Math.Cos(rotation);
                    var sintheta = Math.Sin(rotation);

                    var M11 = costheta;
                    var M12 = -sintheta;
                    var M21 = sintheta;
                    var M22 = costheta;

                    m.M11.Text = "" + M11;
                    m.M12.Text = "" + M12;
                    m.M21.Text = "" + M21;
                    m.M22.Text = "" + M22;

                    info.innerText = "rotation: " + rotation_degrees + "° x: " + InteractiveSetOrigin_x + " y:" + InteractiveSetOrigin_y;
                    //Native.Document.title = new { ax, bx, dx, rotation_degrees }.ToString();

                    joh.style.SetLocation(ax - 1, y - h / 2 + oy - 4, 2, 8);
                    jo.style.SetLocation(x - w / 2 + ox - 4, ay - 1, 8, 2);

                    jzoh.style.SetLocation(x + InteractiveSetOrigin_x - w / 2 + ox - 1, y + InteractiveSetOrigin_y - h / 2 + oy - 4, 2, 8);
                    jzo.style.SetLocation(x + InteractiveSetOrigin_x - w / 2 + ox - 4, y + InteractiveSetOrigin_y - h / 2 + oy - 1, 8, 2);

                    var mm = new[]
					{
						M11, M21,
						M12, M22,
						
						0, 0
						//0.838670551776886,0.5446390509605408,-0.5446390509605408,0.838670551776886,0,0
					};

                    var code = @"
			q.style.filter = ""progid:DXImageTransform.Microsoft.Matrix(M11='"" + m[0] + ""',M12='"" + m[2] + ""',M21='"" + m[1] + ""', M22='"" + m[3] + ""', sizingmethod='auto expand');"";
	
			q.style.MozTransform = ""matrix("" + m[0] + "","" + m[1] + "","" + m[2] + "","" + m[3] + "","" + m[4] + "","" + m[5] + "")"";
			
			q.style.WebkitTransform = ""matrix("" + m[0] + "","" + m[1] + "","" + m[2] + "","" + m[3] + "","" + m[4] + "","" + m[5] + "")"";
				";

                    new IFunction("q", "m", code).apply(null, r_matrix, mm);
                    new IFunction("q", "m", code).apply(null, ro_matrix, mm);


                    var r_matrix_adj_x = (r_matrix.clientWidth - r_matrix.offsetWidth) / 2;
                    var r_matrix_adj_y = (r_matrix.clientHeight - r_matrix.offsetHeight) / 2;

                    var ro_matrix_adj_x = (ro_matrix.clientWidth - ro_matrix.offsetWidth) / 2;
                    var ro_matrix_adj_y = (ro_matrix.clientHeight - ro_matrix.offsetHeight) / 2;



                    r_matrix.style.SetLocation(x + r_matrix_adj_x, y + r_matrix_adj_y/*, w, h*/);
                    ro_matrix.style.SetLocation(x + InteractiveSetOrigin_x + ro_matrix_adj_x, y + InteractiveSetOrigin_y + ro_matrix_adj_y/*, w, h*/);

                };



            #region bind InteractiveSetRotation
            at.onclick +=
                e =>
                {

                    InteractiveSetRotation(e.OffsetX, e.OffsetY);

                };

            at.onmousemove +=
                e =>
                {

                    InteractiveSetRotation(e.OffsetX, e.OffsetY);

                };

            at.onmouseover +=
                delegate
                {
                    info.innerText = "Click to set rotation";
                };

            InteractiveSetRotation(0, 0);
            #endregion

            #region bind InteractiveSetOrigin
            m.ButtonClear.Click +=
                delegate
                {
                    InteractiveSetOrigin(0, 0);
                };

            r.onclick +=
                e =>
                {
                    // 0 0 is top left

                    InteractiveSetOrigin(-e.OffsetX, -e.OffsetY);
                };

            r.onmouseover +=
                delegate
                {
                    if (m.Debug1.Checked)
                    {
                        info.innerText = "Click to set padding";
                        return;
                    }
                    info.innerText = "Click to set origin";
                };


            #endregion

            //InteractiveSetOrigin(0, 0);
            InteractiveSetOrigin(-w / 2, -h / 2);

            var f = new Form { Text = "MatrixModifier" };

            m.BackColor = System.Drawing.Color.White;

            f.Controls.Add(m);
            f.ClientSize = m.Size;

            f.GetHTMLTarget().AttachToDocument();
        }
        /// <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)
        {
            // ! to convert svg to image we would need to normalize source, which defeats shadowdom purpose

            // X:\jsc.svn\examples\javascript\svg\SVGCSSContent\SVGCSSContent\Application.cs

            var s = new ISVGSVGElement
            {

            };

            var f = new ISVGForeignObject().AttachTo(s);
            //requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">

            //f.setAttribute("requiredFeatures", "http://www.w3.org/TR/SVG11/feature#Extensibility");

            // http://starkravingfinkle.org/blog/2007/07/firefox-3-svg-foreignobject/
            // http://stackoverflow.com/questions/11194403/svg-foreignobject-not-showing-in-chrome
            var div = new IHTMLDiv
            {
            };

            new IHTMLContent { select = "div" }.AttachTo(div);

            //var divbody = new IHTMLDiv
            //{
            //    innerHTML = "I like <span style='color:white; text-shadow:0 2px 2px blue;'>cheese</span>"
            //}.AttachTo(div);
            // https://groups.google.com/forum/#!topic/svg-edit/60HICxGWFNE
            // http://www.w3.org/TR/SVG11/extend.html#ForeignObjectElement

            // http://css.dzone.com/articles/securing-pixel-data-svg-and
            // view-source:http://starkravingfinkle.org/blog/wp-content/uploads/2007/07/foreignobject-transform.svg
            // http://stackoverflow.com/questions/6849192/what-can-be-rendered-in-foreignobject-element-when-svg-is-embedded-in-html5
            //new StockToolboxImageForWebGLComponent().AttachTo(divbody);

            //new Anonymous_LogosSingle().AttachTo(divbody);

            // for detatched calculations!
            //div.style.fontFamily = IStyle.FontFamilyEnum.Verdana;
            //div.style.fontSize = "40px";
            div.style.display = IStyle.DisplayEnum.inline_block;

            // div.AttachToDocument();

            s.width = 400;
            s.height = 100;

            //s.width = div.clientWidth;
            //s.height = div.clientHeight;
            //s.height = div.clientHeight;

            div.AttachTo(f);


            //s.AttachToDocument();
            s.AttachTo(Native.body.shadow);

            // and then show any canvases
            //new IHTMLContent { select = "canvas" }.AttachTo(div);

            
            // https://developer.mozilla.org/en-US/docs/Web/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
            //var c = new CanvasRenderingContext2D(400, 100);

            //c.drawImage(
        }
        void InitializeCanvasSelection()
        {
            var u = this.Layers.User;

            var selection = new IHTMLDiv();

            selection.style.border = "1px solid #ffffff";
            //selection.style.overflow = IStyle.OverflowEnum.hidden;


            var selection_start = Point.Zero;
            var selection_end = Point.Zero;
            var selection_rect = new Rectangle();

            #region UpdateSelection
            System.Action UpdateSelection =
                delegate
                {
                    var size = selection_end - selection_start;

                    if (size.X < 0)
                    {
                        selection_rect.Left = selection_start.X + size.X;
                        selection_rect.Width = -size.X;
                    }
                    else
                    {
                        selection_rect.Left = selection_start.X;
                        selection_rect.Width = size.X;
                    }

                    if (size.Y < 0)
                    {
                        selection_rect.Top = selection_start.Y + size.Y;
                        selection_rect.Height = -size.Y;
                    }
                    else
                    {
                        selection_rect.Top = selection_start.Y;
                        selection_rect.Height = size.Y;
                    }


                    if (ShowSelectionRectangle)
                        if (IsSelectionMinimumSize(selection_rect))
                        {
                            selection.style.display = IStyle.DisplayEnum.none;
                        }
                        else
                        {
                            selection.style.display = IStyle.DisplayEnum.block;
                            selection.style.SetLocation(selection_rect);
                        }

                    if (SelectionPreview != null)
                        SelectionPreview(selection_rect);

                    if (SelectionPointsPreview != null)
                        SelectionPointsPreview(selection_start, selection_end);
                };
            #endregion

            Action ReleaseCapture = null;



            var aa = default(Point);
            var bb = default(Point);

            var disablemouse = false;

            #region ontouchmove
            u.ontouchstart +=
                e =>
                {
                    disablemouse = true;

                    // one finger to pan around
                    if (e.touches.length == 2)
                    {
                        //Console.WriteLine("ontouchstart");
                        e.preventDefault();
                        selection.style.border = "1px solid white";

                        _InSelectionMode = true;

                        if (ShowSelectionRectangle)
                            selection.AttachTo(this.Layers.CanvasInfo);

                        //this.Layers.CanvasInfo.appendChild(selection);

                        aa = new Point(
                            // selection_start
                              Math.Min(
                                  e.touches[0].screenX,
                                  e.touches[1].screenX
                              ),
                              Math.Min(
                                  e.touches[0].screenY,
                                  e.touches[1].screenY
                              )
                          );

                        bb = new Point(
                            // selection_start
                            Math.Max(
                                e.touches[0].screenX,
                                e.touches[1].screenX
                            ),
                            Math.Max(
                                e.touches[0].screenY,
                                e.touches[1].screenY
                            )
                        );
                    }
                };

            u.ontouchmove +=
                e =>
                {
                    if (e.touches.length == 2)
                        if (_InSelectionMode)
                        {
                            selection.style.border = "1px solid green";
                            //Console.WriteLine("ontouchmove");

                            e.preventDefault();
                            e.stopPropagation();

                            var a = new Point(
                                // selection_start
                                Math.Min(
                                    e.touches[0].screenX,
                                    Math.Min(e.touches[1].screenX, aa.X)
                                ),
                                Math.Min(
                                    e.touches[0].screenY,
                                    Math.Min(e.touches[1].screenY, aa.Y)
                                )
                            );

                            var b = new Point(
                                // selection_start
                                Math.Max(
                                    e.touches[0].screenX,
                                    Math.Max(e.touches[1].screenX, aa.X)
                                ),
                                Math.Max(
                                    e.touches[0].screenY,
                                    Math.Max(e.touches[1].screenY, bb.Y)
                                )
                            );


                            selection_start = a - this.CurrentCanvasPosition;
                            selection_end = b - this.CurrentCanvasPosition;


                            UpdateSelection();
                        }

                };

            u.ontouchend +=
                e =>
                {

                    if (_InSelectionMode)
                    {
                        _InSelectionMode = false;

                        selection.style.border = "1px solid yellow";
                        //Console.WriteLine("ontouchend");

                        Native.window.requestAnimationFrame +=
                            delegate
                            {
                                // !!! workaround for webview. 
                                selection.style.SetLocation(0, 0, 0, 0);
                                //selection.Orphanize();

                                Console.WriteLine("ontouchend done?");
                            };




                        e.preventDefault();
                        e.stopPropagation();
                    }

                };


            #endregion





            #region mouse
            u.onmousedown +=
                e =>
                {
                    if (disablemouse)
                        return;

                    if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                    {
                        _InSelectionMode = true;

                        if (ShowSelectionRectangle)
                            this.Layers.CanvasInfo.appendChild(selection);

                        selection_start = e.OffsetPosition - this.CurrentCanvasPosition;
                        selection_end = selection_start;

                        UpdateSelection();

                        Console.WriteLine("CaptureMouse");
                        e.preventDefault();
                        e.stopPropagation();
                        ReleaseCapture = u.CaptureMouse();
                    }
                };




            u.onmousemove +=
                delegate(IEvent e)
                {
                    if (disablemouse)
                        return;


                    if (_InSelectionMode)
                    {
                        selection_end = e.OffsetPosition - this.CurrentCanvasPosition;

                        e.preventDefault();
                        e.stopPropagation();
                        UpdateSelection();
                    }
                };

            u.onmouseup +=
                delegate(IEvent e)
                {
                    if (disablemouse)
                        return;


                    if (_InSelectionMode)
                    {
                        if (e.MouseButton == IEvent.MouseButtonEnum.Left)
                        {
                            _InSelectionMode = false;
                            e.preventDefault();
                            e.stopPropagation();

                            if (IsSelectionMinimumSize(selection_rect))
                            {
                                var p = new Point(selection_end.X, selection_end.Y);

                                if (SelectionClick != null)
                                    SelectionClick(p, e);
                            }
                            else
                            {
                                var r = new Rectangle
                                        {
                                            Left = selection_rect.Left,
                                            Top = selection_rect.Top,
                                            Width = selection_rect.Width,
                                            Height = selection_rect.Height,
                                        };

                                if (ApplySelection != null)
                                    ApplySelection(r, e);

                                if (ApplyPointsSelection != null)
                                    ApplyPointsSelection(selection_start, selection_end, e);
                            }

                            if (ShowSelectionRectangle)
                                this.Layers.CanvasInfo.removeChild(selection);

                            if (ReleaseCapture != null)
                            {
                                Console.WriteLine("ReleaseCapture");
                                ReleaseCapture();
                                ReleaseCapture = null;
                            }
                        }
                    }
                };
            #endregion


            //u.onmouseout +=
            //    delegate
            //    {
            //        if (_InSelectionMode)
            //        {
            //            _InSelectionMode = false;

            //            if (ShowSelectionRectangle)
            //                this.Layers.CanvasInfo.removeChild(selection);

            //            if (ReleaseCapture != null)
            //            {
            //                Console.WriteLine("ReleaseCapture");
            //                ReleaseCapture();
            //                ReleaseCapture = null;
            //            }
            //        }
            //    };
        }
Beispiel #24
0
        void Spawn(DudeAnimationInfo LoadedCharacter, Scene.Document LoadedScene)
        {
            var ViewSize = new Size { Width = 640, Height = 480 };

            var Container = new IHTMLDiv();
            Container.AttachToDocument();
            Container.style.SetSize(ViewSize.Width, ViewSize.Height + 22);
            Container.KeepInCenter();

            //Container.MakeCSSShaderCrumple();

            var Wallpaper = new IHTMLDiv().AttachTo(Container);
            Wallpaper.style.SetSize(ViewSize.Width, ViewSize.Height + 22);


            new power().ToBackground(Wallpaper.style);
            Wallpaper.style.position = IStyle.PositionEnum.absolute;
            Wallpaper.style.backgroundRepeat = "no-repeat";
            Wallpaper.style.backgroundPosition = "center center";





            var Margin = 48;
            var MarginSafe = 72;



            var CurrentFrame = LoadedScene.Frames.Randomize().First();
            //var CurrentFrame = LoadedScene.Frames.Single(f => f.Name == "C");

            var Room = new IHTMLDiv();



            Room.style.border = "1px solid #00ff00";
            Room.style.SetSize(ViewSize.Width, ViewSize.Height);
            Room.style.position = IStyle.PositionEnum.absolute;
            Room.style.overflow = IStyle.OverflowEnum.hidden;

            Room.AttachTo(Container);
            Room.style.SetLocation(0, 22);

            //Room.AttachToDocument();
            //Room.KeepInCenter();




            var tween = Room.ToOpacityTween();

            Action HideRoom = () => tween.Value = 1;
            Action ShowRoom = () => tween.Value = 0;

            HideRoom();

            //var GroundOverlay2 = new IHTMLDiv();

            //GroundOverlay2.style.backgroundColor = Color.Blue;
            ////GroundOverlay.style.Opacity = 0;

            //GroundOverlay2.style.position = IStyle.PositionEnum.absolute;
            //GroundOverlay2.style.SetLocation(0, 0, ViewSize.Width, ViewSize.Height);
            //GroundOverlay2.AttachTo(Room);

            var LostInTime_Images = new ImpAdventures.HTML.Pages.LostInTimeImages().Images;

            var BackgroundImage = new IHTMLImage();

            LostInTime_Images.FirstOrDefault(
                                   k => k.src.SkipUntilLastIfAny("/") == CurrentFrame.Image.Source.SkipUntilLastIfAny("/")
                               ).With(
                                   ImageSource =>
                                   {
                                       Console.WriteLine(ImageSource.src);
                                       BackgroundImage.src = ImageSource.src;
                                   }
                               );

            BackgroundImage.style.SetLocation(0, 0, ViewSize.Width, ViewSize.Height);
            BackgroundImage.alt = "BackgroundImage";
            BackgroundImage.AttachTo(Room);

            //GroundOverlay2.style.backgroundImage = "url(" + CurrentFrame.Image.Source + ")";
            //BackgroundImage.InvokeOnComplete(
            //    delegate
            //    {
            //        //BackgroundImage.style.backgroundColor = Color.Red;
            //        //BackgroundImage.style.SetLocation(0,0, ViewSize.Width, ViewSize.Height);
            //        BackgroundImage.AttachTo(GroundOverlay2);
            //    }
            //);


            var GroundOverlay = new IHTMLDiv();

            GroundOverlay.style.backgroundColor = Color.Blue;
            GroundOverlay.style.Opacity = 0;
            GroundOverlay.style.SetLocation(0, 0, ViewSize.Width, ViewSize.Height);
            GroundOverlay.AttachTo(Room);

            var Ground = new IHTMLDiv();

            Ground.style.SetLocation(0, 0, ViewSize.Width, ViewSize.Height);
            Ground.AttachTo(Room);




            var AnimateRoomChange = default(Action<Action>);

            #region TryToChangeRooms
            Func<TryToChangeRoomsArgs, bool> TryToChangeRooms =
                e =>
                {
                    if (e == null)
                        return false;

                    if (e.NextRoomSelector == null) throw new ArgumentNullException("NextRoomSelector");

                    var next = LoadedScene.Frames.SingleOrDefault(e.NextRoomSelector);

                    var r = next != null;

                    if (r)
                    {
                        AnimateRoomChange(
                            delegate
                            {
                                CurrentFrame = next;

                                Console.WriteLine("AnimateRoomChange");

                                LostInTime_Images.FirstOrDefault(
                                    k => k.src.SkipUntilLastIfAny("/") == CurrentFrame.Image.Source.SkipUntilLastIfAny("/")
                                ).With(
                                    ImageSource =>
                                    {
                                        Console.WriteLine(ImageSource.src);
                                        BackgroundImage.src = ImageSource.src;
                                    }
                                );

                                //GroundOverlay2.style.backgroundImage = "url(" + CurrentFrame.Image.Source + ")";
                                //BackgroundImage.src = CurrentFrame.Image.Source;

                                e.ReadyToTeleport();
                            }
                        );
                    }


                    return r;
                };
            #endregion


            var dude = CreateDude(LoadedCharacter);

            dude.Control.AttachTo(Ground);

            #region Doors
            var Doors = new[]
                {
                    new TryToChangeRoomsArgs
                            {
                                Condition = () => dude.CurrentLocation.X > ViewSize.Width - Margin,
                                NextRoomSelector = f => f.Name == CurrentFrame.Right,
                                ReadyToTeleport = delegate
                                {

                                    dude.TeleportTo(-MarginSafe, dude.CurrentLocation.Y);
                                    dude.LookAt(new Point(MarginSafe, (int)dude.CurrentLocation.Y));
                                }
                            },
                    new TryToChangeRoomsArgs
                            {
                                Condition = () => dude.CurrentLocation.X < Margin,
                                NextRoomSelector = f => f.Name == CurrentFrame.Left,
                                ReadyToTeleport = delegate
                                {

                                    dude.TeleportTo(ViewSize.Width + MarginSafe, dude.CurrentLocation.Y);
                                    dude.LookAt(new Point(ViewSize.Width - MarginSafe, (int)dude.CurrentLocation.Y));
                                }
                            },
                    new TryToChangeRoomsArgs
                            {
                                Condition = () => dude.CurrentLocation.Y < Margin,
                                NextRoomSelector = f => f.Name == CurrentFrame.Top,
                                ReadyToTeleport = delegate
                                {

                                     dude.TeleportTo(dude.CurrentLocation.X, ViewSize.Height + MarginSafe);
                                    dude.LookAt(new Point((int)dude.CurrentLocation.X, ViewSize.Height - MarginSafe));

                                }
                            },
                    new TryToChangeRoomsArgs
                            {
                                Condition = () => dude.CurrentLocation.Y > ViewSize.Height - Margin,
                                NextRoomSelector = f => f.Name == CurrentFrame.Bottom,
                                ReadyToTeleport = delegate
                                {

                                  dude.TeleportTo(dude.CurrentLocation.X, -Margin);
                                dude.LookAt(new Point((int)dude.CurrentLocation.X, MarginSafe));

                                }
                            }
                };
            #endregion

            Console.WriteLine(new { Doors = Doors.Length });

            Doors.WithEachIndex(
                (x, index) =>
                {
                    Console.WriteLine(new { index, x });
                    Console.WriteLine(new { index, x.Condition });
                }
            );


            var ChangeRoom = new ChangeRoom { autobuffer = true };
            var Talk = new Talk { autobuffer = true };
            var Argh_RChannel = new Argh_RChannel { autobuffer = true };
            var Argh_LChannel = new Argh_LChannel { autobuffer = true };
            var Argh_Disabled = false;
            var Argh_VolumeMultiplier = 1.0;

            #region Argh_Stereo
            Action<double, double> Argh_Stereo =
                (volume, balance) =>
                {
                    if (Argh_Disabled)
                        return;

                    Argh_RChannel.AttachToDocument();
                    Argh_LChannel.AttachToDocument();

                    Argh_RChannel.volume = Argh_VolumeMultiplier * volume * balance;
                    Argh_LChannel.volume = Argh_VolumeMultiplier * volume * (1 - balance);

                    Argh_RChannel.play();
                    Argh_LChannel.play();

                    Argh_RChannel = new Argh_RChannel { autobuffer = true };
                    Argh_LChannel = new Argh_LChannel { autobuffer = true };

                    Argh_Disabled = true;
                    Argh_VolumeMultiplier /= 2;

                    new Timer(t => Argh_Disabled = false).StartTimeout(800);
                    new Timer(t => Argh_VolumeMultiplier = 1).StartTimeout(5000);
                };
            #endregion

            #region PrintText
            Action<string, Action> PrintText =
                (text, done) =>
                {
                    Talk.AttachToDocument();
                    Talk.load();
                    Talk.volume = Math.Min(1, dude.Zoom.DynamicZoom / 4);
                    Talk.play();
                    Talk = new Talk { autobuffer = true };

                    text.Length.Range().AsyncForEach(
                        i =>
                        {
                            Wallpaper.innerText = text.Left(i + 1);

                            var c = text[i];

                            if (LoadedScene.SlowText.Contains("" + c))
                                return 100.Random();

                            return 50.Random();
                        }, done
                    );
                };
            #endregion

            Action<string, Action> PrintRandomText =
                (text, done) => PrintText(text.Split(LoadedScene.TextDelimiter).Randomize().First(), done);




            dude.DoneWalking +=
                delegate
                {
                    // compiler bug: cannot invoke Action<func, action> delegate ?

                    System.Console.WriteLine("done walking in " + CurrentFrame.Name + " at " + dude.CurrentLocation);

                    var xFirstOrDefault = Doors.FirstOrDefault(d => d.Condition());

                    System.Console.WriteLine("done walking in " + new { xFirstOrDefault });

                    // Doors null?
                    if (TryToChangeRooms(xFirstOrDefault))
                        return;


                    if (CurrentFrame.Items != null)
                    {
                        var item = CurrentFrame.Items.Where(
                            i => new Point(i.X.ToInt32(), i.Y.ToInt32()).GetRange(dude.CurrentLocation) < i.R.ToInt32()
                            ).FirstOrDefault();

                        if (item != null)
                        {


                            dude.IsSelected = false;
                            dude.LookDown();

                            PrintRandomText(item.Text,
                                delegate
                                {

                                    dude.WalkingOnce +=
                                        delegate
                                        {
                                            Wallpaper.innerText = "";
                                        };

                                    dude.IsSelected = true;
                                }
                            );
                        }
                    }

                };

            #region AnimateRoomChange
            AnimateRoomChange =
                ReadyToTeleport =>
                {
                    var Step1 = default(System.Action);
                    var Step2 = default(System.Action);
                    var Step3 = default(Action);

                    Step1 =
                        delegate
                        {
                            tween.Done -= Step1;

                            ReadyToTeleport();

                            tween.Done += Step2;

                            ShowRoom();
                        };

                    Step2 =
                        delegate
                        {
                            tween.Done -= Step2;

                            dude.DoneWalking += Step3;

                            dude.IsWalking = true;

                        };

                    Step3 =
                        delegate
                        {
                            dude.DoneWalking -= Step3;

                            dude.IsSelected = true;
                        };

                    dude.IsSelected = false;

                    tween.Done += Step1;
                    // go left
                    HideRoom();

                    // http://stackoverflow.com/questions/3009888/autoplay-audio-files-on-an-ipad-with-html5
                    ChangeRoom.AttachToDocument();
                    ChangeRoom.load();
                    ChangeRoom.volume = 0.2;
                    ChangeRoom.play();
                    ChangeRoom = new ChangeRoom();
                };
            #endregion

            var pointer_x = 0;
            var pointer_y = 0;

            #region onmousemove
            Container.onmousemove +=
                ev =>
                {
                    if (Native.Document.pointerLockElement == Container)
                    {
                        if (dude.IsSelected)
                        {
                            var volume = Math.Min(1, dude.Zoom.DynamicZoom / 4);
                            var balance = dude.CurrentLocation.X / ViewSize.Width;

                            pointer_x += ev.movementX;
                            pointer_y += ev.movementY;

                            pointer_x = Math.Min(ViewSize.Width - 0, Math.Max(0, pointer_x));
                            pointer_y = Math.Min(ViewSize.Height - 0, Math.Max(0, pointer_y));

                            var OffsetPosition = new Point(pointer_x, pointer_y

                            );

                            Console.WriteLine(OffsetPosition);

                            Argh_Stereo(volume, balance);
                            dude.WalkTo(OffsetPosition);
                        }
                    }
                };
            #endregion

            #region ontouchstart
            Container.ontouchstart +=
                ev =>
                {
                    ev.preventDefault();

                    System.Console.WriteLine(ev.CursorPosition);

                    if (dude.IsSelected)
                    {
                        var volume = Math.Min(1, dude.Zoom.DynamicZoom / 4);
                        var balance = dude.CurrentLocation.X / ViewSize.Width;

                        var ev_OffsetPosition = new Point(
                            ev.touches[0].clientX - Container.Bounds.Left,
                            ev.touches[0].clientY - Container.Bounds.Top
                            );

                        Argh_Stereo(volume, balance);
                        dude.WalkTo(ev_OffsetPosition);
                    }
                };
            #endregion

            #region onclick
            Container.onclick +=
                ev =>
                {
                    ev.preventDefault();

                    if (ev.MouseButton == IEvent.MouseButtonEnum.Middle)
                    {
                        if (Native.Document.pointerLockElement == Container)
                        {
                            Native.Document.exitPointerLock();
                            return;
                        }

                        pointer_x = (int)dude.CurrentLocation.X;
                        pointer_y = (int)dude.CurrentLocation.Y;

                        //Container.requestFullscreen();
                        Container.requestPointerLock();
                        return;
                    }

                    if (ev.Element != Ground)
                        return;

                    System.Console.WriteLine(ev.CursorPosition);

                    if (dude.IsSelected)
                    {
                        var volume = Math.Min(1, dude.Zoom.DynamicZoom / 4);
                        var balance = dude.CurrentLocation.X / ViewSize.Width;

                        Argh_Stereo(volume, balance);
                        dude.WalkTo(ev.OffsetPosition);
                    }
                };
            #endregion



            //GroundOverlay.onclick +=
            //    ev =>
            //    {
            //        if (ev.Element != GroundOverlay)
            //            return;

            //        System.Console.WriteLine(ev.CursorPosition);

            //        if (dude.IsSelected)
            //        {
            //            new Argh().play();

            //            dude.WalkTo(ev.OffsetPosition);
            //        }
            //    };


            dude.TeleportTo(ViewSize.Width / 2, (ViewSize.Height - MarginSafe) / 2);
            dude.LookDown();

            ShowRoom();

            dude.DoneWalkingOnce +=
                delegate
                {
                    PrintRandomText(
                        LoadedScene.IntroText,
                        delegate
                        {

                            dude.WalkingOnce +=
                              delegate
                              {
                                  Wallpaper.innerText = "";
                              };

                            dude.IsSelected = true;
                        }
                    );
                };

            dude.WalkToArc(MarginSafe, dude.Direction);

        }
Beispiel #25
0
        private static IHTMLDiv SpawnDiv(Dictionary<string, IHTMLImage> Images, bool b)
        {
            var div1 = new IHTMLDiv();
            var div2 = new IHTMLDiv();


            var img1 = (IHTMLImage)Images["room 001, obj 005 (296,32)"].cloneNode(false);
            var img2 = (IHTMLImage)Images["room 002, obj 002 (0,24)"].cloneNode(false);
            var img3 = (IHTMLImage)Images["room 002, obj 002 (0,24)"].cloneNode(false);

            div2.AttachTo(div1);
            div2.style.position = IStyle.PositionEnum.relative;
            div2.style.SetSize(100, 100);
            div2.style.border = "1px solid red";

            if (b)
                div2.onfocus += ev => div2.blur();

            img1.style.SetLocation(4, 4);
            img1.AttachTo(div2);

            img2.style.SetLocation(33, 4);
            img2.AttachTo(div2);
            img2.onfocus += ev => img2.blur();

            img3.style.SetLocation(66, 4);
            img3.AttachTo(div2);
            img3.onfocus += ev => ev.preventDefault();

            return div1;
        }
        public HorizontalSplitBase(Arguments args)
        {
            this.Split = args.Split;
            this.SplitArea = args.SplitArea;

            var hs = args.Split;
            var hsArea = args.SplitArea;

            var hsa = args.SplitImage;

            this.SplitImageContainer = new IHTMLDiv();
            SplitImageContainer.AttachTo(hs.Splitter);
            SplitImageContainer.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            SplitImageContainer.style.left = "1px";
            SplitImageContainer.style.top = "50%";
            SplitImageContainer.style.marginTop = (-args.SplitImageHeight / 2) + "px";

            hsa.AttachTo(SplitImageContainer);


            hsArea.Abort.style.Opacity = 0.05;


            var dragmode = false;
            Action ReleaseCapture = delegate { };

            hsArea.Target.onmousedown +=
                ee =>
                {
                    ReleaseCapture = hsArea.Target.CaptureMouse();

                    hsArea.Target.style.backgroundColor = SelectionColor;
                    dragmode = true;

                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151103
                    ee.preventDefault();
                    hsArea.Abort.style.Opacity = SelectionBackgroundOpacity;
                };

            hsArea.PageContainer.onmousemove +=
                ee =>
                {
                    var OffsetX = ee.GetOffsetX(hsArea.PageContainer);


                    if (!dragmode)
                        return;

                    var p = System.Convert.ToInt32(OffsetX * 100 / hsArea.PageContainer.offsetWidth);

                    if (p < Convert.ToInt32(Minimum * 100))
                        p = Convert.ToInt32(Minimum * 100);
                    if (p > Convert.ToInt32(Maximum * 100))
                        p = Convert.ToInt32(Maximum * 100);

                    hsArea.Target.style.left = p + "%";
                };

            InternalSetValue =
                p =>
                {
                    if (p < Convert.ToInt32(Minimum * 100))
                        p = Convert.ToInt32(Minimum * 100);
                    if (p > Convert.ToInt32(Maximum * 100))
                        p = Convert.ToInt32(Maximum * 100);

                    hsArea.Target.style.left = p + "%";
                    hs.Right.style.left = p + "%";
                    hs.Right.style.width = (100 - p) + "%";
                    hs.Left.style.width = p + "%";
                };

            hsArea.PageContainer.onmouseup +=
                ee =>
                {
                    if (!dragmode)
                        return;

                    ReleaseCapture();

                    var OffsetX = ee.GetOffsetX(hsArea.PageContainer);

                    dragmode = false;
                    var p = System.Convert.ToInt32(OffsetX * 100 / hsArea.PageContainer.offsetWidth);

                    Value = p * 0.01;

                    hsArea.Abort.style.Opacity = 0;
                    hsArea.Target.style.backgroundColor = ScriptCoreLib.JavaScript.Runtime.JSColor.None;

                };

            hsArea.Abort.onmousemove +=
                ee =>
                {
                    if (dragmode)
                    {
                        return;
                    }

                    hsArea.Target.style.backgroundColor = ScriptCoreLib.JavaScript.Runtime.JSColor.None;
                    hsArea.PageContainer.Orphanize();
                };

            hs.Splitter.onmouseover +=
                delegate
                {
                    hsArea.Abort.style.Opacity = 0.05;

                    hsArea.PageContainer.AttachTo(hs.ContentContainer);
                };
        }