public static TweenDataDouble ToOpacityTween(this IHTMLElement e)
        {
            var t = new TweenDataDouble();

            t.ValueChanged +=
                delegate
            {
                e.style.Opacity = 1 - t.Value;
            };

            return(t);
        }
        //public const string Alias = "Class1";
        //public const string DefaultData = "Class1Data";


        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public SimpleRollover()
        {
            // wallpapers at http://labnol.blogspot.com/2006/11/download-windows-vista-wallpapers.html

            // * broken at the moment
            #region AnimateCharacterColors
            System.Func<string, INode> AnimateCharacterColors =
                (text) =>
                {
                    var s = new IHTMLSpan();

                    var l = new global::System.Collections.Generic.List<IHTMLSpan>();

                    foreach (char c in text)
                    {
                        var y = new string(c, 1);
                        var x = new IHTMLSpan(y);

                        if (y == " ")
                        {
                            s.appendChild(" ");
                        }
                        else
                        {
                            l.Add(x);


                            s.appendChild(x);
                        }


                    }



                    new Timer(
                        t =>
                        {
                            var len = l.Count + 40;

                            if (t.Counter % len < l.Count)
                            {
                                if (t.Counter % (len * 2) < l.Count)
                                {
                                    l[t.Counter % len].style.visibility = IStyle.VisibilityEnum.hidden;
                                }
                                else
                                {
                                    l[t.Counter % len].style.visibility = IStyle.VisibilityEnum.visible;
                                }
                            }



                        }, 6000, 200);


                    return s;
                };
            #endregion
            // */

            var u = new IHTMLDiv();

            //u.style.backgroundColor = Color.Green;
            u.style.position = IStyle.PositionEnum.absolute;
            u.style.left = "0";
            u.style.top = "0";
            u.style.height = "100%";
            u.style.width = "100%";
            u.style.overflow = IStyle.OverflowEnum.auto;

            var styles = new XStyles
            {
                dark = new IStyleSheet(),
                light = new IStyleSheet(),
                switchbutton = new IHTMLAnchor("", "day/night"),
                counter = 0
            };



            styles.switchbutton.onclick +=
                ev =>
                {
                    ev.PreventDefault();

                    styles.counter++;


                    if (styles.counter % 2 == 1)
                    {
                        styles.dark.disabled = false;
                        styles.light.disabled = true;
                    }
                    else
                    {
                        styles.dark.disabled = true;
                        styles.light.disabled = false;
                    }
                };


            var ad = new IHTMLDiv(
                            new IHTMLSpan(
                                 AnimateCharacterColors(
                                "this application was written in c# and then translated to javascript by jsc to run in your browser"
                                 )
                            ),
                            new IHTMLAnchor("http://zproxy.wordpress.com", "visit blog"),
                            new IHTMLAnchor("http://jsc.sf.net", "get more examples"),
                            styles.switchbutton
                         )
                         {
                             className = "ad1"
                         };

            u.appendChild(ad);

            var sheet = new IStyleSheet();

            sheet.AddRule(".ad1",
                r =>
                {
                    r.style.marginTop = "1em";
                    r.style.color = Color.White;
                    r.style.fontFamily = IStyle.FontFamilyEnum.Verdana;
                }
            );


            sheet.AddRule(".ad1 > *",
                r =>
                {
                    r.style.padding = "1em";

                    r.style.marginTop = "1em";
                }
            );

            sheet.AddRule(".ad1 > span",
                r =>
                {
                    r.style.Float = IStyle.FloatEnum.right;
                }
            );

            sheet.AddRule(".ad1 > a",
                r =>
                {
                    r.style.Float = IStyle.FloatEnum.left;
                    r.style.color = Color.White;

                    r.style.textDecoration = "none";
                }
            );

            sheet.AddRule(".ad1 a:hover",
                r =>
                {
                    r.style.color = Color.Yellow;
                }
            );



            sheet.AddRule("html",
                r =>
                {

                    r.style.overflow = IStyle.OverflowEnum.hidden;
                }
            );

            sheet.AddRule("body",
                r =>
                {
                    r.style.overflow = IStyle.OverflowEnum.hidden;

                    r.style.padding = "0";
                    r.style.margin = "0";

                    //r.style.backgroundImage = "url(assets/vista.jpg)";

                }
            );


            styles.dark.AddRule("body").style.backgroundColor = JSColor.Black;
            styles.dark.AddRule("body").style.backgroundPosition = "center top";

            styles.light.AddRule("body").style.backgroundColor = JSColor.Black;
            styles.light.AddRule("body").style.backgroundPosition = "center top";


            new global::SimpleRollover.HTML.Images.FromAssets.vistax().ToBackground(
                styles.dark.AddRule("body").style, false
            );

            new global::SimpleRollover.HTML.Images.FromAssets.vista().ToBackground(
                styles.dark.AddRule(".effect1").style
            );

            styles.dark.AddRule(".moon1").style.backgroundColor = Color.Yellow;

            new global::SimpleRollover.HTML.Images.FromAssets.vista().ToBackground(
                styles.light.AddRule("body").style, false
            );

            new global::SimpleRollover.HTML.Images.FromAssets.vistax().ToBackground(
                 styles.light.AddRule(".effect1").style
            );
            styles.light.AddRule(".moon1").style.backgroundColor = Color.Red;


            sheet.AddRule(".special1",
                r =>
                {
                    r.style.background = "none";
                    r.style.border = "0";
                    r.style.width = "100%";
                    r.style.marginTop = "4em";


                }
            );

            sheet.AddRule(".content1",
                r =>
                {
                    r.style.backgroundColor = Color.White;

                    r.style.padding = "1em";
                    r.style.marginLeft = "4em";
                    r.style.marginRight = "4em";
                    r.style.Opacity = 0.5;
                    r.style.border = "1px solid gray";
                }
            );

            sheet.AddRule(".special1 img", "border: 0", 0);
            sheet.AddRule(".special1:hover", "background: url(" + new global::SimpleRollover.HTML.Images.FromAssets.Untitled_3().src + ") repeat-x", 1);

            sheet.AddRule(".special1 .hot").style.display = IStyle.DisplayEnum.none;
            sheet.AddRule(".special1:hover .hot").style.display = IStyle.DisplayEnum.inline;

            sheet.AddRule(".special1 .cold", "display: inline;", 1);
            sheet.AddRule(".special1:hover .cold", "display: none;", 1);


            var states = new XState[] { }.AsEnumerable();

            //    new XState { 
            //        Show = default(System.Action), 
            //        Hide = default(System.Action), 
            //        Selected = false } 
            //}.Where(p => false);


            Action<IHTMLImage, IHTMLImage, string> Spawn =
                async (icold, ihot, i2) =>
                {
                    var cold = await icold;
                    var hot = await ihot;

                    //((IHTMLImage)i[0]).InvokeOnComplete(cold =>
                    //((IHTMLImage)i[1]).InvokeOnComplete(hot =>
                    //     {
                    cold.className = "cold";
                    hot.className = "hot";


                    var btn = new IHTMLButton()
                        {
                            className = "special1"
                        };

                    btn.appendChild(cold, hot);

                    var content = new IHTMLElement(IHTMLElement.HTMLElementEnum.pre);

                    content.innerHTML = "...";
                    content.className = "content1";

                    var tween = new TweenDataDouble();
                    var tween_max = 16;

                    tween.ValueChanged +=
                        delegate
                        {
                            content.style.Opacity = tween.Value / tween_max;
                            content.style.height = tween.Value + "em";

                            content.style.overflow = IStyle.OverflowEnum.hidden;

                        };

                    tween.Done += delegate
                    {
                        if (tween.Value > 0)
                            content.style.overflow = IStyle.OverflowEnum.auto;
                    };

                    tween.Value = 0;

                    var state = new XState
                       {
                           Show = (System.Action)(() =>
                                               {
                                                   tween.Value = tween_max;
                                               }
                           ),
                           Hide = (System.Action)(() => tween.Value = 0),
                           Selected = false
                       };

                    //try
                    //{
                    //    new IXMLHttpRequest(HTTPMethodEnum.GET, i[2],
                    //       request => content.innerHTML = request.responseText
                    //    );
                    //}
                    //catch
                    //{
                    content.innerText = i2;
                    //}

                    states = states.Concat(new[] { state });

                    btn.onclick +=
                        delegate
                        {
                            foreach (var v in states)
                            {
                                if (v == state)
                                {

                                    v.Selected = !v.Selected;

                                    if (v.Selected)
                                    {
                                        v.Show();
                                    }
                                    else
                                    {
                                        v.Hide();
                                    }

                                }
                                else
                                {
                                    v.Selected = false;
                                    v.Hide();
                                }
                            }
                        };

                    u.appendChild(btn, content);




                };


            SpawnCursor();


            u.AttachToDocument();

            Spawn(
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_1_03(),
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_2_03(),
                "This application was written in C#."
            );

            Spawn(
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_1_07(),
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_2_07(),

                 "This application was cross compiled into JavaScript."
            );


        }
        private static void Test1()
        {
            var container = "div".AttachToDocument();

            container.style.border = "1px solid red";
            container.style.width = "400px";
            container.style.height = "300px";

            var svg = new ISVGSVGElement();
            var layer = new ISVGGElement();
            var text = new ISVGTextElement();
            var rect = new ISVGRectElement();

            rect.setAttribute("x", 70);
            rect.setAttribute("y", 20);
            rect.setAttribute("rx", 0);
            rect.setAttribute("ry", 0);
            rect.setAttribute("width", 160);
            rect.setAttribute("height", 160);
            rect.setAttribute("fill", "blue");

            text.setAttribute("x", "92");
            text.setAttribute("y", "32");
            text.setAttribute("fill", "red");
            //text.style.cursor = IStyle.CursorEnum.move;

            var img = new ISVGImageElement();


            img.href = new SimpleSVGexample.HTML.Images.FromAssets.TILE1436().src;

            img.setAttribute("x", 0);
            img.setAttribute("y", 0);
            img.setAttribute("width", 200);
            img.setAttribute("height", 200);
            // http://www.svgbasics.com/rotate.html
            img.setAttribute("transform", "rotate(-45 10 10)");

            var r = 0;


            (1000 / 20).AtInterval(
                delegate
                {
                    r++;

                    img.setAttribute("transform", "rotate(" + r + " 100 100)");

                }
            );

            var rectlayer = new ISVGGElement();

            rectlayer.appendChild(rect, text);
            //rectlayer.setAttribute("transform", "scale(0.5) translate(0, 0) rotate(45) skewX(20) skewY(5)");

            var tween = new TweenDataDouble();

            tween.Value = 1;
            tween.ValueChanged +=
                delegate
                {
                    rectlayer.setAttribute("opacity", tween.Value);

                };

            rectlayer.onmouseover +=
                delegate
                {
                    tween.Value = 0.5;

                };

            rectlayer.onmouseout +=
                delegate
                {
                    tween.Value = 1;

                };


            text.textContent = "hello world";


            layer.appendChild(rectlayer, img);
            svg.appendChild(layer);

            container.appendChild(svg);
        }
        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public LightsOut2(IHTMLElement DataElement)
        {

            // based on http://www.cjcraft.com/Blog/PermaLink,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx

            // what happens in beta2 when the anonymous types are immutable? :)


            var usersettings = new  { x = 5, y = 5, tile = new  { w = 64, h = 64, cold = 0.8 } };

    
            var a = new Array2D<IHTMLDiv>(usersettings.x, usersettings.y);
            var m = a.ToBooleanArray();



            var r = new System.Random();

            m.ForEach(
                (x, y) =>
                {
                    m[x, y] = r.NextDouble() > 0.5;
                }
            );


            var canvas = new IHTMLDiv();

            canvas.className = "canvas";

            var canvas_size = new __Type1 { x = ((a.XLength + 1) * usersettings.tile.w), y = ((a.YLength + 1) * usersettings.tile.h) };

            canvas.style.position = IStyle.PositionEnum.relative;
            canvas.style.border = "2px solid black";
            canvas.style.width = canvas_size.x + "px";
            canvas.style.height = canvas_size.y + "px";

            var canvas_bg = new IHTMLDiv();
            //var canvas_bg_tween = new TweenDataDouble();

            //canvas_bg_tween.Value = 1;
            //canvas_bg_tween.ValueChanged += delegate { canvas_bg.style.Opacity = canvas_bg_tween.Value; };

            new HTML.Images.FromAssets.background().ToBackground(canvas_bg.style);
            //canvas_bg.style.backgroundImage = Assets.Default.Background.StyleSheetURL;
            canvas_bg.style.SetLocation(0, 0, canvas_size.x * 2, canvas_size.y);

            canvas.appendChild(canvas_bg);


            IStyleSheet.Default.AddRule(".info").style
                .Aggregate(s =>
                               {
                                   s.backgroundColor = Color.Black;
                                   s.color = Color.White;
                                   s.padding = "2em";
                                   s.fontFamily = IStyle.FontFamilyEnum.Tahoma;
                                   s.Float = IStyle.FloatEnum.right;
                               })
                ;

            IStyleSheet.Default.AddRule(".canvas").style
                .Aggregate(s => s.overflow = IStyle.OverflowEnum.hidden)
                .Aggregate(s => s.backgroundColor = Color.Black)
                ;

            IStyleSheet.Default.AddRule(".on").style
                .Aggregate(s =>
                    
                        new HTML.Images.FromAssets.vistaLogoOn().ToBackground(s)
                    
                   )
                //.Aggregate(s => s.Opacity = 0.8)
                ;

            IStyleSheet.Default.AddRule(".off").style
                .Aggregate(s => 
                    
                        new HTML.Images.FromAssets.vistaLogoOff().ToBackground(s)
                    
                  )
                //.Aggregate(s => s.Opacity = 0.5)
                ;




            Action<int, int> UpdateColor =
                (x, y) =>
                {
                    var n = a[x, y];

                    if (m[x, y])
                    {
                        n.className = "on";
                    }
                    else
                    {
                        n.className = "off";
                    }

                };

            Action<int, int> ToggleDirect =
                (x, y) =>
                {
                    var n = a[x, y];

                    if (n == null)
                        return;

                    m[x, y] = !m[x, y];
                    UpdateColor(x, y);
                };

            Action<int, int> Toggle =
                (x, y) =>
                {
                    //Console.WriteLine("click at: " + new { x, y } + " = " + m[x, y]);

                    var f = ToggleDirect.WithOffset(x, y);

                    f(-1, 0);
                    f(0, -1);
                    f(0, 0);
                    f(0, 1);
                    f(1, 0);
                };


            var info_stats_clicks = new IHTMLDiv();
            var info_stats_clicks_count = 0;
            var info_stats_off = new IHTMLDiv();
            var info_stats_on = new IHTMLDiv();

            Action info_stats_update =
                () =>
                {
                    info_stats_clicks.innerHTML = info_stats_clicks_count + " clicks made so far";
                    info_stats_on.innerHTML = m.Count(i => i) + " blocks are on";
                    info_stats_off.innerHTML = m.Count(i => !i) + " blocks are off";

                };

            var info_stats = new IHTMLDiv(info_stats_clicks, info_stats_off, info_stats_on);
            info_stats.className = "info";


            a.ForEach(
                (x, y) =>
                {
                    var n = new IHTMLDiv();

                    n.style.left = (x * usersettings.tile.w + usersettings.tile.w / 2) + "px";
                    n.style.top = (y * usersettings.tile.h + usersettings.tile.h / 2) + "px";
                    n.style.width = usersettings.tile.w + "px";
                    n.style.height = usersettings.tile.h + "px";
                    n.style.position = IStyle.PositionEnum.absolute;
                    n.style.overflow = IStyle.OverflowEnum.hidden;

                    //n.style.border = "1px solid black";
                    n.style.cursor = IStyle.CursorEnum.pointer;

                    canvas.appendChild(n);

                    var tween = new TweenDataDouble();


                    tween.ValueChanged += () => n.style.Opacity = tween.Value;
                    tween.Value = usersettings.tile.cold;

                    n.style.Opacity = tween.Value;

                    n.onmouseover += delegate
                    {
                        tween.Value = 1;
                        //canvas_bg_tween.Value = 0.5;
                    };

                    n.onmouseout += delegate
                    {
                        tween.Value = usersettings.tile.cold;
                        //canvas_bg_tween.Value = 1;
                    };

                    n.onclick += delegate
                    {
                        info_stats_clicks_count++;

                        Toggle(x, y);


                        info_stats_update();
                    };


                    a[x, y] = n;

                    UpdateColor(x, y);

                }
            );

            var ani = new Timer(t =>
                               canvas_bg.style.left = -(int)System.Math.Floor((double)((IDate.Now.getTime() / 75) % canvas_size.x)) + "px");




            var info = new IHTMLDiv();

            var info_header_text = "Lights out 2";

            Native.Document.title = info_header_text;

            info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.h1, info_header_text));

            info.appendChild(new IHTMLAnchor("http://www.cjcraft.com/Blog/PermaLink,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx", "based on SilverlightsOut"));
            info.appendChild(new IHTMLBreak());
            info.appendChild(new IHTMLAnchor("http://www.cjcraft.com/Blog/CommentView,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx", "cjcraft blog post"));

            info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.p,
                @"Lights out is a one player puzzle that is played on a 5 by 5 grid of squares in which every square has two states: on and off. The game starts off with all squares off, where the goal is to turn on every square. By selecting a square, all the surrounding squares' (up, down, left, right) state is turned toggled. For example, on a 3 by 3 grid of squares with all squares off, if the center one is selected, it will turn 'on' the 4 up, down, left, right squares from it."));

            info.appendChild(new IHTMLDiv("Mozilla based browsers seem to suffer in performance while animating contents under semitransparent elements."));

            info.appendChild(new IHTMLButton("Animate background").Aggregate(btn => btn.onclick += delegate { ani.StartInterval(50); }));
            info.appendChild(new IHTMLButton("Freeze background").Aggregate(btn => btn.onclick += delegate { ani.Stop(); }));
            info.appendChild(info_stats);
            info.appendChild(canvas);

            info_stats_update();

            DataElement.insertNextSibling(info);

        }
Example #5
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);
        }
        public GoogleGearsAdvanced()
        {

            //Native.Window.alert("alert 1");

            CreateStyles();

            //Native.Window.alert("alert 2");

            var shadow = new div { className = "shadow" };
            var toolbar = new div { className = "toolbar" };
            var workspace0 = new div { className = "workspace0" };
            var workspace = new div { className = "workspace" };

            workspace0.appendChild(
                new div("You can create new postcards by clicking on the background image. You can drag those postcards by their borders. You can use your mouse wheel to zoom in or out, too. All postcards will be saved via webSQL. Doubleclick a postcard to delete it."));

            shadow.appendChild(workspace0, workspace, toolbar);



            //toolbar.innerHTML = "<a href='http://gears.google.com/'>get google gears</a> | <a href='http://jsc.sourceforge.net/'>jsc homepage</a> | <a href='http://zproxy.wordpress.com/'>blog</a>";
            //AppendError(workspace0, "loading 1...");


            var BackgroundTween = new TweenDataDouble();


            BackgroundTween.ValueChanged +=
                delegate
            {
                workspace.style.Opacity = BackgroundTween.Value;
            };

            BackgroundTween.Value = 0.5;

            workspace.onmouseover +=
                delegate
            {
                BackgroundTween.Value = 0;
            };

            workspace.onmouseout +=
                  delegate
            {
                BackgroundTween.Value = 0.5;
            };

            //AppendError(workspace0, "loading 2...");




            //var cc = new SQLiteConnection();
            //cc.Open();

            new { }.With(
                async delegate
            {
                while (true)
                {
                    await Native.window.async.onframe;

                    // we are logging a lot. idle more for now
                    await Task.Delay(500);

                    var Count = await new xxPostcard().Create().CountAsync();


                    // let UI know how many we have
                    Native.document.title = new { Count }.ToString();

                    // chrome style may not show title
                    toolbar.innerText = new { Count }.ToString();


                    // can we do conditional css here?
                    //toolbar.style.color = "blue";
                    //await toolbar.async.onclick;
                    //// undo
                    //toolbar.style.color = "";

                }
            }
            );



            new HTML.Images.FromAssets.postcard_alpha().InvokeOnComplete(
                postcard =>

            new HTML.Images.FromAssets.postcard_alpha_200_unfocus().InvokeOnComplete(
                postcard200 =>
                {
                    // at this point we have the image and we know how large it is
                    //AppendError(workspace0, "loading 3...");


                    // X:\jsc.svn\examples\javascript\forms\SQLiteConsoleExperiment\SQLiteConsoleExperiment\ApplicationControl.cs
                    // X:\jsc.svn\examples\javascript\Test\TestSQLiteConnection\TestSQLiteConnection\Application.cs

                    // Cannot read property 'transaction' of null"


                    new xxPostcard().Create();

                    //catch (System.Exception exc)
                    //{
                    //    var err_msg = exc.Message;
                    //    AppendError(workspace0, err_msg);
                    //}

                    //AppendError(workspace0, "loading 4...");

                    #region Spawn
                    Func<PostcardEntry, Postcard> Spawn =
                        template =>
                        {
                            var p2 = new Postcard(postcard, postcard200, workspace);

                            p2.CurrentDrag.Position.X = template.X;
                            p2.CurrentDrag.Position.Y = template.Y;
                            p2.AttachTo(shadow);

                            System.Console.WriteLine("new: " + p2.Id);

                            if (template.Text == null)
                            {
                                template.Text = new[] { "Hello!", "Yo!", "Whuzza!", "Howdy!", "Cheers!" }.Randomize().First() + "\nWrite something here!";
                            }

                            if (template.Zoom100 == 0)
                            {
                                template.Zoom100 = (int)System.Math.Floor((new System.Random().NextDouble() + 0.5) * 100);
                            }

                            p2.Content.value = template.Text;


                            System.Console.WriteLine("SetZoom: " + new { template.Zoom100 });

                            p2.SetZoom(template.Zoom100 / 100.0);

                            if (template.Id == null)
                            {
                                try
                                {
                                    new xxPostcard().InsertAsync(
                                        new xxPostcardRow
                                    {
                                        Id = p2.Id,
                                        Text = p2.Text,
                                        Zoom100 = (int)System.Math.Floor(p2.Zoom * 100),
                                        X = p2.CurrentDrag.Position.X,
                                        Y = p2.CurrentDrag.Position.Y
                                    }
                                    );
                                }
                                catch (System.Exception exc)
                                {
                                    AppendError(workspace0, exc.Message);
                                }
                            }
                            else
                            {
                                p2.Id = template.Id;
                            }







                            #region RightClick
                            p2.RightClick +=
                                delegate
                            {
                                System.Console.WriteLine("dispose: " + p2.Id);
                                p2.Dispose();

                                //db.execute("delete from Postcards where Id = ?", p2.Id);

                                Console.WriteLine("delete:");

                                //                                21:15078ms delete: view - source:41361
                                //Uncaught RangeError: Maximum call stack size exceeded
                                (
                                     from x in new xxPostcard()
                                     where x.Id == p2.Id
                                     select x
                                 ).Delete();

                                //new xPostcard().Where(x => x.Id == p2.Id).Delete(cc);
                                Console.WriteLine("delete: done?");

                            };
                            #endregion

                            #region DoubleClick
                            p2.DoubleClick +=
                                delegate
                            {
                                System.Console.WriteLine("dispose: " + p2.Id);
                                p2.Dispose();

                                //db.execute("delete from Postcards where Id = ?", p2.Id);

                                Console.WriteLine("delete:");
                                (
                                     from x in new xxPostcard()
                                     where x.Id == p2.Id
                                     select x
                                 ).Delete();

                                //new xPostcard().Where(x => x.Id == p2.Id).Delete(cc);
                                Console.WriteLine("delete: done?");

                            };
                            #endregion

                            #region Changed
                            p2.Changed +=
                                delegate
                            {
                                System.Console.WriteLine("changed: " + new PostcardEntry { Id = p2.Id, Text = p2.Text, Zoom100 = (int)System.Math.Floor(p2.Zoom * 100), X = p2.CurrentDrag.Position.X, Y = p2.CurrentDrag.Position.Y }.ToString());

                                Console.WriteLine("delete:");

                                new xxPostcard().Delete(x => x.Id == p2.Id);

                                new xxPostcard().InsertAsync(
                                    new xxPostcardRow
                                {
                                    Id = p2.Id,
                                    Text = p2.Text,
                                    Zoom100 = (int)System.Math.Floor(p2.Zoom * 100),
                                    X = p2.CurrentDrag.Position.X,
                                    Y = p2.CurrentDrag.Position.Y
                                }
                                );
                            };
                            #endregion

                            System.Console.WriteLine("item: " + template.ToString());




                            p2.ZoomAndMove();

                            p2.CurrentDrag.DragStart +=
                                delegate
                            {
                                p2.AttachTo(shadow);
                            };

                            return p2;
                        };
                    #endregion


                    workspace.onclick +=
                        delegate (IEvent ev)
                    {
                        Spawn(
                            new PostcardEntry { X = ev.CursorX, Y = ev.CursorY }
                        );

                    };

                    #region LoadFromDatabase
                    new { }.With(
                        async delegate
                    {
                        var query = from Data in new xxPostcard()
                                    select Data;

                        foreach (var v in await query.AsEnumerableAsync())
                        {
                            // 13:232ms {{ Text = hey, X = 355.0, Y = 243.0, Zoom100 = 30.0 }} 

                            //Console.WriteLine(new { v.Text, v.X, v.Y, v.Zoom100 });

                            Spawn(
                                new PostcardEntry
                            {
                                Id = v.Id,
                                Text = v.Text,
                                X = (int)v.X,
                                Y = (int)v.Y,
                                Zoom100 = Math.Max(60, (int)v.Zoom100),

                            }
                            );
                        }
                    }
                    );
                    #endregion
            }
            )
            );

            Native.Document.body.appendChild(shadow);
        }
Example #7
0
        //public const string Alias = "Class1";
        //public const string DefaultData = "Class1Data";


        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public SimpleRollover()
        {
            // wallpapers at http://labnol.blogspot.com/2006/11/download-windows-vista-wallpapers.html

            // * broken at the moment
            #region AnimateCharacterColors
            System.Func <string, INode> AnimateCharacterColors =
                (text) =>
            {
                var s = new IHTMLSpan();

                var l = new global::System.Collections.Generic.List <IHTMLSpan>();

                foreach (char c in text)
                {
                    var y = new string(c, 1);
                    var x = new IHTMLSpan(y);

                    if (y == " ")
                    {
                        s.appendChild(" ");
                    }
                    else
                    {
                        l.Add(x);


                        s.appendChild(x);
                    }
                }



                new Timer(
                    t =>
                {
                    var len = l.Count + 40;

                    if (t.Counter % len < l.Count)
                    {
                        if (t.Counter % (len * 2) < l.Count)
                        {
                            l[t.Counter % len].style.visibility = IStyle.VisibilityEnum.hidden;
                        }
                        else
                        {
                            l[t.Counter % len].style.visibility = IStyle.VisibilityEnum.visible;
                        }
                    }
                }, 6000, 200);


                return(s);
            };
            #endregion
            // */

            var u = new IHTMLDiv();

            //u.style.backgroundColor = Color.Green;
            u.style.position = IStyle.PositionEnum.absolute;
            u.style.left     = "0";
            u.style.top      = "0";
            u.style.height   = "100%";
            u.style.width    = "100%";
            u.style.overflow = IStyle.OverflowEnum.auto;

            var styles = new XStyles
            {
                dark         = new IStyleSheet(),
                light        = new IStyleSheet(),
                switchbutton = new IHTMLAnchor("", "day/night"),
                counter      = 0
            };



            styles.switchbutton.onclick +=
                ev =>
            {
                ev.PreventDefault();

                styles.counter++;


                if (styles.counter % 2 == 1)
                {
                    styles.dark.disabled  = false;
                    styles.light.disabled = true;
                }
                else
                {
                    styles.dark.disabled  = true;
                    styles.light.disabled = false;
                }
            };


            var ad = new IHTMLDiv(
                new IHTMLSpan(
                    AnimateCharacterColors(
                        "this application was written in c# and then translated to javascript by jsc to run in your browser"
                        )
                    ),
                new IHTMLAnchor("http://zproxy.wordpress.com", "visit blog"),
                new IHTMLAnchor("http://jsc.sf.net", "get more examples"),
                styles.switchbutton
                )
            {
                className = "ad1"
            };

            u.appendChild(ad);

            var sheet = new IStyleSheet();

            sheet.AddRule(".ad1",
                          r =>
            {
                r.style.marginTop  = "1em";
                r.style.color      = Color.White;
                r.style.fontFamily = IStyle.FontFamilyEnum.Verdana;
            }
                          );


            sheet.AddRule(".ad1 > *",
                          r =>
            {
                r.style.padding = "1em";

                r.style.marginTop = "1em";
            }
                          );

            sheet.AddRule(".ad1 > span",
                          r =>
            {
                r.style.Float = IStyle.FloatEnum.right;
            }
                          );

            sheet.AddRule(".ad1 > a",
                          r =>
            {
                r.style.Float = IStyle.FloatEnum.left;
                r.style.color = Color.White;

                r.style.textDecoration = "none";
            }
                          );

            sheet.AddRule(".ad1 a:hover",
                          r =>
            {
                r.style.color = Color.Yellow;
            }
                          );



            sheet.AddRule("html",
                          r =>
            {
                r.style.overflow = IStyle.OverflowEnum.hidden;
            }
                          );

            sheet.AddRule("body",
                          r =>
            {
                r.style.overflow = IStyle.OverflowEnum.hidden;

                r.style.padding = "0";
                r.style.margin  = "0";

                //r.style.backgroundImage = "url(assets/vista.jpg)";
            }
                          );


            styles.dark.AddRule("body").style.backgroundColor    = JSColor.Black;
            styles.dark.AddRule("body").style.backgroundPosition = "center top";

            styles.light.AddRule("body").style.backgroundColor    = JSColor.Black;
            styles.light.AddRule("body").style.backgroundPosition = "center top";


            new global::SimpleRollover.HTML.Images.FromAssets.vistax().ToBackground(
                styles.dark.AddRule("body").style, false
                );

            new global::SimpleRollover.HTML.Images.FromAssets.vista().ToBackground(
                styles.dark.AddRule(".effect1").style
                );

            styles.dark.AddRule(".moon1").style.backgroundColor = Color.Yellow;

            new global::SimpleRollover.HTML.Images.FromAssets.vista().ToBackground(
                styles.light.AddRule("body").style, false
                );

            new global::SimpleRollover.HTML.Images.FromAssets.vistax().ToBackground(
                styles.light.AddRule(".effect1").style
                );
            styles.light.AddRule(".moon1").style.backgroundColor = Color.Red;


            sheet.AddRule(".special1",
                          r =>
            {
                r.style.background = "none";
                r.style.border     = "0";
                r.style.width      = "100%";
                r.style.marginTop  = "4em";
            }
                          );

            sheet.AddRule(".content1",
                          r =>
            {
                r.style.backgroundColor = Color.White;

                r.style.padding     = "1em";
                r.style.marginLeft  = "4em";
                r.style.marginRight = "4em";
                r.style.Opacity     = 0.5;
                r.style.border      = "1px solid gray";
            }
                          );

            sheet.AddRule(".special1 img", "border: 0", 0);
            sheet.AddRule(".special1:hover", "background: url(" + new global::SimpleRollover.HTML.Images.FromAssets.Untitled_3().src + ") repeat-x", 1);

            sheet.AddRule(".special1 .hot").style.display       = IStyle.DisplayEnum.none;
            sheet.AddRule(".special1:hover .hot").style.display = IStyle.DisplayEnum.inline;

            sheet.AddRule(".special1 .cold", "display: inline;", 1);
            sheet.AddRule(".special1:hover .cold", "display: none;", 1);


            var states = new XState[] { }.AsEnumerable();

            //    new XState {
            //        Show = default(System.Action),
            //        Hide = default(System.Action),
            //        Selected = false }
            //}.Where(p => false);


            Action <IHTMLImage, IHTMLImage, string> Spawn =
                async(icold, ihot, i2) =>
            {
                var cold = await icold;
                var hot  = await ihot;

                //((IHTMLImage)i[0]).InvokeOnComplete(cold =>
                //((IHTMLImage)i[1]).InvokeOnComplete(hot =>
                //     {
                cold.className = "cold";
                hot.className  = "hot";


                var btn = new IHTMLButton()
                {
                    className = "special1"
                };

                btn.appendChild(cold, hot);

                var content = new IHTMLElement(IHTMLElement.HTMLElementEnum.pre);

                content.innerHTML = "...";
                content.className = "content1";

                var tween     = new TweenDataDouble();
                var tween_max = 16;

                tween.ValueChanged +=
                    delegate
                {
                    content.style.Opacity = tween.Value / tween_max;
                    content.style.height  = tween.Value + "em";

                    content.style.overflow = IStyle.OverflowEnum.hidden;
                };

                tween.Done += delegate
                {
                    if (tween.Value > 0)
                    {
                        content.style.overflow = IStyle.OverflowEnum.auto;
                    }
                };

                tween.Value = 0;

                var state = new XState
                {
                    Show = (System.Action)(() =>
                    {
                        tween.Value = tween_max;
                    }
                                           ),
                    Hide     = (System.Action)(() => tween.Value = 0),
                    Selected = false
                };

                //try
                //{
                //    new IXMLHttpRequest(HTTPMethodEnum.GET, i[2],
                //       request => content.innerHTML = request.responseText
                //    );
                //}
                //catch
                //{
                content.innerText = i2;
                //}

                states = states.Concat(new[] { state });

                btn.onclick +=
                    delegate
                {
                    foreach (var v in states)
                    {
                        if (v == state)
                        {
                            v.Selected = !v.Selected;

                            if (v.Selected)
                            {
                                v.Show();
                            }
                            else
                            {
                                v.Hide();
                            }
                        }
                        else
                        {
                            v.Selected = false;
                            v.Hide();
                        }
                    }
                };

                u.appendChild(btn, content);
            };


            SpawnCursor();


            u.AttachToDocument();

            Spawn(
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_1_03(),
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_2_03(),
                "This application was written in C#."
                );

            Spawn(
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_1_07(),
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_2_07(),

                "This application was cross compiled into JavaScript."
                );
        }
Example #8
0
        public GoogleGearsAdvanced()
        {
            //Native.Window.alert("alert 1");

            CreateStyles();

            //Native.Window.alert("alert 2");

            var shadow = new div {
                className = "shadow"
            };
            var toolbar = new div {
                className = "toolbar"
            };
            var workspace0 = new div {
                className = "workspace0"
            };
            var workspace = new div {
                className = "workspace"
            };

            workspace0.appendChild(
                new div("You can create new postcards by clicking on the background image. You can drag those postcards by their borders. You can use your mouse wheel to zoom in or out, too. All postcards will be saved via webSQL. Doubleclick a postcard to delete it."));

            shadow.appendChild(workspace0, workspace, toolbar);



            //toolbar.innerHTML = "<a href='http://gears.google.com/'>get google gears</a> | <a href='http://jsc.sourceforge.net/'>jsc homepage</a> | <a href='http://zproxy.wordpress.com/'>blog</a>";
            //AppendError(workspace0, "loading 1...");


            var BackgroundTween = new TweenDataDouble();


            BackgroundTween.ValueChanged +=
                delegate
            {
                workspace.style.Opacity = BackgroundTween.Value;
            };

            BackgroundTween.Value = 0.5;

            workspace.onmouseover +=
                delegate
            {
                BackgroundTween.Value = 0;
            };

            workspace.onmouseout +=
                delegate
            {
                BackgroundTween.Value = 0.5;
            };

            //AppendError(workspace0, "loading 2...");



            //var cc = new SQLiteConnection();
            //cc.Open();

            new { }.With(
                async delegate
            {
                while (true)
                {
                    await Native.window.async.onframe;

                    // we are logging a lot. idle more for now
                    await Task.Delay(500);

                    var Count = await new xxPostcard().Create().CountAsync();


                    // let UI know how many we have
                    Native.document.title = new { Count }.ToString();

                    // chrome style may not show title
                    toolbar.innerText = new { Count }.ToString();


                    // can we do conditional css here?
                    //toolbar.style.color = "blue";
                    //await toolbar.async.onclick;
                    //// undo
                    //toolbar.style.color = "";
                }
            }
                );



            new HTML.Images.FromAssets.postcard_alpha().InvokeOnComplete(
                postcard =>

                new HTML.Images.FromAssets.postcard_alpha_200_unfocus().InvokeOnComplete(
                    postcard200 =>
            {
                // at this point we have the image and we know how large it is
                //AppendError(workspace0, "loading 3...");


                // X:\jsc.svn\examples\javascript\forms\SQLiteConsoleExperiment\SQLiteConsoleExperiment\ApplicationControl.cs
                // X:\jsc.svn\examples\javascript\Test\TestSQLiteConnection\TestSQLiteConnection\Application.cs

                // Cannot read property 'transaction' of null"


                new xxPostcard().Create();

                //catch (System.Exception exc)
                //{
                //    var err_msg = exc.Message;
                //    AppendError(workspace0, err_msg);
                //}

                //AppendError(workspace0, "loading 4...");

                #region Spawn
                Func <PostcardEntry, Postcard> Spawn =
                    template =>
                {
                    var p2 = new Postcard(postcard, postcard200, workspace);

                    p2.CurrentDrag.Position.X = template.X;
                    p2.CurrentDrag.Position.Y = template.Y;
                    p2.AttachTo(shadow);

                    System.Console.WriteLine("new: " + p2.Id);

                    if (template.Text == null)
                    {
                        template.Text = new[] { "Hello!", "Yo!", "Whuzza!", "Howdy!", "Cheers!" }.Randomize().First() + "\nWrite something here!";
                    }

                    if (template.Zoom100 == 0)
                    {
                        template.Zoom100 = (int)System.Math.Floor((new System.Random().NextDouble() + 0.5) * 100);
                    }

                    p2.Content.value = template.Text;


                    System.Console.WriteLine("SetZoom: " + new { template.Zoom100 });

                    p2.SetZoom(template.Zoom100 / 100.0);

                    if (template.Id == null)
                    {
                        try
                        {
                            new xxPostcard().InsertAsync(
                                new xxPostcardRow
                            {
                                Id      = p2.Id,
                                Text    = p2.Text,
                                Zoom100 = (int)System.Math.Floor(p2.Zoom * 100),
                                X       = p2.CurrentDrag.Position.X,
                                Y       = p2.CurrentDrag.Position.Y
                            }
                                );
                        }
                        catch (System.Exception exc)
                        {
                            AppendError(workspace0, exc.Message);
                        }
                    }
                    else
                    {
                        p2.Id = template.Id;
                    }



                    #region RightClick
                    p2.RightClick +=
                        delegate
                    {
                        System.Console.WriteLine("dispose: " + p2.Id);
                        p2.Dispose();

                        //db.execute("delete from Postcards where Id = ?", p2.Id);

                        Console.WriteLine("delete:");

                        //                                21:15078ms delete: view - source:41361
                        //Uncaught RangeError: Maximum call stack size exceeded
                        (
                            from x in new xxPostcard()
                            where x.Id == p2.Id
                            select x
                        ).Delete();

                        //new xPostcard().Where(x => x.Id == p2.Id).Delete(cc);
                        Console.WriteLine("delete: done?");
                    };
                    #endregion

                    #region DoubleClick
                    p2.DoubleClick +=
                        delegate
                    {
                        System.Console.WriteLine("dispose: " + p2.Id);
                        p2.Dispose();

                        //db.execute("delete from Postcards where Id = ?", p2.Id);

                        Console.WriteLine("delete:");
                        (
                            from x in new xxPostcard()
                            where x.Id == p2.Id
                            select x
                        ).Delete();

                        //new xPostcard().Where(x => x.Id == p2.Id).Delete(cc);
                        Console.WriteLine("delete: done?");
                    };
                    #endregion

                    #region Changed
                    p2.Changed +=
                        delegate
                    {
                        System.Console.WriteLine("changed: " + new PostcardEntry {
                            Id = p2.Id, Text = p2.Text, Zoom100 = (int)System.Math.Floor(p2.Zoom * 100), X = p2.CurrentDrag.Position.X, Y = p2.CurrentDrag.Position.Y
                        }.ToString());

                        Console.WriteLine("delete:");

                        new xxPostcard().Delete(x => x.Id == p2.Id);

                        new xxPostcard().InsertAsync(
                            new xxPostcardRow
                        {
                            Id      = p2.Id,
                            Text    = p2.Text,
                            Zoom100 = (int)System.Math.Floor(p2.Zoom * 100),
                            X       = p2.CurrentDrag.Position.X,
                            Y       = p2.CurrentDrag.Position.Y
                        }
                            );
                    };
                    #endregion

                    System.Console.WriteLine("item: " + template.ToString());



                    p2.ZoomAndMove();

                    p2.CurrentDrag.DragStart +=
                        delegate
                    {
                        p2.AttachTo(shadow);
                    };

                    return(p2);
                };
                #endregion


                workspace.onclick +=
                    delegate(IEvent ev)
                {
                    Spawn(
                        new PostcardEntry {
                        X = ev.CursorX, Y = ev.CursorY
                    }
                        );
                };

                #region LoadFromDatabase
                new { }.With(
                    async delegate
                {
                    var query = from Data in new xxPostcard()
                                select Data;

                    foreach (var v in await query.AsEnumerableAsync())
                    {
                        // 13:232ms {{ Text = hey, X = 355.0, Y = 243.0, Zoom100 = 30.0 }}

                        //Console.WriteLine(new { v.Text, v.X, v.Y, v.Zoom100 });

                        Spawn(
                            new PostcardEntry
                        {
                            Id      = v.Id,
                            Text    = v.Text,
                            X       = (int)v.X,
                            Y       = (int)v.Y,
                            Zoom100 = Math.Max(60, (int)v.Zoom100),
                        }
                            );
                    }
                }
                    );
                #endregion
            }
                    )
                );

            Native.Document.body.appendChild(shadow);
        }
Example #9
0
        private static void Spawn()
        {
            // this ctor creates a new div which has a text and a button element
            // on mouseover over the color text is changed
            // on pressing the button the next message in text element is displayed


            IStyleSheet.Default.AddRule("img.fx1",
                                        r =>
            {
                r.style.position = IStyle.PositionEnum.absolute;
                r.style.top      = "0";
                r.style.border   = "0";
            });


            Native.css.style.cursorImage = new HTML.Images.FromAssets.cursor01();

            //IStyleSheet.Default.AddRule("*", "cursor: url('" + new HTML.Images.FromAssets.cursor01().src + "'), auto;", 0);

            var img = new HTML.Images.FromAssets._99851426_7f408a6cc3_o_gray {
                className = "fx1"
            };

            var img_up = new HTML.Images.FromAssets.up {
                className = "fx1"
            };
            var img_up_neg = new HTML.Images.FromAssets.up_neg {
                className = "fx1"
            };
            var img_down = new HTML.Images.FromAssets.down {
                className = "fx1"
            };



            img.AttachToDocument();
            img_up.AttachToDocument();
            img_up_neg.AttachToDocument();


            var info_size = new XSize
            {
                width  = 350,
                height = 200
            };

            var info_bg = new IHTMLDiv();

            info_bg.style.SetLocation(60, 60, info_size.width, info_size.height);
            info_bg.style.Opacity = 0.2;
            info_bg.style.zIndex  = 1;
            info_bg.AttachToDocument();

            var info_borders = new IHTMLDiv();

            info_borders.style.SetLocation(60 - 4, 60 - 4, info_size.width + 8, info_size.height + 8);
            info_borders.style.Opacity = 0.2;
            info_borders.style.zIndex  = 4;
            info_borders.AttachToDocument();

            var info_drag_tween = new TweenDataDouble();

            var info_bg_useimage_cookie = new Cookie("setting1");

            var info_bg_useimage = new DynamicProperty <bool>(
                p =>
            {
                info_bg_useimage_cookie.BooleanValue = p.Value;

                if (p.Value)
                {
                    new HTML.Images.FromAssets.up_neg().ToBackground(info_borders.style);
                    new HTML.Images.FromAssets.up_neg().ToBackground(info_bg.style);
                }
                else
                {
                    info_borders.style.backgroundImage = "";
                    info_bg.style.backgroundImage      = "";
                }

                info_drag_tween.Value = 0.5;
            }
                )
            {
                Value = info_bg_useimage_cookie.BooleanValue
            };



            var info_drag = new DragHelper(info_borders);

            info_drag_tween.Value         = 0;
            info_drag_tween.ValueChanged +=
                delegate
            {
                var i = ScriptCoreLib.JavaScript.Runtime.Convert.ToInteger(255 * info_drag_tween.Value);

                if (!info_bg_useimage.Value)
                {
                    info_bg.style.backgroundColor      = Color.FromRGB(i, i, 0);
                    info_borders.style.backgroundColor = Color.FromRGB(i, i, 0);
                }
                else
                {
                    if (i < 1)
                    {
                        i = 1;
                    }

                    info_bg.style.Opacity      = i / 255;
                    info_borders.style.Opacity = i / 255 * 0.5;
                }
            };

            info_borders.style.cursor = IStyle.CursorEnum.move;

            info_borders.onmouseover +=
                delegate
            {
                if (info_drag.IsDrag)
                {
                    return;
                }

                info_drag_tween.Value = 1;
            };



            info_borders.onmouseout +=
                delegate
            {
                if (info_drag.IsDrag)
                {
                    return;
                }

                info_drag_tween.Value = 0;
            };



            var info = new IHTMLDiv();

            info.onmouseover +=
                delegate
            {
                if (info_drag.IsDrag)
                {
                    return;
                }

                info_drag_tween.Value = 0.5;
            };



            info.onmouseout +=
                delegate
            {
                if (info_drag.IsDrag)
                {
                    return;
                }

                info_drag_tween.Value = 0;
            };

            info.style.color      = Color.White;
            info.style.fontFamily = IStyle.FontFamilyEnum.Tahoma;

            Func <string, IHTMLElement> par = texty => new IHTMLElement(IHTMLElement.HTMLElementEnum.p, texty);


            Native.Document.title = "HotPolygon";

            info.innerHTML = @"<h1>HotPolygon</h1>";

            //var preview = new IHTMLImage("assets/HotPolygon/Preview.png");

            //preview.style.Float = IStyle.FloatEnum.right;
            //preview.style.margin = "1em";

            info.appendChild(
                //preview,
                par("This example demonstrates the use of custom cursors, map, area, timed animation, cookies and a custom dialog."),
                par("You can change the background of this page by hovering above the tree or one of the clouds."),
                par("And yes you can drag this dialog at the borders :)"),

                new IHTMLDiv(
                    @"
                    <ul>
                        <li>visit <a href='http://jsc.sf.net/'>jsc homepage</a></li>
                        <li>visit <a href='http://zproxy.wordpress.com/'>blog</a></li>
                    </ul>
                                ")
                );



            var info_option       = new IHTMLInput(HTMLInputTypeEnum.checkbox);
            var info_option_label = new IHTMLLabel("Alternative background", info_option);


            info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.p, info_option, info_option_label));



            info_option.onclick += i => info_bg_useimage.Value = info_option.@checked;
            info_option.@checked = info_bg_useimage.Value;

            info.style.overflow = IStyle.OverflowEnum.auto;

            info.style.SetLocation(70, 70, info_size.width - 20, info_size.height - 20);
            info.style.zIndex = 5;
            info.AttachToDocument();

            info_drag.DragMove +=
                delegate
            {
                if (info_bg_useimage.Value)
                {
                    info_borders.style.backgroundPosition = (-(info_drag.Position.X - 4)) + "px " + (-(info_drag.Position.Y - 4)) + "px";
                    info_bg.style.backgroundPosition      = (-info_drag.Position.X) + "px " + (-info_drag.Position.Y) + "px";
                }

                info_borders.style.SetLocation(info_drag.Position.X - 4, info_drag.Position.Y - 4);
                info_bg.style.SetLocation(info_drag.Position.X, info_drag.Position.Y);
                info.style.SetLocation(info_drag.Position.X + 10, info_drag.Position.Y + 10);
            };

            info_drag.Position = new Point(60, 60);
            info_drag.Enabled  = true;

            // 416 x 100

            var img_here_src_off =
                new IHTMLImage[]
            {
                new HTML.Images.FromAssets.here0(),
                new HTML.Images.FromAssets.here1(),
                new HTML.Images.FromAssets.here2(),
                new HTML.Images.FromAssets.here3(),
                new HTML.Images.FromAssets.here4(),
                new HTML.Images.FromAssets.here5(),
            };

            var img_here_src_on =
                new IHTMLImage[]
            {
                new HTML.Images.FromAssets.here0(),
                new HTML.Images.FromAssets.here1(),
                new HTML.Images.FromAssets.here2(),
                new HTML.Images.FromAssets.here3(),
                new HTML.Images.FromAssets.here4(),
                new HTML.Images.FromAssets.here5(),
            }.Reverse().ToArray();



            var img_here = new IHTMLDiv();

            img_here.style.SetSize(416, 100);

            Action <Action, int> Wait =
                (done, time) =>
            {
                new Timer(t => done(), time, 0);
            };


            ActionParams <Action, Action> DelayFrames =
                (done, h) =>
            {
                int i = 0;

                var next = default(Action);

                next = () =>
                {
                    if (i < h.Length)
                    {
                        var v = h[i];
                        i++;

                        Wait(() => { if (v != null)
                                     {
                                         v();
                                     }
                                     next(); }, 1000 / 24);
                    }
                    else
                    {
                        Wait(done, 1000 / 24);
                    }
                };

                next();
            };


            var AnimationOn       = default(Action);
            var AnimationOff      = default(Action);
            var AnimationRandomOn = default(Action);


            AnimationOff =
                () =>
            {
                DelayFrames(
                    () =>
                {
                    img_here.style.display = IStyle.DisplayEnum.none;

                    Wait(() =>
                    {
                        AnimationRandomOn();
                    }, 5000);
                }
                    ,
                    img_here_src_off.Select <IHTMLImage, Action>(i => () => i.ToBackground(img_here.style)).ToArray()
                    );
            };

            AnimationOn =
                () =>
            {
                img_here.style.display = IStyle.DisplayEnum.block;

                DelayFrames(
                    () => Wait(AnimationOff, 3000),
                    img_here_src_on.Select <IHTMLImage, Action>(i => () => i.ToBackground(img_here.style)).ToArray()
                    );
            };

            AnimationRandomOn =
                () =>
            {
                try
                {
                    if (new System.Random().NextDouble() > 0.5)
                    {
                        img_here.SetCenteredLocation(589, 509);
                    }
                    else
                    {
                        img_here.SetCenteredLocation(686, 141);
                    }

                    Wait(AnimationOn, new System.Random().Next() % 15000);
                }
                catch
                {
                }
            };


            img_here.style.SetLocation(100, 100);
            img_here.style.zIndex = 1;

            AnimationRandomOn();


            img_here.AttachToDocument();

            img_down.AttachToDocument();

            img_up.style.Opacity     = 0;
            img_up_neg.style.Opacity = 0;

            var tw_up = new TweenDataDouble();

            tw_up.Value         = 0;
            tw_up.ValueChanged += delegate { img_up.style.Opacity = tw_up.Value; };

            var tw_up_neg = new TweenDataDouble();

            tw_up_neg.Value         = 0;
            tw_up_neg.ValueChanged += delegate { img_up_neg.style.Opacity = tw_up_neg.Value; };



            var map = new IHTMLElement(IHTMLElement.HTMLElementEnum.map);

            map.id   = "map1";
            map.name = "map1";

            var area1 = new IHTMLArea
            {
                shape  = ShapeEnum.polygon,
                coords = "477, 178, 515, 144, 557, 160, 576, 194, 614, 181, 629, 206, 648, 209, 659, 163, 719, 154, 730, 103, 845, 118, 891, 168, 949, 213, 917, 246, 931, 266, 859, 300, 787, 302, 756, 274, 721, 294, 658, 282, 615, 257, 537, 239, 492, 230, 470, 195"
            };

            area1.onmouseover += i =>
            {
                System.Console.WriteLine("over");
                tw_up_neg.Value = 1;                          /*tw_down.Value = 0.2;*/
            };
            area1.onmouseout += i =>
            {
                try
                {
                    System.Console.WriteLine("out");
                    tw_up_neg.Value = 0;                        /* tw_down.Value = 1;*/
                }
                catch
                {
                }
            };


            var area2 = new IHTMLArea
            {
                shape  = ShapeEnum.polygon,
                coords = "677, 556, 718, 551, 747, 570, 758, 594, 756, 613, 729, 625, 688, 629, 663, 604, 657, 585"
            };



            area2.onmouseover += i =>
            {
                System.Console.WriteLine("over");
                tw_up.Value = 1;                          /*tw_down.Value = 0.2;*/
            };
            area2.onmouseout += i =>
            {
                try
                {
                    System.Console.WriteLine("out");
                    tw_up.Value = 0;                        /* tw_down.Value = 1;*/
                }
                catch
                {
                }
            };

            img_down.onclick += i => System.Console.WriteLine(i.CursorPosition);

            //area1.href = "http://google.com";
            //area1.target = "_blank";

            map.appendChild(area1);
            map.appendChild(area2);

            map.AttachToDocument();


            img_down.style.zIndex = 2;
            img_down.setAttribute("useMap", "#map1");


            //img_overlay.style.backgroundColor = Color.Red;
        }
Example #10
0
        public Card(CardDeck d, CardInfo i)
        {
            CurrentDeck = d;

            Drag = new DragHelper(Control);
            OpacityHelper = new TweenDataDouble(
                delegate
                {
                    foreach (Card v in this.MovableCards)
                    {
                        v.Control.style.Opacity = Opacity;
                    }
                }
                );

            Info = i;

            Control.style.cursor = IStyle.CursorEnum.@default;
            Control.style.SetSize(CardInfo.Width, CardInfo.Height);

            

            Native.Document.body.appendChild(Control);

            MoveTo(Drag.Position);

            Drag.History = new System.Collections.Generic.List<Point>();

            Drag.DragStop +=
                delegate
                {
                    Opacity = 1;

                    var s = FindStack();

                    if (s == null)
                        MoveTo(Drag.History.First());
                    else
                    {
                        s.AttachCards(this.MovableCards);
                    }

                    Drag.History.Clear();
                };

            Drag.DragStart +=
                delegate
                {
                    Opacity = 0.7;

                    foreach (Card v in MovableCards)
                    {
                        v.BringToFront();
                    }
                };

            Drag.DragMove +=
                delegate
                {
                   
                          
                 
                    var s = FindStack();

                    if (s != null)
                    {
                        Opacity = 1;
                        MoveTo(s.NextPosition);
                    }
                    else
                    {
                        Opacity = 0.7;
                        MoveTo(Drag.Position);
                    }
                

                    
               

                };



            Control.ondblclick += ( e) => Helper.Invoke(DoubleClick);
            Control.onclick += delegate (IEvent e)
            {

                Helper.Invoke(Click);

                if (CurrentStack != null)
                    CurrentStack.RaiseClick(this);
            };
    

    
            Opacity = 1;

            Enabled = false;
        }
        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public LightsOut2FullScreen()
        {
            // based on http://www.cjcraft.com/Blog/PermaLink,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx

            // what happens in beta2 when the anonymous types are immutable? :)


            var usersettings = new __Type1 {
                x = 5, y = 5, tile = new __Type2 {
                    w = 64, h = 64, cold = 0.8
                }
            };
            var search = Native.document.location.search;

            if (search.StartsWith("?"))
            {
                var values = from i in search.Substring(1).Split('&')
                             let kvp = i.Split('=')
                                       where kvp.Length == 2
                                       select new { key = kvp[0], value = kvp[1] };

                var _x = values.FirstOrDefault(i => i.key == "x");
                if (_x != null)
                {
                    usersettings.x = int.Parse(_x.value);
                }

                var _y = values.FirstOrDefault(i => i.key == "y");
                if (_y != null)
                {
                    usersettings.y = int.Parse(_y.value);
                }
            }

            var a = new Array2D <IHTMLDiv>(usersettings.x, usersettings.y);
            var m = a.ToBooleanArray();



            var r = new System.Random();

            m.ForEach(
                (x, y) =>
            {
                m[x, y] = r.NextDouble() > 0.5;
            }
                );


            var canvas = new IHTMLDiv();

            canvas.className = "canvas";


            // does it work???
            //canvas.MakeCSSShaderCrumple();

            canvas.style.overflow        = IStyle.OverflowEnum.hidden;
            canvas.style.backgroundColor = Color.Black;


            var canvas_size = new __Type1 {
                x = ((a.XLength + 1) * usersettings.tile.w), y = ((a.YLength + 1) * usersettings.tile.h)
            };

            canvas.style.position = IStyle.PositionEnum.relative;
            canvas.style.border   = "2px solid black";
            canvas.style.width    = canvas_size.x + "px";
            canvas.style.height   = canvas_size.y + "px";

            var canvas_bg = new IHTMLDiv();

            //var canvas_bg_tween = new TweenDataDouble();

            //canvas_bg_tween.Value = 1;
            //canvas_bg_tween.ValueChanged += delegate { canvas_bg.style.Opacity = canvas_bg_tween.Value; };

            new HTML.Images.FromAssets.background().ToBackground(canvas_bg.style);

            //canvas_bg.style.backgroundImage = Assets.Default.Background.StyleSheetURL;
            canvas_bg.style.SetLocation(0, 0, canvas_size.x * 2, canvas_size.y);

            canvas.appendChild(canvas_bg);


            Action <int, int> UpdateColor =
                (x, y) =>
            {
                var n = a[x, y];

                if (m[x, y])
                {
                    new HTML.Images.FromAssets.vistaLogoOn().ToBackground(n.style);
                    //n.style.backgroundImage = Assets.Default.LogoOn.StyleSheetURL;
                    //n.className = "on";
                }
                else
                {
                    new HTML.Images.FromAssets.vistaLogoOff().ToBackground(n.style);
                    //n.style.backgroundImage = Assets.Default.LogoOff.StyleSheetURL;
                    //n.className = "off";
                }
            };

            Action <int, int> ToggleDirect =
                (x, y) =>
            {
                var n = a[x, y];

                if (n == null)
                {
                    return;
                }

                m[x, y] = !m[x, y];
                UpdateColor(x, y);
            };

            Action <int, int> Toggle =
                (x, y) =>
            {
                //Console.WriteLine("click at: " + new { x, y } + " = " + m[x, y]);

                var f = ToggleDirect.WithOffset(x, y);

                f(-1, 0);
                f(0, -1);
                f(0, 0);
                f(0, 1);
                f(1, 0);
            };


            var info_stats_clicks       = new IHTMLDiv();
            var info_stats_clicks_count = 0;
            var info_stats_off          = new IHTMLDiv();
            var info_stats_on           = new IHTMLDiv();

            Action info_stats_update =
                () =>
            {
                info_stats_clicks.innerHTML = info_stats_clicks_count + " clicks made so far";
                info_stats_on.innerHTML     = m.Count(i => i) + " blocks are on";
                info_stats_off.innerHTML    = m.Count(i => !i) + " blocks are off";
            };

            var info_stats = new IHTMLDiv(info_stats_clicks, info_stats_off, info_stats_on);

            info_stats.className = "info";


            a.ForEach(
                (x, y) =>
            {
                var n = new IHTMLDiv();

                n.style.left     = (x * usersettings.tile.w + usersettings.tile.w / 2) + "px";
                n.style.top      = (y * usersettings.tile.h + usersettings.tile.h / 2) + "px";
                n.style.width    = usersettings.tile.w + "px";
                n.style.height   = usersettings.tile.h + "px";
                n.style.position = IStyle.PositionEnum.absolute;
                n.style.overflow = IStyle.OverflowEnum.hidden;

                //n.style.border = "1px solid black";
                n.style.cursor = IStyle.CursorEnum.pointer;

                canvas.appendChild(n);

                var tween = new TweenDataDouble();


                tween.ValueChanged += () => n.style.Opacity = tween.Value;
                tween.Value         = usersettings.tile.cold;

                n.style.Opacity = tween.Value;

                n.onmouseover += delegate
                {
                    tween.Value = 1;
                    //canvas_bg_tween.Value = 0.5;
                };

                n.onmouseout += delegate
                {
                    tween.Value = usersettings.tile.cold;
                    //canvas_bg_tween.Value = 1;
                };

                n.onclick += delegate
                {
                    info_stats_clicks_count++;

                    Toggle(x, y);


                    info_stats_update();

                    new click().play();
                };


                a[x, y] = n;

                UpdateColor(x, y);
            }
                );

            var ani = new Timer(t =>
                                canvas_bg.style.left = -(int)System.Math.Floor((double)((IDate.Now.getTime() / 75) % canvas_size.x)) + "px");



            var info = new IHTMLDiv();

            info_stats.style.Aggregate(
                s =>
            {
                s.backgroundColor = Color.Black;
                s.color           = Color.White;
                s.padding         = "2em";
                s.fontFamily      = IStyle.FontFamilyEnum.Tahoma;
                s.Float           = IStyle.FloatEnum.right;
            }
                );

            var info_header_text = "Lights out 2";

            Native.Document.title = info_header_text;
            Native.Document.body.style.backgroundColor = Color.Black;

            /*
             * info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.h1, info_header_text));
             *
             * info.appendChild(new IHTMLAnchor("http://www.cjcraft.com/Blog/PermaLink,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx", "based on SilverlightsOut"));
             * info.appendChild(new IHTMLBreak());
             * info.appendChild(new IHTMLAnchor("http://www.cjcraft.com/Blog/CommentView,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx", "cjcraft blog post"));
             *
             * info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.p,
             *  @"Lights out is a one player puzzle that is played on a 5 by 5 grid of squares in which every square has two states: on and off. The game starts off with all squares off, where the goal is to turn on every square. By selecting a square, all the surrounding squares' (up, down, left, right) state is turned toggled. For example, on a 3 by 3 grid of squares with all squares off, if the center one is selected, it will turn 'on' the 4 up, down, left, right squares from it."));
             *
             * info.appendChild(new IHTMLDiv("Mozilla based browsers seem to suffer in performance while animating contents under semitransparent elements."));
             *
             * info.appendChild(new IHTMLButton("Animate background").Aggregate(btn => btn.onclick += delegate { ani.StartInterval(50); }));
             * info.appendChild(new IHTMLButton("Freeze background").Aggregate(btn => btn.onclick += delegate { ani.Stop(); }));
             */

            ani.StartInterval(50);

            info.appendChild(info_stats);
            info.appendChild(canvas);

            info_stats_update();


            info.AttachToDocument();

            new reveal().play();
        }
Example #12
0
        public Card(CardDeck d, CardInfo i)
        {
            CurrentDeck = d;

            Drag          = new DragHelper(Control);
            OpacityHelper = new TweenDataDouble(
                delegate
            {
                foreach (Card v in this.MovableCards)
                {
                    v.Control.style.Opacity = Opacity;
                }
            }
                );

            Info = i;

            Control.style.cursor = IStyle.CursorEnum.@default;
            Control.style.SetSize(CardInfo.Width, CardInfo.Height);



            Native.Document.body.appendChild(Control);

            MoveTo(Drag.Position);

            Drag.History = new System.Collections.Generic.List <Point>();

            Drag.DragStop +=
                delegate
            {
                Opacity = 1;

                var s = FindStack();

                if (s == null)
                {
                    MoveTo(Drag.History.First());
                }
                else
                {
                    s.AttachCards(this.MovableCards);
                }

                Drag.History.Clear();
            };

            Drag.DragStart +=
                delegate
            {
                Opacity = 0.7;

                foreach (Card v in MovableCards)
                {
                    v.BringToFront();
                }
            };

            Drag.DragMove +=
                delegate
            {
                var s = FindStack();

                if (s != null)
                {
                    Opacity = 1;
                    MoveTo(s.NextPosition);
                }
                else
                {
                    Opacity = 0.7;
                    MoveTo(Drag.Position);
                }
            };



            Control.ondblclick += (e) => Helper.Invoke(DoubleClick);
            Control.onclick    += delegate(IEvent e)
            {
                Helper.Invoke(Click);

                if (CurrentStack != null)
                {
                    CurrentStack.RaiseClick(this);
                }
            };



            Opacity = 1;

            Enabled = false;
        }