public UltraApplication(IHTMLElement e)
		{
			var Title = new IHTMLDiv
				{
					innerHTML = @"
<img border='0' src='http://www.w3schools.com/images/compatible_ie.gif' width='31' height='30' alt='Internet Explorer' title='Internet Explorer' />
<img border='0' src='http://www.w3schools.com/images/compatible_firefox.gif' width='31' height='30' alt='Firefox' title='Firefox' />
<img border='0' src='http://www.w3schools.com/images/compatible_opera.gif' width='28' height='30' alt='Opera' title='Opera' />
<img border='0' src='http://www.w3schools.com/images/compatible_chrome.gif' width='31' height='30' alt='Google Chrome' title='Google Chrome' />
<img border='0' src='http://www.w3schools.com/images/compatible_safari.gif' width='28' height='30' alt='Safari' title='Safari' />
"
				};


			var TitleLogo = new IHTMLImage("assets/ScriptCoreLib/jsc.png");
			var TitleText = new IHTMLSpan("UltraApplication");
			TitleText.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
			TitleText.style.paddingLeft = "2em";
			TitleText.style.fontSize = "xx-large";
			TitleLogo.style.verticalAlign = "middle";


			Title.appendChild(TitleLogo);
			Title.appendChild(TitleText);

			Title.style.height = "128px";

			Title.AttachToDocument();
			Title.FadeIn(2500, 1000,
				delegate
				{
					1500.AtDelay(ContinueBuildingApplication);
				}
			);
		}
        static IHTMLSpan InternalConstructor(string e)
        {
            IHTMLSpan n = new IHTMLSpan();

            n.innerHTML = e;

            return(n);
        }
        static IHTMLSpan InternalConstructor(params INode[] e)
        {
            IHTMLSpan n = new IHTMLSpan();

            n.appendChild(e);

            return(n);
        }
        static IHTMLSpan InternalConstructor(params INode[] e)
        {
            IHTMLSpan n = new IHTMLSpan();

            n.appendChild(e);

            return n;
        }
        static IHTMLSpan InternalConstructor(string e)
        {
            IHTMLSpan n = new IHTMLSpan();

            n.innerHTML = e;

            return n;
        }
        public static void RenderProxyTo(ProxyProvider r, IHTMLElement Target)
        {
            Func<Color, Action<string>> ToColorWrite =
                color =>
                    text =>
                    {
                        var s = new IHTMLSpan { innerText = text };

                        s.style.color = color;
                        s.AttachTo(Target);
                    };

            Action<string> Write = text => new IHTMLSpan(text).AttachTo(Target);

            ProxyConverter.RenderProxyTo(r, ToColorWrite, Write, null);
        }
		private void Start1()
		{

			//concept.AttachToDocument();

			var Title = new IHTMLDiv
			{

			};

			new Browsers
			{
			}.Container.AttachTo(Title);

			new HTML.Images.FromBase64.twitter_small().AttachToDocument();
			new HTML.Images.FromAssets.twitter_small().AttachToDocument();




			var TitleLogo = new IHTMLImage("assets/ScriptCoreLib/jsc.png");
			var TitleText = new IHTMLSpan("UltraApplication");
			TitleText.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
			TitleText.style.paddingLeft = "2em";
			TitleText.style.fontSize = "xx-large";
			TitleLogo.style.verticalAlign = "middle";


			Title.appendChild(TitleLogo);
			Title.appendChild(TitleText);

			Title.style.height = "128px";

			Title.AttachToDocument();
			Title.FadeIn(2500, 1000,
				delegate
				{
					1500.AtDelay(
						delegate
						{
							ContinueBuildingApplication();
						}
					);
				}
			);
		}
        private static void DoVideo(string video)
        {
            var uri = video.ToYoutubeVideo();

            var di = new IHTMLDiv
			{
				new IHTMLAnchor { href = uri.ToString(), innerText = video }
			}.AttachToDocument();

            video.ToCaptionTuples(
                x =>
                {
                    var text = new IHTMLSpan(x.Text);

                    var n = new IHTMLDiv
					{

						text

					}.AttachTo(di);

                    var colors = @"red,blue,green,yellow".Split(',');

                    var c = Enumerable.FirstOrDefault(
                        from k in colors
                        where (" " + x.Text + " ").Contains(" " + k + " ")
                        select k
                    );

                    if (c != null)
                        text.style.backgroundColor = c;

                    if (x.Text.Contains("step"))
                    {
                        n.style.fontSize = "large";
                        n.style.color = "blue";
                        n.style.textDecoration = "underline";
                    }


                    n.title = x.Start + " (" + x.Duration + ")";
                    text.style.marginLeft = x.Start + "px";
                }
            );
        }
        public MatrixTransformBExample()
        {
            var x = 400;
            var y = 200;
            var w = 200;
            var h = 200;

            var ro_matrix = new IHTMLDiv();

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

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


            var r_matrix = new IHTMLDiv();

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

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

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


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

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

            jo.AttachToDocument();

            var joh = new IHTMLDiv();

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

            joh.AttachToDocument();

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

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

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

            zo.AttachToDocument();

            var zoh = new IHTMLDiv();

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

            zoh.AttachToDocument();
            #endregion




            var ro = new IHTMLDiv();

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



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


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

            info.AttachToDocument();

            var at = new IHTMLDiv();

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



            var r = new IHTMLDiv();

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

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

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

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

            o.AttachToDocument();

            var oh = new IHTMLDiv();

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

            oh.AttachToDocument();
            #endregion



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

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

            jzo.AttachToDocument();

            var jzoh = new IHTMLDiv();

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

            jzoh.AttachToDocument();


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


            var m = new MatrixModifiers();

            var InteractiveSetOrigin_x = 0;
            var InteractiveSetOrigin_y = 0;

            var InteractiveSetRotation_x = 0;
            var InteractiveSetRotation_y = 0;


            Action<int, int> InteractiveSetRotation = null;

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

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

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

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

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



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

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

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

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

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

                        return;
                    }

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

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

                    InteractiveSetOrigin_x = ox;
                    InteractiveSetOrigin_y = oy;

                    SetPadding(ox, oy);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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



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

                };



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

                    InteractiveSetRotation(e.OffsetX, e.OffsetY);

                };

            at.onmousemove +=
                e =>
                {

                    InteractiveSetRotation(e.OffsetX, e.OffsetY);

                };

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

            InteractiveSetRotation(0, 0);
            #endregion

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

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

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

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


            #endregion

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

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

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

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

            f.GetHTMLTarget().AttachToDocument();
        }
        private static void RenderAnyTo(ReflectionProvider r, IHTMLElement pre)
        {
            Func<bool> DelegatesParams = () => false;
            Func<bool> IsInterface = () => r.IsInterface;
            Func<bool> IsField = () => false;

            IHTMLElement Target = pre;

            Func<Color, Action<string>> ToColorWrite =
                color =>
                    text =>
                    {
                        var s = new IHTMLSpan { innerText = text };

                        s.style.color = color;
                        s.AttachTo(Target);
                    };

            Func<string, IHTMLSpan> Write = text => new IHTMLSpan(text).AttachTo(Target);

            Action WriteLine = () => Write("\r\n");
            Action WriteSpace = () => Write(" ");

            #region Write<Color>
            Action<string> WriteBlue = ToColorWrite(Color.Blue);
            Action<string> WriteBlack = ToColorWrite(Color.Black);
            Action<string> WriteGray = ToColorWrite(Color.FromRGB(0x80, 0x80, 0x80));
            Action<string> WriteCyan = ToColorWrite(Color.FromRGB(0, 0x80, 0x80));
            Action<string> WriteGreen = ToColorWrite(Color.FromRGB(0, 0x80, 0));
            #endregion

            int Indent = 1;

            Action WriteIdent = () => Write(new string(' ', 4 * Indent));


            #region Region
            Func<string, IDisposable> Region =
                text =>
                {
                    WriteIdent();
                    WriteBlue("#region");
                    WriteSpace();
                    var Collapsible = Write(text);
                    WriteLine();

                    var PreviousTarget = Target;
                    var CurrentTarget = new IHTMLElement(IHTMLElement.HTMLElementEnum.pre).AttachTo(PreviousTarget); ;

                    Collapsible.style.cursor = IStyle.CursorEnum.pointer;
                    Collapsible.onclick +=
                        delegate
                        {
                            CurrentTarget.ToggleVisible();
                        };

                    Target = CurrentTarget;

                    return new Disposable(
                        delegate
                        {


                            WriteIdent();
                            WriteBlue("#endregion");
                            WriteLine();

                            Target = PreviousTarget;
                        }
                    );
                };
            #endregion


            Func<IDisposable> CodeBlock =
                delegate
                {
                    WriteIdent();
                    Write("{");
                    WriteLine();

                    Indent++;

                    return new Disposable(
                        delegate
                        {
                            Indent--;

                            WriteIdent();
                            Write("}");
                            WriteLine();
                        }
                    );
                };

            Action<string> WriteSummary =
                text =>
                {
                    WriteIdent();
                    WriteGray("/// <summary>");
                    WriteLine();

                    WriteIdent();
                    WriteGray("/// ");
                    WriteGreen(text);
                    WriteLine();

                    WriteIdent();
                    WriteGray("/// </summary>");
                    WriteLine();
                };

            Action<string> WriteTypeName =
                text =>
                {
                    var z = FixTypeName(text.Trim());

                    if (CSharpKeywords.Contains(z))
                        WriteBlue(z);
                    else
                        WriteCyan(z);
                };

            Action<string, string> WriteVariableDefinition =
                (TypeName, VariableName) =>
                {
                    WriteTypeName(TypeName);
                    WriteSpace();
                    Write(FixVariableName(VariableName));
                };

            WriteIdent();
            WriteBlue("namespace");
            WriteSpace();
            Write(r.PackageName);
            WriteLine();

            using (CodeBlock())
            {
                WriteIdent();
                Write("[");
                WriteCyan("Script");
                Write("(");
                Write("IsNative = ");
                WriteBlue("true");
                Write(")");
                Write("]");
                WriteLine();

                WriteIdent();

                WriteBlue("public");
                WriteSpace();

                if (r.IsSealed)
                {
                    WriteBlue("sealed");
                    WriteSpace();
                }

                if (r.IsInterface)
                {
                    WriteBlue("interface");
                }
                else
                {
                    WriteBlue("class");
                }
                WriteSpace();
                WriteCyan(r.TypeName);
                WriteLine();

                using (CodeBlock())
                {
                    #region Constants
                    if (r.Constants.Count > 0)
                        using (Region("Constants"))
                            foreach (var p in r.Constants)
                            {

                                WriteSummary(p.Summary);

                                WriteIdent();

                                if (string.IsNullOrEmpty(p.Value) && p.IsAirOnly)
                                {
                                    WriteGreen("// " + p.Name + " constant was ommited due to no given value");
                                    WriteLine();
                                    continue;
                                }

                                if (p.Value == "\"?\"")
                                {
                                    WriteGreen("// " + p.Name + " constant was ommited due to no string given value");
                                    WriteLine();
                                    continue;
                                }


                                WriteBlue("public");
                                WriteSpace();

                                if (p.IsAirOnly)
                                {
                                    WriteBlue("const");
                                    WriteSpace();
                                }
                                else
                                {
                                    WriteBlue("static");
                                    WriteSpace();
                                    WriteBlue("readonly");
                                    WriteSpace();
                                }

                                WriteVariableDefinition(p.Type, p.Name);

                                if (!string.IsNullOrEmpty(p.Value))
                                {
                                    WriteSpace();
                                    Write("=");
                                    WriteSpace();
                                    Write(p.Value);
                                }

                                Write(";");

                                WriteLine();
                                WriteLine();
                            }
                    #endregion


                    #region Properties
                    using (Region("Properties"))
                        foreach (var p in r.Properties)
                        {
                            if (p.IsInherited)
                                continue;

                            WriteSummary(p.Summary);

                            WriteIdent();

                            if (IsInterface())
                            {
                            }
                            else
                            {
                                WriteBlue("public");
                                WriteSpace();

                                if (p.IsStatic)
                                {
                                    WriteBlue("static");
                                    WriteSpace();
                                }
                            }

                            WriteVariableDefinition(p.PropertyType, p.PropertyName);

                            if (IsField())
                                Write(";");
                            else
                            {
                                WriteSpace();
                                Write("{");
                                WriteSpace();
                                WriteBlue("get");
                                Write(";");
                                WriteSpace();


                                if (IsInterface())
                                {
                                    if (p.IsReadOnly)
                                    {

                                    }
                                    else
                                    {
                                        WriteBlue("set");
                                        Write(";");
                                    }
                                }
                                else
                                {
                                    if (p.IsReadOnly)
                                    {

                                        WriteBlue("private");
                                    }

                                    WriteBlue("set");
                                    Write(";");
                                  
                                }

                                WriteSpace();
                                Write("}");
                            }


                            WriteLine();
                            WriteLine();
                        }
                    #endregion

                    #region Constructors
                    if (r.GetInstanceConstructors().Count() > 0)
                        using (Region("Constructors"))
                            foreach (var p in r.GetInstanceConstructors())
                                foreach (var v in p.ParametersInfo.Variations)
                                {
                                    WriteSummary(p.Summary);

                                    WriteIdent();

                                    WriteBlue("public");
                                    WriteSpace();

                                    Write(p.Name);
                                    Write("(");

                                    for (int k = 0; k < v.Parameters.Length; k++)
                                    {
                                        if (k > 0)
                                        {
                                            Write(",");
                                            WriteSpace();
                                        }

                                        WriteVariableDefinition(v.Parameters[k].TypeName, v.Parameters[k].Name);
                                    }

                                    Write(")");

                                    if (DelegatesParams())
                                    {
                                        WriteSpace();
                                        Write(":");
                                        WriteSpace();
                                        WriteBlue("base");
                                        Write("(" + v.NamesToString() + ")");
                                    }


                                    WriteLine();


                                    using (CodeBlock()) { }

                                    WriteLine();
                                }
                    #endregion

                    #region Methods
                    using (Region("Methods"))
                        foreach (var p in r.GetInstanceMethods())
                            foreach (var v in p.ParametersInfo.Variations)
                            {
                                WriteSummary(p.Summary);

                                WriteIdent();

                                if (IsInterface())
                                {

                                }
                                else
                                {
                                    WriteBlue("public");
                                    WriteSpace();

                                    if (p.IsStatic)
                                    {
                                        WriteBlue("static");
                                        WriteSpace();
                                    }
                                }


                                WriteVariableDefinition(p.ReturnType, p.Name);

                                Write("(");

                                for (int k = 0; k < v.Parameters.Length; k++)
                                {
                                    if (k > 0)
                                    {
                                        Write(",");
                                        WriteSpace();
                                    }

                                    WriteVariableDefinition(v.Parameters[k].TypeName, v.Parameters[k].Name);
                                }

                                Write(")");

                                if (IsInterface())
                                {
                                    Write(";");
                                    WriteLine();
                                }
                                else
                                {

                                    WriteLine();

                                    using (CodeBlock())
                                    {
                                        if (!p.ReturnTypeVoid)
                                        {
                                            WriteIdent();
                                            WriteBlue("return");
                                            WriteSpace();
                                            WriteBlue("default");
                                            Write("(");
                                            WriteTypeName(p.ReturnType);
                                            Write(")");
                                            Write(";");
                                            WriteLine();
                                        }
                                    }
                                }

                                WriteLine();
                            }
                    #endregion

                }
            }

        }
        public StudioView(Action<IHTMLElement, Action<ISaveAction>> AddSaveButton = null)
        {
            Content.style.position = IStyle.PositionEnum.absolute;
            Content.style.left = "0px";
            Content.style.right = "0px";
            Content.style.top = "0px";
            Content.style.bottom = "0px";

            new TwentyTenWorkspace().ToBackground(Content.style, true);

            var WorkspaceHeaderTab0 = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.top = "0px";
                    div.style.left = "0px";
                    div.style.width = "14em";
                    div.style.height = "6em";

                    div.style.padding = "0.5em";

                    new Glow1().ToBackground(div.style, false);
                }
            ).AttachTo(Content);

            var WorkspaceHeaderTab1 = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.top = "0px";
                    div.style.left = "14em";
                    div.style.width = "20em";
                    div.style.height = "6em";

                    div.style.padding = "0.5em";

                    new Glow1().ToBackground(div.style, false);
                }
            ).AttachTo(Content);

            var WorkspaceHeaderTab2 = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.top = "0px";
                    div.style.left = "34em";
                    div.style.right = "6em";
                    div.style.height = "6em";

                    div.style.padding = "0.5em";

                    new Glow1().ToBackground(div.style, false);
                }
            ).AttachTo(Content);

            var WorkspaceHeaderTab7 = new IHTMLDiv().With(
                 div =>
                 {
                     div.style.position = IStyle.PositionEnum.absolute;
                     div.style.top = "0px";
                     div.style.width = "6em";
                     div.style.right = "0px";
                     div.style.height = "6em";

                     //div.style.padding = "0.5em";

                     new Glow1().ToBackground(div.style, false);
                 }
             ).AttachTo(Content);

            var WorkspaceHeaderTab0Text = default(IHTMLSpan);



            new DownloadSDK
            {

            }.AttachTo(
                 new IHTMLAnchor
                 {
                     title = "Download JSC SDK!",
                     href = "http://download.jsc-solutions.net"
                 }.AttachTo(WorkspaceHeaderTab7)
            );

            @"studio.jsc-solutions.net".ToDocumentTitle().With(
                title =>
                {
                    WorkspaceHeaderTab0Text = new IHTMLSpan { innerText = title };

                    WorkspaceHeaderTab0Text.AttachTo(WorkspaceHeaderTab0);
                    //WorkspaceHeaderTab0Text.style.SetLocation(16, 8);
                    WorkspaceHeaderTab0Text.style.fontFamily = IStyle.FontFamilyEnum.Tahoma;
                    WorkspaceHeaderTab0Text.style.color = Color.White;
                    WorkspaceHeaderTab0Text.style.display = IStyle.DisplayEnum.block;

                    // http://www.quirksmode.org/css/textshadow.html
                    WorkspaceHeaderTab0Text.style.textShadow = "#808080 4px 2px 2px";

                }
            );


            if (AddSaveButton != null)
                AddSaveButton(WorkspaceHeaderTab0Text, i => Save = i);

            // em + px :)
            var Workspace0 = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.left = "0px";
                    div.style.right = "0px";
                    div.style.bottom = "0px";
                    div.style.top = "6em";
                }
            ).AttachTo(Content);

            // workspace contains the split views
            var Workspace = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.left = "6px";
                    div.style.right = "6px";
                    div.style.bottom = "6px";
                    div.style.top = "6px";
                }
            ).AttachTo(Workspace0);

            // in this project we wont be having toolbox or toolbar yet

            Action<HorizontalSplit> ApplyStyle =
                t =>
                {
                    t.Split.Splitter.style.backgroundColor = Color.None;
                    t.SplitImageContainer.Orphanize();
                    t.SplitArea.Target.style.borderLeft = "0";
                    t.SplitArea.Target.style.borderRight = "0";
                    t.SplitArea.Target.style.width = "6px";
                    t.SplitArea.Target.style.Opacity = 0.7;

                    // should we obselete JSColor already?
                    t.SelectionColor = JSColor.Black;
                };

            var EditorTreeSplit = new HorizontalSplit
            {
                Minimum = 0,
                Maximum = 1,
                Value = 0.7,
            };

            EditorTreeSplit.With(ApplyStyle);

            EditorTreeSplit.Split.Splitter.style.backgroundColor = Color.None;


            EditorTreeSplit.Container.AttachTo(Workspace);



            var Split = new HorizontalSplit
            {
                Minimum = 0,
                Maximum = 1,
                Value = 0.3,
            };

            Split.With(ApplyStyle);

            Split.Split.Splitter.style.backgroundColor = Color.None;

            EditorTreeSplit.LeftContainer = Split.Container;



            var SolutionToolbox = new SolutionDockWindowPage();

            SolutionToolbox.HeaderText.innerText = "Toolbox";
            SolutionToolbox.Content.style.backgroundColor = Color.White;
            SolutionToolbox.Content.style.padding = "2px";
            SolutionToolbox.Content.style.overflow = IStyle.OverflowEnum.auto;
            SolutionToolbox.Content.Clear();


            var vv = new SolutionToolboxListView();

            vv.Container.style.color = Color.Black;
            //vv.Container.AttachTo(SolutionToolbox.Content);

            var items = new StockToolboxTabsForHTMLDocument();

            // jsc market components

            vv.Add(
             new SolutionToolboxListViewTab
             {
                 DataType = "DataTable",

                 Name = "DataTable",
                 Title = "DataTable",
                 Text = "DataTable",
                 Icon = new DataTableImage()
             }
          );

            vv.Add(
                new SolutionToolboxListViewTab
                {
                    DataType = "SpiralDataType",

                    Name = "Spiral1",
                    Title = "Spiral",
                    Text = "Spiral",
                    Icon = new Spiral()
                }
             );

            // can we drag this into 
            // code ?
            // msvs gets the image link
            //http://192.168.43.252:11924/assets/ScriptCoreLib.Ultra.Components/StockToolboxImageTransparent64.png?data-jsc-type=DAETruck
            vv.Add(
                  new SolutionToolboxListViewTab
                  {
                      DataType = "DAETruck",

                      Name = "DAETruck",
                      Title = "DAETruck",
                      Text = "DAETruck",
                      Icon = new DAETruck()
                  }
               );

            vv.Add(
                new SolutionToolboxListViewTab
                {
                    DataType = "WebGLEarthByBjorn",

                    Name = "WebGLEarthByBjorn",
                    Title = "WebGLEarthByBjorn",
                    Text = "WebGLEarthByBjorn",
                    Icon = new WebGLEarthByBjorn()
                }
                );


            items.WithEach(vv.Add);




            var Viewer = new SolutionDocumentViewer();
            SolutionDocumentViewerTab File7Tab = "Design/App.htm";
            Viewer.Add(File7Tab);

            #region OutputFile
            var OutputFile = new SolutionFile();
            var OutputFileViewer = new SolutionFileView();

            // fullscreen! :)
            OutputFileViewer.Container.style.height = "100%";

            OutputFile.IndentStack.Push(
                delegate
                {
                    OutputFile.Write(SolutionFileTextFragment.Comment, "" + DateTime.Now);
                    OutputFile.WriteSpace();
                }
            );

            Action<string> OutputWriteLine =
                n =>
                {
                    // Would we want to rewire System.Out? Console.WriteLine?
                    OutputFile.WriteIndent();
                    OutputFile.WriteLine(n);

                    // we could have a resume feature? now we just go and clear...
                    OutputFileViewer.File = OutputFile;
                };


            OutputWriteLine("studio.jsc-solutions.net ready!");
            #endregion

            SolutionDocumentViewerTab OutputTab = "Output";
            Viewer.Add(OutputTab);
            OutputTab.TabElement.style.Float = IStyle.FloatEnum.right;


            SolutionDocumentViewerTab AboutTab = "Project";
            Viewer.Add(AboutTab);
            AboutTab.TabElement.style.Float = IStyle.FloatEnum.right;


            var CurrentDesigner = new SolutionFileDesigner();




            var HTMLDesigner = new SolutionFileDesignerHTMLElementTabs();

            CurrentDesigner.Add(HTMLDesigner);


            // undoable?
            var sln = new SolutionBuilder();




            #region CodeSourceA
            var CodeSourceATab =
                new SolutionFileDesignerTab
                {
                    Image = new RTA_mode_html(),
                    Text = "Generated Code"
                };

            var CodeSourceAView = new SolutionFileView();

            CodeSourceAView.Container.style.position = IStyle.PositionEnum.absolute;
            CodeSourceAView.Container.style.left = "0px";
            CodeSourceAView.Container.style.right = "0px";
            CodeSourceAView.Container.style.top = "0px";
            CodeSourceAView.Container.style.bottom = "0px";

            CodeSourceAView.Container.style.display = IStyle.DisplayEnum.none;
            CodeSourceAView.Container.AttachTo(CurrentDesigner.Content);

            CodeSourceATab.Deactivated +=
                delegate
                {
                    CodeSourceAView.Container.style.display = IStyle.DisplayEnum.none;
                };

            CodeSourceATab.Activated +=
                delegate
                {
                    HTMLDesigner.HTMLDesignerContent.WhenContentReady(
                        body =>
                        {
                            var CodeSourceFile = new SolutionFile
                            {

                                Name = "Default.htm"
                            };

                            var Type = new SolutionProjectLanguageType
                            {
                                Comments = new SolutionFileComment[] { "This type was generated from the HTML file." },
                                Namespace = sln.Name + ".HTML.Pages",
                                Name = "IDefaultPage",
                                IsInterface = true,
                            };

                            (from n in body.AsXElement().DescendantsAndSelf()
                             let id = n.Attribute("id")
                             where id != null
                             select new { n, id }
                            ).WithEach(
                                k =>
                                {
                                    Type.Properties.Add(
                                        new KnownStockTypes.ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement().ToAutoProperty(k.id.Value)
                                    );
                                }
                            );

                            sln.Language.WriteType(CodeSourceFile, Type, null);

                            CodeSourceAView.File = CodeSourceFile;

                            CodeSourceAView.Container.style.display = IStyle.DisplayEnum.empty;
                        }
                    );
                };


            #endregion


            #region CodeSourceB
            var CodeSourceBTab =
                new SolutionFileDesignerTab
                {
                    Image = new RTA_mode_html(),
                    // all source code, not just html?
                    Text = "Source"
                };

            var CodeSourceBView = new SolutionFileView();

            CodeSourceBView.Container.style.position = IStyle.PositionEnum.absolute;
            CodeSourceBView.Container.style.left = "0px";
            CodeSourceBView.Container.style.right = "0px";
            CodeSourceBView.Container.style.top = "0px";
            CodeSourceBView.Container.style.bottom = "0px";

            CodeSourceBView.Container.style.display = IStyle.DisplayEnum.none;
            CodeSourceBView.Container.AttachTo(CurrentDesigner.Content);

            CodeSourceBTab.Deactivated +=
                delegate
                {
                    CodeSourceBView.Container.style.display = IStyle.DisplayEnum.none;
                };

            CodeSourceBTab.Activated +=
                delegate
                {

                    CodeSourceBView.Container.style.display = IStyle.DisplayEnum.empty;
                };


            #endregion

            #region CodeSourceFormsDesignerTab
            var CodeSourceFormsDesignerTab =
                new SolutionFileDesignerTab
                {
                    Image = new RTA_mode_design(),
                    // all source code, not just html?
                    Text = "Designer"
                };


            var CodeSourceFormsDesignerTabView = new SolutionFileView();

            CodeSourceFormsDesignerTabView.Container.style.With(
                style =>
                {
                    style.position = IStyle.PositionEnum.absolute;
                    style.left = "0px";
                    style.right = "0px";
                    style.top = "0px";
                    style.bottom = "0px";

                    style.display = IStyle.DisplayEnum.none;
                }
            );

            new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.left = "16px";
                    div.style.top = "16px";
                    div.style.width = "400px";
                    div.style.height = "300px";
                    div.style.backgroundColor = Color.FromGray(0xe0);
                    div.style.border = "1px solid gray";
                    div.AttachTo(CodeSourceFormsDesignerTabView.Container);
                }
            );


            CodeSourceFormsDesignerTabView.Container.AttachTo(CurrentDesigner.Content);

            CodeSourceFormsDesignerTab.Deactivated +=
                delegate
                {
                    CodeSourceFormsDesignerTabView.Container.style.display = IStyle.DisplayEnum.none;
                };

            CodeSourceFormsDesignerTab.Activated +=
                delegate
                {

                    CodeSourceFormsDesignerTabView.Container.style.display = IStyle.DisplayEnum.empty;
                };


            #endregion

            CurrentDesigner.Add(CodeSourceFormsDesignerTab);
            CurrentDesigner.Add(CodeSourceBTab);
            CurrentDesigner.Add(CodeSourceATab);




            var wLeftScrollable = new System.Windows.Forms.Form
            {
                BackColor = global::System.Drawing.Color.White,
                Text = "Toolbox",
                ControlBox = false,
                ShowIcon = false,
                AutoScroll = true
            };

            vv.Container.AttachTo(
                wLeftScrollable.GetHTMLTargetContainer()
            );

            //wLeftScrollable.Show();

            Split.Split.LeftScrollable.style.zIndex = 0;
            wLeftScrollable.AttachFormTo(Split.Split.LeftScrollable);


            //wLeftScrollable.PopupInsteadOfClosing();

            //Split.Split.LeftScrollable = (IHTMLDiv)(object)SolutionToolbox.body;
            Split.Split.RightScrollable = Viewer.Container;

            // ...





            #region dynamic content
            Func<IEnumerable<XElement>> GetPages = delegate
            {
                return from n in sln.ApplicationPage.DescendantsAndSelf()
                       let type = n.Attribute(SolutionBuilderInteractive.DataTypeAttribute)
                       where type != null
                       let id = n.Attribute("id")
                       where id != null
                       select n;
            };

            sln.Interactive.GenerateApplicationExpressions +=
                Add =>
                {


                    // page.PageContainer.ReplaceWith(
                    GetPages().WithEach(
                        k =>
                        {
                            var id = k.Attribute("id").Value;

                            if (id == "Page1")
                            {
                                Add(
                                    new StockReplaceWithNewPageExpression(id)
                                );
                            }

                            if (id == "UserControl1")
                            {
                                Add(
                                    new StockReplaceWithNewUserControlExpression(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "Applet1")
                            {
                                Add(
                                    new StockReplaceWithNewAppletExpression(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "Sprite1")
                            {
                                Add(
                                    new StockReplaceWithNewSpriteExpression(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "AppletUserControl1")
                            {
                                Add(
                                    new StockReplaceWithNewAppletExpression(sln.Name + ".Components", id)
                                );
                            }
                        }
                    );
                };

            sln.Interactive.GenerateHTMLFiles +=
                Add =>
                {

                    GetPages().WithEach(
                        k =>
                        {
                            var id = k.Attribute("id").Value;

                            if (id == "Page1")
                            {
                                var __Content = new XElement(StockPageDefault.Page);


                                __Content.Element("head").Element("title").Value = id;

                                Add(
                                    new SolutionProjectHTMLFile
                                    {
                                        Name = "Design/" + id + ".htm",
                                        Content = __Content
                                    }
                                );
                            }
                        }
                     );
                };

            sln.Interactive.GenerateTypes +=
                Add =>
                {
                    GetPages().WithEach(
                        k =>
                        {
                            var id = k.Attribute("id").Value;

                            if (id == "UserControl1")
                            {
                                Add(
                                    new StockUserControlType(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "Applet1")
                            {
                                Add(
                                    new StockAppletType(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "Sprite1")
                            {
                                Add(
                                    new StockSpriteType(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "AppletUserControl1")
                            {
                                var UserControl2 = new StockUserControlType(sln.Name + ".Components", "UserControl2");

                                Add(
                                    UserControl2
                                );

                                Add(
                                    new StockUserControlAppletType(sln.Name + ".Components", id, UserControl2)
                                );
                            }
                        }
                     );
                };
            #endregion


            var _Solution = new TreeNode(VistaTreeNodePage.Create);


            var _Project = _Solution.Add();

            var About = new About();

            #region UpdateFile1Text
            Action UpdateFile1Text =
                delegate
                {

                    if (CodeSourceBView.File != null)
                    {
                        File7Tab.Text = CodeSourceBView.File.Name.SkipUntilLastIfAny("/");
                    }
                    else
                    {
                        File7Tab.Text = sln.Name;
                    }


                };
            #endregion



            #region Update
            Action Update =
                delegate
                {
                    sln.Name = About.ProjectName.value;

                    UpdateFile1Text();

                    _Project.Clear();
                    UpdateTree(sln, CodeSourceBView, _Solution, _Project);
                };
            #endregion


            var PreviousVersion = default(string);

            #region HTMLDesigner.HTMLDesignerContent
            HTMLDesigner.HTMLDesignerContent.WhenContentReady(
                body =>
                {
                    if (PreviousVersion == null)
                    {
                        var x = new XElement(body.AsXElement());
                        var y = x.ToString();
                        PreviousVersion = y;
                    }

                    Action<bool> HTMLDesignerContentCheck =
                        DoUpdate =>
                        {
                            var x = new XElement(body.AsXElement());
                            var y = x.ToString();

                            if (PreviousVersion != y)
                            {
                                PreviousVersion = y;


                                sln.ApplicationPage = x;

                                // allow any blur causing action to complete first
                                // we get reselected for some odd reason, why?
                                new Timer(
                                    delegate
                                    {
                                        if (DoUpdate)
                                        {
                                            OutputWriteLine("Designer has caused an update.");
                                            Update();
                                        }
                                        else
                                        {
                                            OutputWriteLine("Designer will cause an update.");
                                        }

                                    }
                                ).StartTimeout(700);
                            }
                        };

                    var HTMLDesignerContentDirty = new Timer(
                        delegate
                        {
                            HTMLDesignerContentCheck(false);
                        }
                    );

                    HTMLDesigner.HTMLDesignerContent.contentWindow.onfocus +=
                        delegate
                        {
                            OutputWriteLine("Designer activated.");
                            //"focus".ToDocumentTitle();

                            //HTMLDesignerContentDirty.StartInterval(700);
                        };

                    HTMLDesigner.HTMLDesignerContent.contentWindow.onblur +=
                        delegate
                        {
                            //HTMLDesignerContentDirty.Stop();

                            OutputWriteLine("Designer deactivated.");
                            //"blur".ToDocumentTitle();
                            HTMLDesignerContentCheck(true);

                        };
                }
            );
            #endregion

            #region CodeSourceBView.FileChanged
            CodeSourceBView.FileChanged +=
                delegate
                {
                    UpdateFile1Text();


                    OutputWriteLine("Select: " + CodeSourceBView.File.Name);

                    CodeSourceFormsDesignerTab.TabElement.Hide();

                    // hack :)
                    if (CodeSourceBView.File.Name.EndsWith("/App.htm"))
                    {
                        // currently we only have one element :)

                        HTMLDesigner.HTMLDesignerTab.RaiseActivated();

                        HTMLDesigner.HTMLDesignerTab.TabElement.style.display = IStyle.DisplayEnum.inline_block;
                        HTMLDesigner.HTMLSourceTab.TabElement.style.display = IStyle.DisplayEnum.none;
                        CodeSourceATab.TabElement.style.display = IStyle.DisplayEnum.inline_block;
                        CodeSourceBTab.TabElement.style.display = IStyle.DisplayEnum.inline_block;

                        HTMLDesigner.HTMLDesignerContent.WhenContentReady(
                            body =>
                            {
                                HTMLDesigner.HTMLDesignerContent.contentWindow.focus();
                            }
                        );

                        // show the design/source buttons
                    }
                    else if (CodeSourceBView.File.Name.EndsWith(".sln"))
                    {
                        AboutTab.Activate();
                    }
                    else if (CodeSourceBView.File.Name.EndsWith(sln.Language.ProjectFileExtension))
                    {
                        AboutTab.Activate();
                    }
                    else if (CodeSourceBView.File.Name.EndsWith(sln.Language.CodeFileExtension))
                    {
                        // show type outline / member
                        CodeSourceBTab.RaiseActivated();

                        HTMLDesigner.HTMLDesignerTab.TabElement.style.display = IStyle.DisplayEnum.none;
                        HTMLDesigner.HTMLSourceTab.TabElement.style.display = IStyle.DisplayEnum.none;
                        CodeSourceATab.TabElement.style.display = IStyle.DisplayEnum.none;
                        CodeSourceBTab.TabElement.style.display = IStyle.DisplayEnum.inline_block;

                        CodeSourceBView.File.ContextType.BaseType.With(
                            BaseType =>
                            {
                                if (BaseType is KnownStockTypes.System.Windows.Forms.UserControl)
                                {
                                    CodeSourceFormsDesignerTab.TabElement.Show();
                                    CodeSourceFormsDesignerTab.RaiseActivated();

                                }

                                if (BaseType is KnownStockTypes.System.ComponentModel.Component)
                                {
                                    CodeSourceFormsDesignerTab.TabElement.Show();
                                    CodeSourceFormsDesignerTab.RaiseActivated();

                                }
                            }
                        );

                    }


                };
            #endregion


            //AddSaveButton(WorkspaceHeader, i => Save = i);

            About.ProjectName.value = sln.Name;
            About.ProjectName.onchange +=
                delegate
                {
                    OutputWriteLine("Project name has changed.");
                    Update();
                };



            Viewer.Content.Clear();
            Viewer.Content.Add(About.Container);
            Viewer.Content.Add(CurrentDesigner.Container);
            Viewer.Content.Add(OutputFileViewer.Container);

            AboutTab.WhenActivated(About.Container);
            File7Tab.WhenActivated(CurrentDesigner.Container);
            OutputTab.WhenActivated(OutputFileViewer.Container);



            Viewer.First().Activate();

            //var SolutionExplorer = new SolutionDockWindowPage();

            //SolutionExplorer.HeaderText.innerText = "Solution Explorer";
            //SolutionExplorer.Content.style.backgroundColor = Color.White;
            //SolutionExplorer.Content.style.padding = "2px";
            //SolutionExplorer.Content.ReplaceContentWith(_Solution.Container);


            var fSolutionExplorer = new System.Windows.Forms.Form
            {
                BackColor = global::System.Drawing.Color.White,
                Text = "Solution Explorer",
                ControlBox = false,
                ShowIcon = false

            };

            EditorTreeSplit.Split.RightScrollable.style.zIndex = 0;
            EditorTreeSplit.Split.RightScrollable.style.position = IStyle.PositionEnum.relative;

            fSolutionExplorer.AttachFormTo(EditorTreeSplit.Split.RightScrollable);

            _Solution.Container.AttachTo(fSolutionExplorer.GetHTMLTargetContainer());

            _Solution.Container.style.overflow = IStyle.OverflowEnum.auto;
            _Solution.Container.style.height = "100%";
            _Solution.Container.style.backgroundColor = Color.White;

            //EditorTreeSplit.Split.RightContainer = (IHTMLDiv)(object)SolutionExplorer.Container;

            EditorTreeSplit.Container.AttachTo(Workspace);

            //CurrentDesigner.First().RaiseActivated();

            Update();

            #region CreateLanguageButton
            Action<IHTMLImage, string, SolutionProjectLanguage, string> CreateLanguageButton =
                (Icon, Text, Language, Name) =>
                {
                    var span = new IHTMLSpan(Text);

                    span.style.marginLeft = "0.7em";
                    span.style.marginRight = "0.7em";

                    new IHTMLButton { Icon /*, span */ }.AttachTo(WorkspaceHeaderTab1).With(
                        btn =>
                        {
                            btn.onclick +=
                                delegate
                                {
                                    sln.Language = Language;
                                    sln.Name = Language.LanguageSpelledName.Replace(" ", "") + "Project1";
                                    Update();
                                };

                            //btn.style.display = IStyle.DisplayEnum.block;
                        }
                    );
                };
            #endregion


            CreateLanguageButton(new VisualCSharpProject(), "C#", KnownLanguages.VisualCSharp, "VisualCSharpProject1");
            CreateLanguageButton(new VisualFSharpProject(), "F#", KnownLanguages.VisualFSharp, "VisualFSharpProject1");
            CreateLanguageButton(new VisualBasicProject(), "Visual Basic", KnownLanguages.VisualBasic, "VisualBasicProject1");

            var ListOfCreateProjectTypeButton = new List<IHTMLButton>();

            #region CreateProjectTypeButton
            Action<string, Action> CreateProjectTypeButton =
              (Text, Handler) =>
              {
                  var span = new IHTMLSpan(Text);

                  span.style.marginLeft = "0.7em";
                  span.style.marginRight = "0.7em";

                  new IHTMLButton { span }.AttachTo(WorkspaceHeaderTab2).With(
                      btn =>
                      {
                          ListOfCreateProjectTypeButton.Add(btn);

                          btn.onclick +=
                              delegate
                              {
                                  ListOfCreateProjectTypeButton.WithEach(n => n.disabled = true);

                                  Handler();
                              };

                          //btn.style.display = IStyle.DisplayEnum.block;
                      }
                  );
              };
            #endregion

            #region ToSpecificProjectType
            Action<string, Action> ToSpecificProjectType =
                (Text, Handler) =>
                {
                    CreateProjectTypeButton(Text,
                        delegate
                        {
                            Handler();


                            HTMLDesigner.HTMLDesignerContent.WhenDocumentReady(
                                document =>
                                {
                                    document.WithContent(sln.ApplicationPage);
                                    // we should now also lock the designer!
                                    document.DesignMode = false;
                                }
                            );

                            Update();
                        }
                    );
                };
            #endregion

            #region Avalon, Forms
            ToSpecificProjectType("Avalon App",
                delegate
                {
                    sln.WithCanvas();
                }
            );


            ToSpecificProjectType("Avalon Flash App",
               delegate
               {
                   sln.WithCanvasAdobeFlash();

               }
            );

            ToSpecificProjectType("Forms App",
                delegate
                {
                    sln.WithForms();
                }
            );


            ToSpecificProjectType("Forms Applet App",
               delegate
               {
                   sln.WithFormsApplet();

               }
            );
            #endregion

            ToSpecificProjectType("Flash App",
              delegate
              {
                  sln.WithAdobeFlash();
              }
            );

            ToSpecificProjectType("Flash Camera App",
                delegate
                {
                    sln.WithAdobeFlashCamera();
                }
              );

            ToSpecificProjectType("Flash Flare3D App",
               delegate
               {
                   sln.WithAdobeFlashWithFlare3D();
               }
             );

            ToSpecificProjectType("Applet App",
              delegate
              {
                  sln.WithJavaApplet();
              }
            );
        }
        public static void GenerateView(string[] lines)
        {
            string Status = "";

            var c = new IHTMLElement(IHTMLElement.HTMLElementEnum.center, "");
            var cursor = Native.Document.createElement("blink");
            cursor.innerText = "_";

            var index = 0;
            var index_char = 0;

            var span = new IHTMLSpan();

            var delay_delayed = false;

            Status = "creating actions";
            var Delay = default(System.Action<System.Action, int>);

            Delay = (h, due) => new Timer(

            delegate
            {

                if (delay_delayed)
                    Delay(h, due);
                else
                    h();

            }, due, 0);

            System.Func<string> CurrentLineString = () => (1 + index) + ". " + lines[index].Trim();

            var DeleteChar = default(System.Action);
            var PrintChar = default(System.Action);
            var ChooseLine = default(System.Action);

            DeleteChar =
                () =>
                {
                    index_char--;

                    span.innerText = CurrentLineString().Substring(0, index_char);

                    if (index_char == 0)
                    {
                        ChooseLine();
                    }
                    else
                    {
                        Delay(DeleteChar, 30);
                    }
                };

            PrintChar =
                () =>
                {
                    index_char++;

                    if (index_char < CurrentLineString().Length)
                    {
                        var x = 100;
                        var y = CurrentLineString()[index_char];


                        if (",. \t\n".Contains("" + y))
                            x = 200;


                        if (index_char > 1)
                            span.style.color = Color.None;

                        span.innerText = CurrentLineString().Substring(0, index_char);
                        Delay(PrintChar, x);
                    }
                    else
                    {
                        Delay(DeleteChar, 3000);
                    }
                };

            ChooseLine =
                () =>
                {
                    index = new System.Random().Next() % lines.Length;
                    index_char = 0;
                    span.innerText = "";
                    span.style.color = Color.White;

                    PrintChar();
                };

            Status = "adding to document";

            c.onmouseover +=
                delegate
                {
                    c.style.color = Color.Yellow;
                    delay_delayed = true;
                };

            c.onmouseout +=
                delegate
                {
                    c.style.color = Color.None;
                    delay_delayed = false;
                };


            c.appendChild(span, cursor);
            c.AttachToDocument();

            ChooseLine();
        }
		/// <summary>
		/// This is a javascript application.
		/// </summary>
		/// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
		public Application(IDefaultPage page)
		{
			new JSCSolutionsNETImage().ToBackground(page.Item1.style, false);
			new JSCSolutionsNETImage().ToBackground(page.Item2.style, false);


			// Update document title
			// http://do.jsc-solutions.net/Update-document-title

			@"Hello world".ToDocumentTitle();
			// Send xml to server
			// http://do.jsc-solutions.net/Send-xml-to-server

			var v = new SolutionFileView();

			var f = new SolutionFile();

			f.WriteHTMLElement(StockPageDefault.Element);

			v.File = f;

			var Container = new IHTMLDiv();

			Container.style.position = IStyle.PositionEnum.relative;
			Container.style.display = IStyle.DisplayEnum.inline_block;
			Container.style.width = "600px";
			Container.style.height = "400px";
			Container.style.border = "1px solid gray";

			var ToolbarHeight = "1.3em";
			var Content = new IHTMLDiv().AttachTo(Container);

			Content.style.position = IStyle.PositionEnum.absolute;
			Content.style.left = "0px";
			Content.style.top = "0px";
			Content.style.right = "0px";
			Content.style.bottom = ToolbarHeight;


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

			Toolbar.style.backgroundColor = Color.FromGray(0xef);
			Toolbar.style.position = IStyle.PositionEnum.absolute;
			Toolbar.style.left = "0px";
			Toolbar.style.height = ToolbarHeight;
			Toolbar.style.right = "0px";
			Toolbar.style.bottom = "0px";

			Action<IHTMLImage, string, Action> AddToolbarButton =
				(img, text, handler) =>
				{
					var span = new IHTMLSpan { innerText = text };

					span.style.paddingLeft = "1.5em";
					span.style.paddingRight = "0.3em";

					var a = new IHTMLAnchor
					{
						img, span
					};

					img.style.verticalAlign = "middle";
					img.border = 0;
					img.style.position = IStyle.PositionEnum.absolute;

					a.style.backgroundColor = Color.FromGray(0xef);
					a.style.color = Color.Black;
					a.style.textDecoration = "none";
					a.style.fontFamily = IStyle.FontFamilyEnum.Tahoma;

					a.href = "javascript: void(0);";
					a.onclick +=
						delegate
						{
							handler();
						};
					a.style.display = IStyle.DisplayEnum.inline_block;
					a.style.height = "100%";


					a.onmousemove +=
						delegate
						{
							a.style.backgroundColor = Color.FromGray(0xff);
						};

					a.onmouseout +=
						delegate
						{
							a.style.backgroundColor = Color.FromGray(0xef);
						};

					Toolbar.Add(a);
				};


			v.Container.style.height = "100%";
			v.Container.AttachTo(Content);


			Content.Add(v.Container);

			var i = CreateEditor();

			i.AttachTo(Content);



			var ii = new IHTMLPre().AttachTo(Content);

			ii.style.position = IStyle.PositionEnum.absolute;
			ii.style.left = "0px";
			ii.style.top = "0px";
			ii.style.right = "0px";
			ii.style.bottom = "0px";
			ii.style.overflow = IStyle.OverflowEnum.auto;
			ii.style.padding = "0px";
			ii.style.margin = "0px";
			ii.style.whiteSpace = IStyle.WhiteSpaceEnum.normal;

			v.Container.style.display = IStyle.DisplayEnum.none;
			i.style.display = IStyle.DisplayEnum.empty;
			ii.style.display = IStyle.DisplayEnum.none;

			AddToolbarButton(new RTA_mode_design(), "Design",
				delegate
				{
					v.Container.style.display = IStyle.DisplayEnum.none;
					ii.style.display = IStyle.DisplayEnum.none;
					i.style.display = IStyle.DisplayEnum.empty;
				}
			);

			AddToolbarButton(new RTA_mode_html(), "Source",
				delegate
				{
					v.Container.style.display = IStyle.DisplayEnum.empty;
					ii.style.display = IStyle.DisplayEnum.none;
					i.style.display = IStyle.DisplayEnum.none;

					f.Clear();

					i.WhenContentReady(
						body =>
						{
							f.WriteHTMLElement(body.AsXElement());

							// update
							v.File = f;
						}
					);


				}
			);

			AddToolbarButton(new RTA_mode_html(), "Source raw",
				delegate
				{
					v.Container.style.display = IStyle.DisplayEnum.none;
					ii.style.display = IStyle.DisplayEnum.empty;
					i.style.display = IStyle.DisplayEnum.none;



					i.WhenContentReady(
						body =>
						{
							ii.innerText = body.AsXElement().ToString();
						}
					);


				}
			);

			page.PageContainer.Add(Container);

			new ApplicationWebService().WebMethod2(
				new XElement(@"Document",
					new object[] {
						new XElement(@"Data", 
							new object[] {
								@"Hello world"
							}
						),
						new XElement(@"Client", 
							new object[] {
								@"Unchanged text"
							}
						)
					}
				),
				delegate(XElement doc)
				{
					// Show server message as document title
					// http://do.jsc-solutions.net/Show-server-message-as-document-title

					doc.Element(@"Data").Value.ToDocumentTitle();
				}
			);
		}
		public StudioView(Action<IHTMLElement, Action<ISaveAction>> AddSaveButton)
		{
			Content.style.position = IStyle.PositionEnum.absolute;
			Content.style.left = "0px";
			Content.style.right = "0px";
			Content.style.top = "0px";
			Content.style.bottom = "0px";

			new TwentyTenWorkspace().ToBackground(Content.style, true);

			var WorkspaceHeader = default(IHTMLSpan);

			@"jsc-solutions.net studio".ToDocumentTitle().With(
				title =>
				{
					WorkspaceHeader = new IHTMLSpan { innerText = title };

					WorkspaceHeader.AttachTo(Content);
					WorkspaceHeader.style.SetLocation(16, 8);
					WorkspaceHeader.style.color = Color.White;

					// http://www.quirksmode.org/css/textshadow.html
					WorkspaceHeader.style.textShadow = "#808080 4px 2px 2px";

				}
			);

			// em + px :)
			var Workspace0 = new IHTMLDiv().With(
				div =>
				{
					div.style.position = IStyle.PositionEnum.absolute;
					div.style.left = "0px";
					div.style.right = "0px";
					div.style.bottom = "0px";
					div.style.top = "3em";
				}
			).AttachTo(Content);

			// workspace contains the split views
			var Workspace = new IHTMLDiv().With(
				div =>
				{
					div.style.position = IStyle.PositionEnum.absolute;
					div.style.left = "6px";
					div.style.right = "6px";
					div.style.bottom = "6px";
					div.style.top = "6px";
				}
			).AttachTo(Workspace0);

			// in this project we wont be having toolbox or toolbar yet

			Action<HorizontalSplit> ApplyStyle =
				t =>
				{
					t.Split.Splitter.style.backgroundColor = Color.None;
					t.SplitImageContainer.Orphanize();
					t.SplitArea.Target.style.borderLeft = "0";
					t.SplitArea.Target.style.borderRight = "0";
					t.SplitArea.Target.style.width = "6px";
					t.SplitArea.Target.style.Opacity = 0.7;

					// should we obselete JSColor already?
					t.SelectionColor = JSColor.Black;
				};

			var EditorTreeSplit = new HorizontalSplit
			{
				Minimum = 0,
				Maximum = 1,
				Value = 0.7,
			};

			EditorTreeSplit.With(ApplyStyle);

			EditorTreeSplit.Split.Splitter.style.backgroundColor = Color.None;

			var Viewer = new SolutionDocumentViewer();
			SolutionDocumentViewerTab AboutTab = "About";
			Viewer.Add(AboutTab);
			AboutTab.TabElement.style.Float = IStyle.FloatEnum.right;

			SolutionDocumentViewerTab File1 = "File1";
			Viewer.Add(File1);

			var File1Content = new IHTMLDiv();

			// location + design

			File1Content.style.left = "0px";
			File1Content.style.top = "1em";
			File1Content.style.right = "0px";
			File1Content.style.bottom = "1em";
			File1Content.style.position = IStyle.PositionEnum.absolute;


			var File1View = new SolutionFileView();

			File1View.Container.style.left = "0px";
			File1View.Container.style.top = "0px";
			File1View.Container.style.right = "0px";
			File1View.Container.style.bottom = "0px";
			File1View.Container.style.position = IStyle.PositionEnum.absolute;

			File1Content.ReplaceContentWith(File1View.Container);

			var sln = new SolutionBuilder();

			var _Solution = new TreeNode(VistaTreeNodePage.Create);


			var _Project = _Solution.Add();

			var About = new AboutPage();

			Action UpdateFile1Text =
				delegate
				{

					if (File1View.File != null)
					{
						File1.Text = File1View.File.Name.SkipUntilIfAny("/");
					}
					else
					{
						File1.Text = sln.Name;
					}


				};
			Action Update =
				delegate
				{
					sln.Name = About.ProjectName.value;

					UpdateFile1Text();

					_Project.Clear();
					UpdateTree(sln, File1View, _Solution, _Project);
				};

			File1View.FileChanged +=
				delegate
				{
					if (File1View.File.Name.EndsWith(".htm"))
					{
						File1Content.style.top = "0px";
						File1Content.style.bottom = "1em";
						// show the design/source buttons
					}
					else if (File1View.File.Name.EndsWith(sln.Language.CodeFileExtension))
					{
						File1Content.style.top = "1em";
						File1Content.style.bottom = "0px";
						// show type outline / member
					}

					UpdateFile1Text();

					File1.Activate();
				};

			AddSaveButton(WorkspaceHeader, i => Save = i);

			About.ProjectName.value = sln.Name;
			About.ProjectName.onchange +=
				delegate
				{
					Update();
				};


			AboutTab.Activated +=
				delegate
				{
					// our about page has dynamic size..
					Viewer.Content.ReplaceContentWith(About.Container);
				};

			File1.Activated +=
				delegate
				{
				

					// our about page has dynamic size..
					Viewer.Content.ReplaceContentWith(File1Content);
				};

			AboutTab.Activate();

			EditorTreeSplit.Split.LeftContainer = Viewer.Container;

			var SolutionExplorer = new SolutionDockWindowPage();

			SolutionExplorer.HeaderText.innerText = "Solution Explorer";
			SolutionExplorer.Content.style.backgroundColor = Color.White;
			SolutionExplorer.Content.style.padding = "2px";
			SolutionExplorer.Content.ReplaceContentWith(_Solution.Container);

			_Solution.Container.style.overflow = IStyle.OverflowEnum.auto;
			_Solution.Container.style.height = "100%";
			_Solution.Container.style.backgroundColor = Color.White;

			EditorTreeSplit.Split.RightContainer = SolutionExplorer.Container;

			EditorTreeSplit.Container.AttachTo(Workspace);


			Update();

			new Rules(File1View, sln, Update);
		}
        private static Tuple CreateDiv()
        {
            var t = new Tuple
                    {
                        y = 0,
                        div = new IHTMLDiv { className = "block" }
                    };

            var info = new IHTMLSpan();

            t.div.appendChild(info);

            t.div.AttachToDocument();

            t.div.onmousewheel +=
                delegate(IEvent e)
                {
                    info.innerHTML = "wheel, " + t.y;
                    info.appendChild(": " + e.WheelDirection);

                    t.y += e.WheelDirection;
                };

            t.div.style.position = IStyle.PositionEnum.absolute;
            t.div.style.height = "50%";
            t.div.style.width = "100%";
            t.div.style.backgroundColor = Color.Yellow;

            info.innerHTML = "scroll here";

            return t;
        }
		public Application(IHTMLElement e)
		{
			Native.Document.title = "IntelliSense1";

			var c = new IHTMLDiv
			{

			}.AttachToDocument();

			c.onmouseover +=
				delegate
				{
					c.style.backgroundColor = "#efefff";
				};

			c.onmouseout +=
				delegate
				{
					c.style.backgroundColor = "";
				};


			c.style.margin = "2em";
			c.style.padding = "2em";
			c.style.border = "1px solid #777777";
			c.style.borderLeft = "2em solid #777777";


			new IHTMLDiv
			{
				new IHTMLAnchor
				{
					innerText = "Write javascript, flash and java applets within a C# project.",
					href = "http://www.jsc-solutions.net"
				}
			}.AttachTo(c);


			{
				var btn = new IHTMLButton { innerText = "UltraWebService" }.AttachTo(c);

				btn.onclick +=
					delegate
					{

						new UltraWebService().GetTime("time: ",
							result =>
							{
								new IHTMLDiv { innerText = result }.AttachTo(c);

							}
						);

					};
			}

			var Editor = new IHTMLDiv().AttachToDocument();

			Editor.style.position = IStyle.PositionEnum.relative;
			Editor.style.backgroundColor = "#efefef";
			Editor.style.SetSize(400, 200);
			//Editor.style.overflow = IStyle.OverflowEnum.auto;

			var CodeShadowContainer = new IHTMLDiv().AttachTo(Editor);
			var CodeShadowSize = new IHTMLSpan().AttachTo(CodeShadowContainer);
			var CodeShadow = new IHTMLSpan().AttachTo(CodeShadowContainer);
			var CodeShadowLine = new IHTMLSpan().AttachTo(CodeShadowContainer);
			var CodeShadowMenu = new IHTMLDiv().AttachTo(CodeShadowContainer);

			CodeShadowMenu.style.backgroundColor = "red";

			var Code = new IHTMLTextArea().AttachTo(Editor);
			Code.style.SetLocation(0, 0, 400, 200);

			CodeShadowSize.style.position = IStyle.PositionEnum.absolute;
			CodeShadowSize.style.SetLocation(0, 0);

			CodeShadow.style.position = IStyle.PositionEnum.absolute;
			CodeShadow.style.SetLocation(0, 0);

			CodeShadowLine.style.position = IStyle.PositionEnum.absolute;
			CodeShadowLine.style.SetLocation(0, 0);

			CodeShadowContainer.style.SetLocation(0, 0, 400, 200);

			Action Update =
				delegate
				{
					CodeShadowSize.innerText = Code.value;

					var n = Code.value.Substring(0, Code.SelectionStart).Replace("\r", "");

					CodeShadow.innerText = n;
					CodeShadowLine.innerText = n.SkipUntilLastIfAny("\n");

					//var w = CodeShadowSize.offsetWidth;
					//if (w < 400)
					//    w = 400;

					//var h = CodeShadowSize.offsetHeight;
					//if (h < 200)
					//    h = 200;

					//Code.style.SetSize(w, h);

					if (n.EndsWith("."))
					{
						CodeShadowMenu.style.SetLocation(
							CodeShadowLine.offsetWidth,
							CodeShadow.offsetHeight,
							64, 32
						);
					}
					else
					{
						CodeShadowMenu.style.SetLocation(
							CodeShadowLine.offsetWidth,
							CodeShadow.offsetHeight,
							12, 12
						);
					}
				};

			Code.onkeyup +=
				delegate
				{
					Update();
				};

			Code.onchange +=
				delegate
				{
					Update();
				};

			Code.onmouseup +=
				delegate
				{
					Update();
				};

			Action<IStyle> SetStyle =
				style =>
				{
					style.padding = "0";
					style.margin = "0";
					style.display = IStyle.DisplayEnum.inline;

					style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
					style.fontSize = "1em";

					// http://www.tagindex.net/css/form/line_height.html
					// http://www.eskimo.com/~bloo/indexdot/css/properties/dimension/lineheight.htm
					style.lineHeight = "200%";

					// http://www.w3schools.com/CSS/pr_text_white-space.asp
					style.whiteSpace = IStyle.WhiteSpaceEnum.pre;
					//style.textWrap = 
				};

			Code.style.border = "0";

			// http://www.idocs.com/tags/forms/_TEXTAREA_WRAP.html
			Code.wrap = "off";
			Code.style.overflow = IStyle.OverflowEnum.hidden;
			Code.style.backgroundColor = JSColor.Transparent;

			//if (IsMicrosoftInternetExplorer)
			//{
			//    CodeShadow.style.lineHeight = "125%";
			//}

			CodeShadow.style.color = "gray";
			CodeShadow.style.backgroundColor = "yellow";

			CodeShadowLine.style.color = "gray";
			CodeShadowLine.style.backgroundColor = "cyan";

			SetStyle(Code);
			SetStyle(CodeShadowSize);
			SetStyle(CodeShadow);
			SetStyle(CodeShadowLine);

			Code.value = "hello1\nhello2\nhello3 WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW\n...";
			Update();
		}
        // Z:\jsc.svn\examples\javascript\android\com.abstractatech.wiki\com.abstractatech.wiki\Application.cs


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

            var t = new ScriptCoreLib.JavaScript.Controls.TextEditor(
                page.body,

                fonts:
                    new[] {
                        new Fonts.BLOKKRegular().rule,
                        new Fonts.redacted_script_regular().rule,
                    }
            );

            Console.WriteLine("adding the button");

            // <font color="#0000fc">s</font>


            new IHTMLButton
            {
                "make svg friendly"
            }.AttachToDocument().WhenClicked(
                x =>
                {
                    Console.WriteLine(
                        new { body = t.Document.body.AsXElement() }
                    );

                //7990ms { body = <body style="height: auto; border: 0; overflow: auto; background-color:transparent;">ss<font color="#ff0000">dfsdf</font>sd</body> } view-source:35444
                //7993ms { f = <font color="#ff0000">dfsdf</font> } 

                t.Document.body.AsXElement().Elements().WithEach(
                zf =>
                {
                            Console.WriteLine(new { zf, zf.Name.LocalName });

                        // 10797ms { zf = <font color="#ff0000">dfs</font>, LocalName = FONT } 

                        if (zf.Name.LocalName.ToLower() == "div")
                            {

                                var ff = new IHTMLSpan { innerText = zf.Value };

                                var color = zf.Attribute("color").Value;

                                ff.style.color = color;

                                Console.WriteLine("ReplaceWith" + new { ff.innerText, color });

                                zf.ReplaceWith(ff.AsXElement());
                            }

                            if (zf.Name.LocalName.ToLower() == "font")
                            {

                                var ff = new IHTMLSpan { innerText = zf.Value };

                                var color = zf.Attribute("color").Value;

                                ff.style.color = color;

                                Console.WriteLine("ReplaceWith" + new { ff.innerText, color });

                                zf.ReplaceWith(ff.AsXElement());
                            }
                        }
            );

                // we inline images, should look for fonts inside svg too?
                t.Document.body.AsXElement().Elements("font").ToArray().WithEach(
                f =>
                {
                            Console.WriteLine(new { f });


                            var ff = new IHTMLSpan { innerText = f.Value };

                            ff.style.color = f.Attribute("color").Value;

                            f.ReplaceWith(ff.AsXElement());

                        //f.Nodes().att
                    }
            );
                }
            );

            new IHTMLButton
            {
                "getframe"
            }.AttachToDocument().WhenClicked(
                delegate
                {
                    var snapshot = new IHTMLDiv
                    {
                        innerHTML = t.InnerHTML
                    };

                    Console.WriteLine(t.InnerHTML);

                    IHTMLImage i = snapshot;

                    i.AttachToDocument();
                }
            );

            //@"Hello world".ToDocumentTitle();
            //// Send data from JavaScript to the server tier
            //service.WebMethod2(
            //    @"A string from JavaScript.",
            //    value => value.ToDocumentTitle()
            //);
        }
            public MainMenu(EnemyDirectory MyEnemyDirectory, ImageResources gfx)
            {
                Func<string, Color, IHTMLSpan> GetText2 =
                           delegate(string text, Color color)
                           {
                               var s = new IHTMLSpan(text);
                               s.style.color = color;
                               return s;
                           };

                Func<string, Color, string, IHTMLSpan> GetText =
                    delegate(string text, Color color, string size)
                    {
                        var s = GetText2(text, color);

                        s.style.fontSize = size;

                        return s;
                    };


                Control.appendChild(
                    new IHTMLDiv(
                        gfx.cenemy.Clone(),
                            GetText("&nbsp;SPACE&nbsp;", Color.White, "48px"),
                        gfx.cenemy.Clone()
                    )
                );

                Control.appendChild(
                  new IHTMLDiv(
                      gfx.aenemy.Clone(),
                          GetText("&nbsp;INVADERS&nbsp;", Color.Green, "48px"),
                      gfx.aenemy.Clone()
                  )
                );


                Action DrawBreak =
                    delegate
                    {
                        Control.appendChild(new IHTMLBreak());
                    };


                DrawBreak();

                Control.appendChild(
                    GetText2("Press&nbsp;", Color.White),
                    GetText2("enter", Color.Green),
                    GetText2("&nbsp;to start game", Color.White)
                );

                DrawBreak();
                DrawBreak();
                Action<EnemyInfo> DrawEnemyInfo =
                    delegate(EnemyInfo e)
                    {
                        Control.appendChild(
                          new IHTMLDiv(
                              e.Image.Clone(),
                                  GetText2("&nbsp;- " + e.Points + " points", Color.White)
                          )
                        );
                    };

                DrawEnemyInfo(MyEnemyDirectory.A);
                DrawBreak();
                DrawEnemyInfo(MyEnemyDirectory.B);
                DrawBreak();
                DrawEnemyInfo(MyEnemyDirectory.C);
                DrawBreak();
                DrawEnemyInfo(MyEnemyDirectory.UFO);
                DrawBreak();
                DrawBreak();


                Control.appendChild(
                    new IHTMLDiv(
                    GetText2("Left/Right arrow", Color.Green),
                    GetText2(" - move, ", Color.White),
                    GetText2("SPACE", Color.Green),
                    GetText2(" - fire", Color.White)
                    )
                );

                Control.appendChild(
                    new IHTMLDiv(
                             GetText2("Escape", Color.Green),
                             GetText2(" - quit, ", Color.White),
                             GetText2("'p'", Color.Green),
                             GetText2(" - pause", Color.White)
                             )
                         );

                DrawBreak();
                DrawBreak();


                Control.appendChild(
                    new IHTMLDiv(
                        new IHTMLAnchor("http://zproxy.wordpress.com/2007/03/03/jsc-space-invaders/", "post a comment")
                    ),
                    new IHTMLDiv(
                        new IHTMLAnchor("http://jsc.sourceforge.net", "powered by jsc")
                    )
                );
            }
            public GameOverMenu()
            {
                Func<string, Color, IHTMLSpan> GetText2 =
                           delegate(string text, Color color)
                           {
                               var s = new IHTMLSpan(text);
                               s.style.color = color;
                               return s;
                           };

                Func<string, Color, string, IHTMLSpan> GetText =
                    delegate(string text, Color color, string size)
                    {
                        var s = GetText2(text, color);

                        s.style.fontSize = size;

                        return s;
                    };

                Control.appendChild(GetText("GAME OVER", Color.Green, "44px"));
            }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            #region hr
            Action hr = delegate
            {
                //new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument();
                new IHTMLHorizontalRule().AttachToDocument();
            };
            #endregion


            {
                var x = new IHTMLSpan { "hello world" }.AttachToDocument();
            }
            hr();

            {
                var x = new IHTMLSpan { "hello world" }.AttachToDocument();


                x.css.before.contentText = "look we are using ::before content string";
            }
            hr();

            {
                var x = new IHTMLSpan { "hello world" }.AttachToDocument();

                //x.css.before.contentText = "look we are using ::before content string";
                //x.createShadowRoot(

                x.shadow.appendChild("this is a shadow fragment");

            }
            hr();

            {
                var x = new IHTMLSpan { "hello world" }.AttachToDocument();

                // is it visible if there is shadow defined?
                x.css.before.contentText = "[::before content string with shadow] ";

                //x.createShadowRoot(

                x.shadow.appendChild("this is a shadow fragment");


            }
            hr();



            {
                var x = new IHTMLSpan { "hello world" }.AttachToDocument();

                // is it visible if there is shadow defined?
                x.css.before.contentText = "[::before content string with shadow] ";

                //x.createShadowRoot(


                // what about multiple shadows?
                x.shadow.appendChild("this is a shadow fragment with content: ");

                // can we style the content ? no
                new IHTMLContent { }.AttachTo(x.shadow).style.border = "1px solid red";

            }
            hr();

        }
        public __ToolStripButton()
        {
            (this.InternalElement.style.display as dynamic).display = "table-cell";

            //InternalElement.style.width = "auto";
            InternalElement.style.padding = "2px";


            var InternalElementSpan = new IHTMLSpan().AttachTo(InternalElement);
            //InternalElementSpan.style.verticalAlign = "baseline";

            this.InternalElement.style.font = Control.DefaultFont.ToCssString();


            //this.Font = DefaultFont;

            this.InternalImageChanged +=
                delegate
                {

                    if (this.InternalImage == null)
                        return;

                    var i = ((__Bitmap)(object)this.InternalImage).InternalImage;

                    // https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align
                    //i.style.verticalAlign = "baseline";

                    this.InternalElement.insertBefore(
                        i,
                        InternalElementSpan
                    );

                    if (this.DisplayStyle == ToolStripItemDisplayStyle.Image)
                    {
                        i.InvokeOnComplete(
                            delegate
                            {
                                InternalElementSpan.Hide();
                            }
                        );
                    }
                };

            this.InternalElement.onclick +=
                delegate
                {
                    this.RaiseClick();
                };

            this.TextChanged += delegate
            {
                InternalElementSpan.innerText = this.InternalText;
            };

            this.InternalAfterSetOwner +=
                delegate
                {
                    __ToolStrip o = this.Owner;

                    // or contaner?
                    InternalElement.AttachTo(o.InternalElement);


                };

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

            var n = new MyEditor();

            n.Container.AttachToDocument();

            //var a = new IHTMLAnchor(
            //    "http://sketchup.google.com/3dwarehouse/search?q=stargate",
            //    "Open 3dwarehouse in another window"
            //);
            //a.style.fontSize = "large-xx";
            //a.AttachToDocument();



            //ii.setAttribute("src", "http://sketchup.google.com/3dwarehouse/");


            IHTMLDiv Control = new IHTMLDiv();

            n.Edit1.parentNode.replaceChild(Control, n.Edit1);

            //n.Logo.src = "assets/TextEditorDemo2/Preview.png";

            //Control.AttachToDocument();


            var text = new TextEditor(Control);


            text.InnerHTML = "Drag images to this frame!<hr />";

            // IE error

            text.Height = 200;
            text.Width = 400;
            //text.InnerHTML = n.Edit1.value;

            text.IsFadeEnabled = false;

            //var i = new IHTMLImage(21, 20) { src = "assets/TextEditorDemo2/cal.png" };

            var CurrentList = new List<InternalExtensions.GoogleThreeDWarehouseImage>();

            n.ToLarge.onclick += e =>
            {
                CurrentList.ForEach(k => k.AnimationZoom = 4);
            };

            n.ToMedium.onclick += e =>
            {
                CurrentList.ForEach(k => k.AnimationZoom = 1);
            };
            n.ToSmall.onclick += e =>
            {
                CurrentList.ForEach(k => k.AnimationZoom = 0.5);
            };

            Action<string[], IHTMLButton> ToPreview =
                (data, button) =>
                {
                    var ii = new IHTMLImage(40, 30) { src = data[0] };
                    ii.style.verticalAlign = "middle";

                    var sp = new IHTMLSpan();
                    sp.style.marginLeft = "1em";
                    sp.AttachTo(button);

                    ii.AttachTo(button).ToGoogleThreeDWarehouseImage().Animate();

                };
            n.Nasa.onclick +=
                delegate
                {
                    text.InnerHTML = NasaSource.Text;

                };


            //n.Houses.onclick +=
            //    delegate
            //    {
            //        text.InnerHTML = Pages.Houses.Static.HTML;

            //    };

            n.CnC.onclick +=
                delegate
                {
                    text.InnerHTML = CnCSource.Text;

                };

            n.Ships.onclick +=
            delegate
            {
                text.InnerHTML = ShipsSource.Text;
            };

            //ToPreview(Ships..Images, n.Ships);
            //ToPreview(CnC.Static.Images, n.CnC);
            ////ToPreview(Houses.Static.Images, n.Houses);
            //ToPreview(Nasa.Static.Images, n.Nasa);


            //i.AttachToDocument();
            n.OK.onclick +=
                delegate
                {
                    n.ContainerForImages.removeChildren();
                    CurrentList.Clear();
                    //text.Document.getElementsByTagName("img").ToGoogleThreeDWarehouseImages().Animate();

                    var clones = text.Document.GetClonedImages();
                    foreach (IHTMLImage iii in clones)
                    {


                        var w = iii.AttachTo(n.ContainerForImages).ToGoogleThreeDWarehouseImage();

                        w.Animate();

                        CurrentList.Add(w);
                    }

                };
            //);

            //OK.Control.style.paddingLeft = "1em";
            //text.BottomToolbarContainer.appendChild(OK.Control);

            text.TopToolbarContainer.Hide();
            text.BottomToolbarContainer.Hide();
        }
        public __DataGridView()
        {
            //Console.WriteLine("enter DataGridView .ctor");

            Console.WriteLine("event: enter new DataGridView()");

            this.AutoGenerateColumns = true;


            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201404/20140412
            // tested by?
            // X:\jsc.svn\examples\javascript\forms\test\TestWebBrowserOneWayDataBinding\TestWebBrowserOneWayDataBinding\ApplicationControl.Designer.cs
            //    this.dataGridView1.RowTemplate.Height = 24;
            this.RowTemplate = new DataGridViewRow();

            this.InternalElement = new IHTMLDiv
            {

                // do this ahead of time
                // when can we have a special type for a classname string?
                className = typeof(DataGridView).Name
            };

            // can jsc help us here and via [HTMLAttribute] redirect the data to html attribute?
            this.AllowUserToResizeColumnsAttribute = new XAttribute("AllowUserToResizeColumns", "").AttachTo(this.InternalElement);
            this.RowHeadersVisibleAttribute = new XAttribute("RowHeadersVisible", "true").AttachTo(this.InternalElement);


            // add the rule to current document.
            // what happens if we do popup?
            // wha about scoped style?
            this.css = this.InternalElement.css;

            // do we need this?
            this.InternalElement.style.overflow = DOM.IStyle.OverflowEnum.hidden;



            this.InternalColumns = new __DataGridViewColumnCollection();
            this.Columns = (DataGridViewColumnCollection)(object)this.InternalColumns;

            #region InternalRows
            this.InternalRows = new __DataGridViewRowCollection
            {
                InternalContext = this
            };
            this.Rows = (DataGridViewRowCollection)(object)this.InternalRows;

            this.InternalRows.InternalItems.Added +=
                (s, i) =>
                {
                    s.InternalContext = this;
                };
            #endregion


            #region SelectedCells
            this.InternalSelectedCells = new __DataGridViewSelectedCellCollection();
            this.SelectedCells = (DataGridViewSelectedCellCollection)(object)this.InternalSelectedCells;
            this.InternalSelectedCells.InternalItems.ListChanged +=
                (_s, _e) =>
                {
                    if (_e.ListChangedType == ListChangedType.ItemAdded)
                    {
                        var item = this.InternalSelectedCells.InternalItems[_e.NewIndex];

                        // when is this null?
                        //if (this.DefaultCellStyle == null)
                        //{
                        //    item.InternalContentContainer.style.backgroundColor = JSColor.System.Highlight;
                        //}
                        //else
                        //{
                        var SelectionBackColor = this.DefaultCellStyle.SelectionBackColor;
                        var SelectionForeColor = this.DefaultCellStyle.SelectionForeColor;

                        item.InternalTableColumn_div.style.backgroundColor = SelectionBackColor.ToString();
                        //}
                        //item.InternalContentContainer.style.color = JSColor.System.HighlightText;

                        // tested by
                        // X:\jsc.svn\core\ScriptCoreLib.Windows.Forms\ScriptCoreLib.Windows.Forms\JavaScript\BCLImplementation\System\Windows\Forms\DataGridView.cs
                        item.InternalTableColumn_div.style.color = SelectionForeColor.ToString();
                    }


                    if (SelectionChanged != null)
                        SelectionChanged(this, new EventArgs());
                };
            #endregion


            this.MultiSelect = true;



            this.InternalSetDefaultFont();

            this.InternalScrollContainerElement = new IHTMLDiv
            {
                // pstyle
                className = "InternalScrollContainerElement"
            }.AttachTo(this.InternalElement);




            //this.InternalScrollContainerElement.style.backgroundColor = JSColor.Gray;
            this.BackgroundColor = global::System.Drawing.SystemColors.AppWorkspace;

            this.InternalScrollContainerElement.style.overflow = DOM.IStyle.OverflowEnum.auto;

            // tested by
            // X:\jsc.svn\examples\javascript\css\CSSPrintMediaExperiment\CSSPrintMediaExperiment\Application.cs

            // for printer we do not want to see the scollbar
            // if we change the document we will loose the style?
            // this wont work
            //IStyleSheet.Default
            //    [CSSMediaTypes.print]
            //    [this.InternalScrollContainerElement].style.overflow =
            //        IStyle.OverflowEnum.hidden;


            new IStyle(this.InternalScrollContainerElement)
            {
                position = DOM.IStyle.PositionEnum.absolute,
                left = "0px",
                top = "0px",
                right = "0px",
                bottom = "0px"
            };


            var __ContentTableContainer = new IHTMLDiv { className = "__ContentTableContainer" }.AttachTo(InternalScrollContainerElement);

            // 116ms css.style { selectorText = table.__ContentTable[style-id="2"] > tbody > tr > td } 
            this.__ContentTable = new IHTMLTable
            {
                className = __ContentTable_className,
                cellPadding = 0,
                cellSpacing = 0
            }.AttachTo(__ContentTableContainer);

            // X:\jsc.svn\examples\javascript\css\CSSOdd\CSSOdd\Application.cs

            //this.__ContentTable_css = css.descendants[className];
            this.__ContentTable_css = css[this.__ContentTable];

            //css.adjacentSibling[]
            //css.siblings

            //92ms css.style { selectorText = div.DataGridView[style-id="2"] table.__DataGridViewContentTable > tbody > tr > td } view-source:34816

            // view-source:34816
            //92ms css.style { selectorText = table.__DataGridViewColumnsTable[style-id="3"] > tbody > tr > td } 

            // the hacky way:
            //this.__ContentTable_css = css[" table." + this.__ContentTable.className];

            this.__ContentTable_css_td = this.__ContentTable_css
                + IHTMLElement.HTMLElementEnum.tbody
                + IHTMLElement.HTMLElementEnum.tr
                + IHTMLElement.HTMLElementEnum.td;

            this.__ContentTable_css_alt_td = this.__ContentTable_css
                [IHTMLElement.HTMLElementEnum.tbody][IHTMLElement.HTMLElementEnum.tr].even[IHTMLElement.HTMLElementEnum.td];

            this.__ContentTable_css_odd_td = this.__ContentTable_css
                [IHTMLElement.HTMLElementEnum.tbody][IHTMLElement.HTMLElementEnum.tr].odd[IHTMLElement.HTMLElementEnum.td];


            __ContentTable.style.paddingTop = "22px";



            var __ColumnsTableContainer = new IHTMLDiv
            {
                className = "__ColumnsTableContainer"
            }.AttachTo(InternalScrollContainerElement);

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201312/20131213-forms-css
            this.__ColumnsTable = new IHTMLTable
            {
                className = __ColumnsTable_className,

                cellPadding = 0,
                cellSpacing = 0
            }.AttachTo(
            __ColumnsTableContainer);

            this.__ColumnsTable_css = css[this.__ColumnsTable];

            this.__ColumnsTable_css_td =
                this.__ColumnsTable_css
                + IHTMLElement.HTMLElementEnum.tbody
                + IHTMLElement.HTMLElementEnum.tr
                + IHTMLElement.HTMLElementEnum.td;

            IHTMLTableRow __ColumnsTableRow = null;

            //__ColumnsTableContainer.style.SetLocation(0, 0);
            __ColumnsTableContainer.style.position = IStyle.PositionEnum.absolute;
            __ColumnsTableContainer.style.left = "0px";

            __ColumnsTableRow = __ColumnsTable.AddBody().AddRow();
            __ColumnsTableRow.style.height = "22px";


            var __RowsTableContainer = new IHTMLDiv
            {
                className = "__RowsTableContainer"
            }.AttachTo(InternalScrollContainerElement);

            //__RowsTableContainer.style.SetLocation(0, 0);
            __RowsTableContainer.style.position = IStyle.PositionEnum.absolute;
            __RowsTableContainer.style.top = "0px";


            this.__RowsTable = new IHTMLTable
            {
                className = __RowsTable_className,
                cellPadding = 0,
                cellSpacing = 0
            }.AttachTo(__RowsTableContainer);

            // should we make the monkier a bit lazier?
            this.__RowsTable_css = css[this.__RowsTable];

            // 139ms { __RowsTable_css = { selectorText = div.DataGridView[style-id="2"] > div:nth-of-type(1) > div:nth-of-type(3) > table:nth-of-type(1), selectorElement =  } } 
            //Console.WriteLine(new { this.__RowsTable_css });
            this.__RowsTable_css_td = this.__RowsTable_css
                + IHTMLElement.HTMLElementEnum.tbody
                + IHTMLElement.HTMLElementEnum.tr
                + IHTMLElement.HTMLElementEnum.td;

            this.__RowsTable_css_td.style.backgroundColor = "cyan";


            __RowsTable.style.paddingTop = "22px";
            this.__RowsTableBody = __RowsTable.AddBody();

            Console.WriteLine("new DataGridView() before Corner");

            #region Corner
            this.__Corner = new IHTMLDiv().AttachTo(InternalScrollContainerElement);


            __Corner.style.position = IStyle.PositionEnum.absolute;
            //__Corner.style.SetLocation(0, 0);
            __Corner.style.height = "22px";

            #endregion

            // too slow for onscroll
            //var css_fixed_left =
            //    __RowsTableContainer.css
            //    | __Corner.css;

            //var css_fixed_top =
            //   __ColumnsTableContainer.css
            //   | __Corner.css;

            #region onscroll
            Action onscroll = delegate
            {
                // perhaps we should only use .css for static styles?

                // how much faster are we if we skip .css ?
                __Corner.style.top = this.InternalScrollContainerElement.scrollTop + "px";
                __ColumnsTableContainer.style.top = this.InternalScrollContainerElement.scrollTop + "px";

                __Corner.style.left = this.InternalScrollContainerElement.scrollLeft + "px";
                __RowsTableContainer.style.left = this.InternalScrollContainerElement.scrollLeft + "px";


                //css_fixed_left.style.left = this.InternalScrollContainerElement.scrollLeft + "px";
                //css_fixed_top.style.top = this.InternalScrollContainerElement.scrollTop + "px";
            };
            #endregion

            this.__ContentTableBody = __ContentTable.AddBody();

            this.InternalNewRow = new __DataGridViewRow();
            this.InternalNewRow.InternalTableRow = __ContentTableBody.AddRow();
            this.InternalNewRow.InternalTableRow.style.height = "22px";


            this.InternalRows.InternalItems.Source.Add(InternalNewRow);

            // http://www.w3schools.com/cssref/sel_last-of-type.asp
            // dont we have lastOfType available yet?
            var InternalNewRow_content_css =
                // can we have LINQ style?  .Last()
                (__ContentTable_css + IHTMLElement.HTMLElementEnum.tbody).last[IHTMLElement.HTMLElementEnum.tr];

            var InternalNewRow_header_css = __RowsTable_css
                [IHTMLElement.HTMLElementEnum.tbody].last[IHTMLElement.HTMLElementEnum.tr];

            var InternalNewRow_css = InternalNewRow_content_css | InternalNewRow_header_css;

            // move to conditional css!
            this.AllowUserToAddRowsChanged +=
                delegate
                {
                    if (this.AllowUserToAddRows)
                        InternalNewRow_css.style.display = IStyle.DisplayEnum.empty;
                    else
                        InternalNewRow_css.style.display = IStyle.DisplayEnum.none;
                };


            this.DefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = global::System.Drawing.SystemColors.Window
            };

            this.ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = global::System.Drawing.SystemColors.ButtonFace
            };

            this.RowHeadersDefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = global::System.Drawing.SystemColors.ButtonFace
            };


            Console.WriteLine("new DataGridView() before CreateVerticalResizer");


            #region CreateVerticalResizer --
            Func<IHTMLDiv> CreateVerticalResizer =
                () =>
                {
                    var r = new IHTMLDiv { className = "VerticalResizer" };

                    r.style.position = DOM.IStyle.PositionEnum.absolute;
                    r.style.height = "9px";
                    r.style.left = "0px";
                    r.style.width = "200px";
                    //HorizontalResizer.style.backgroundColor = JSColor.Red;
                    //r.style.cursor = DOM.IStyle.CursorEnum.move;

                    var l = new IHTMLDiv().AttachTo(r);

                    l.style.position = DOM.IStyle.PositionEnum.absolute;
                    l.style.top = "4px";
                    l.style.height = "1px";
                    l.style.left = "0px";
                    l.style.right = "0px";

                    //l.style.backgroundColor = this.InternalBackgroundColor.ToString();
                    ////l.style.backgroundColor = "yellow";

                    //InternalBackgroundColorChanged +=
                    //    delegate
                    //    {
                    //        l.style.backgroundColor = this.InternalBackgroundColor.ToString();
                    //    };


                    l.setAttribute("data-resizer", "resizer");

                    //this.InternalGridColorTargets.Add(
                    //     l.css
                    // );



                    this.ClientSizeChanged +=
                       delegate
                       {
                           r.style.width = "200x";
                           //r.Hide();

                           Native.window.requestAnimationFrame +=
                               //new ScriptCoreLib.JavaScript.Runtime.Timer(
                               delegate
                               {
                                   r.style.width = this.InternalScrollContainerElement.clientWidth + "px";
                                   //l.style.backgroundColor = "red";
                                   //r.Show();

                               }
                           ;
                           //).StartTimeout(200);
                       };


                    return r;
                };
            #endregion


            //css[(dynamic x) => x.AllowUserToResizeColumns == false][" .HorizontalResizer"].style.display = IStyle.DisplayEnum.none;
            //css[x => x.getAttribute("AllowUserToResizeColumns") == false][" .HorizontalResizer"].style.display = IStyle.DisplayEnum.none;

            var xAllowUserToResizeColumns_false = new XAttribute("AllowUserToResizeColumns", "false");

            css[xAllowUserToResizeColumns_false][" .HorizontalResizer"].style.display = IStyle.DisplayEnum.none;

            // should jsc go and detect where the attribute is attached to?
            //css[" .HorizontalResizer"][xAllowUserToResizeColumns_false].style.display = IStyle.DisplayEnum.none;

            // before CreateHorizontalResizer 

            var css_HorizontalResizer = css[" .HorizontalResizer"];

            new IStyle(css_HorizontalResizer)
            {
                position = DOM.IStyle.PositionEnum.absolute,
                width = "9px",
                height = "22px"
            };

            css_HorizontalResizer.hover.style.height = "100%";
            css_HorizontalResizer.active.style.height = "100%";
            css_HorizontalResizer.style.cursor = DOM.IStyle.CursorEnum.move;

            //var css_HorizontalResizerLine = css_HorizontalResizer[IHTMLElement.HTMLElementEnum.div];

            new IStyle(css_HorizontalResizer.after)
            {
                // just to show up, we need to set this?
                content = "''",

                position = DOM.IStyle.PositionEnum.absolute,
                left = "4px",
                width = "1px",
                top = "0px",
                bottom = "0px"
            };

            //_HorizontalResizer.css.active.first.style.color = "blue";
            //_HorizontalResizer.css.style.backgroundColor = "yellow";
            //_HorizontalResizer.css.active.style.backgroundColor = "cyan";

            // debug
            //_HorizontalResizer.css.first.style.backgroundColor = "cyan";

            // ?css.after.parent.hover...
            css_HorizontalResizer.hover.after.style.backgroundColor = "black";
            css_HorizontalResizer.active.after.style.backgroundColor = "blue";

            // save it so we can change the color
            this.InternalGridColor_css = css_HorizontalResizer.after;

            //var css = 



            //var ZeroVerticalResizer = CreateVerticalResizer().AttachTo(InternalElement);

            //ZeroVerticalResizer.style.SetLocation(0, 22 - 5);

            Console.WriteLine("new DataGridView() before ZeroHorizontalResizer");



            #region ZeroHorizontalResizer

            //var ZeroHorizontalResizer = CreateHorizontalResizer().AttachTo(InternalElement);
            var ZeroHorizontalResizer = new IHTMLDiv { className = "HorizontalResizer" }.AttachTo(InternalScrollContainerElement);

            var ZeroHorizontalResizerDrag = new DragHelper(ZeroHorizontalResizer)
            {
                // why cant I see it?
                Position = new Point(32, 0),
                Enabled = true
            };


            //Action UpdateToVerticalResizerScroll = delegate
            //{
            //    //ZeroVerticalResizer.style.SetLocation(
            //    //    this.InternalScrollContainerElement.scrollLeft,
            //    //    this.InternalScrollContainerElement.scrollTop + (22 - 5)
            //    //);
            //};



            #region UpdateToHorizontalResizerScroll
            Action UpdateToHorizontalResizerScroll = delegate
            {
                ZeroHorizontalResizer.style.SetLocation(
                        this.InternalScrollContainerElement.scrollLeft + ZeroHorizontalResizerDrag.Position.X - 1,
                        this.InternalScrollContainerElement.scrollTop
                    );
            };
            #endregion

            // what if the the value is changed in the inspector/
            // will our control survive the change? as we dont get any events for that.
            // almost. the Fill will not be recalculate just yet tho
            // tested by
            // X:\jsc.svn\examples\javascript\forms\Test\TestFlowDataGridPadding\TestFlowDataGridPadding\Application.cs
            css[new XAttribute("RowHeadersVisible", "false")][__ColumnsTable, __ContentTable].style.paddingLeft = "1px";
            var css_RowHeadersVisible_true = css[new XAttribute("RowHeadersVisible", "true")][__ColumnsTable, __ContentTable];

            #endregion

            Console.WriteLine("new DataGridView() before UpdateToHorizontalResizerDrag");


            #region UpdateToHorizontalResizerDrag
            Action UpdateToHorizontalResizerDrag = delegate
            {
                //var value = (ZeroHorizontalResizerDrag.Position.X + 4);
                var value = (ZeroHorizontalResizerDrag.Position.X + 4);

                // no we want it completly gone, not just at 4px
                if (this.RowHeadersVisible)
                {

                    __Corner.style.width = (value - 2) + "px";

                    __RowsTable.style.width = value + "px";
                    __RowsTable.style.minWidth = value + "px";

                    // has 2 borders
                }

                css_RowHeadersVisible_true.style.paddingLeft = value + "px";
            };

            #endregion

            // when this.RowHeadersVisible == false
            css[new XAttribute("RowHeadersVisible", "false")]
                [ZeroHorizontalResizer,
                __Corner,
                __RowsTable]
                .style.display = IStyle.DisplayEnum.none;

            UpdateToHorizontalResizerScroll();
            UpdateToHorizontalResizerDrag();

            InternalRowHeadersVisibleChanged +=
              delegate
              {
                  // tested by
                  // X:\jsc.svn\examples\javascript\Test\TestNoZeroColumnHeaderNoScrollbarDateDataGrid\TestNoZeroColumnHeaderNoScrollbarDateDataGrid\ApplicationControl.cs
                  UpdateToHorizontalResizerDrag();
                  UpdateToHorizontalResizerScroll();
              };


            #region ZeroHorizontalResizerDrag Drag
            ZeroHorizontalResizerDrag.DragStart +=
                delegate
                {
                    Native.Document.body.style.cursor = DOM.IStyle.CursorEnum.move;
                    //((IHTMLElement)ZeroHorizontalResizer.firstChild).style.backgroundColor = JSColor.Blue;
                };



            ZeroHorizontalResizerDrag.DragStop +=
                 delegate
                 {
                     Native.Document.body.style.cursor = DOM.IStyle.CursorEnum.auto;
                     //((IHTMLElement)ZeroHorizontalResizer.firstChild).style.backgroundColor = this.InternalBackgroundColor.ToString();
                     //((IHTMLElement)ZeroHorizontalResizer.firstChild).style.backgroundColor = "";
                     //((IHTMLElement)ZeroHorizontalResizer.firstChild).style.backgroundColor = "yellow";

                     UpdateToHorizontalResizerDrag();
                     InternalAutoSizeWhenFill();
                 };



            ZeroHorizontalResizerDrag.DragMove +=
                delegate
                {
                    UpdateToHorizontalResizerScroll();

                };
            #endregion



            Console.WriteLine("new DataGridView() before onscroll");

            onscroll();

            #region onscroll
            this.InternalScrollContainerElement.onscroll +=
               e =>
               {
                   // onscroll is high performance.
                   // using .css will slow us down 10x?

                   var s = Stopwatch.StartNew();

                   //UpdateToVerticalResizerScroll();
                   UpdateToHorizontalResizerScroll();


                   // 153209ms DataGridView onscroll { ElapsedMilliseconds = 13 }
                   // should jsc inline for performance?
                   onscroll();

                   // 35418ms DataGridView onscroll { ElapsedMilliseconds = 20 }
                   // 234208ms DataGridView onscroll { ElapsedMilliseconds = 120 } 
                   // 10468ms DataGridView onscroll { ElapsedMilliseconds = 27 } 

                   if (s.ElapsedMilliseconds > 10)
                       Console.WriteLine("DataGridView onscroll " + new { s.ElapsedMilliseconds });

               };
            #endregion

            Console.WriteLine("new DataGridView() after onscroll");

            __DataGridViewCell MouseCaptureCell = null;

            InternalScrollContainerElement.onmouseup +=
                delegate
                {
                    MouseCaptureCell = null;
                };


            // show data fast

            // API should do the casting here of the proxyies

            // this.Height = 22;
            // 

            // set the default for all
            // are the borders getting in our way?
            //__ContentTable_css_td.style.height = "22px";
            __ContentTable_css_td.style.height = "21px";
            __ContentTable_css_td.style.lineHeight = "21px";

            // this wont work for ff, ie
            //__ContentTable_css_td.style.position = IStyle.PositionEnum.relative;




            // IE, ff workaround. need a div to play relative
            var __ContentTable_css_td_relative = __ContentTable_css_td
                + IHTMLElement.HTMLElementEnum.div;

            new IStyle(__ContentTable_css_td_relative)
            {
                position = IStyle.PositionEnum.relative,
                width = "100%",
                height = "100%"
            };


            // ready to be made interactive
            //__ContentTable_css_td_relative["[data]"].empty.first.letter.style.color = "red";
            __ContentTable_css_td_relative["[data]"].empty.style.color = "red";
            // ah a place holder?
            // X:\jsc.svn\examples\javascript\forms\Test\TestLargeDataTable\TestLargeDataTable\ApplicationControl.cs
            __ContentTable_css_td_relative[":not([data])"].empty.style.backgroundColor = "yellow";


            var __ContentTable_css_td_empty_before = __ContentTable_css_td_relative.empty.before;

            __ContentTable_css_td_empty_before.contentXAttribute = new XAttribute("data", "");

            new IStyle(__ContentTable_css_td_empty_before)
            {

                paddingLeft = "4px",
                paddingRight = "4px",

                whiteSpace = IStyle.WhiteSpaceEnum.pre,
                overflow = IStyle.OverflowEnum.hidden,
                position = IStyle.PositionEnum.absolute,
                left = "0",
                top = "0",
                bottom = "0",
                right = "0",
            };





            // X:\jsc.svn\examples\javascript\CSS\Test\CSSNewIStyle\CSSNewIStyle\Application.cs

            // http://stackoverflow.com/questions/6601697/restore-webkits-css-outline-on-input-field

            new IStyle(
                __ContentTable_css_td + IHTMLElement.HTMLElementEnum.div + IHTMLElement.HTMLElementEnum.div)
            {
                outline = "none",

                whiteSpace = IStyle.WhiteSpaceEnum.pre,
                overflow = IStyle.OverflowEnum.hidden,
                position = IStyle.PositionEnum.absolute,
                left = "0",
                top = "0",
                bottom = "0",
                right = "0"
            };


            new IStyle(__ContentTable_css_td + IHTMLElement.HTMLElementEnum.div + IHTMLElement.HTMLElementEnum.div + IHTMLElement.HTMLElementEnum.span)
            {
                marginLeft = "4px",
                marginRight = "4px",
                lineHeight = "21px",
                whiteSpace = IStyle.WhiteSpaceEnum.pre
            };

            //Console.WriteLine("new DataGridView() before InitializeMissingCell");

            #region InitializeCell
            Action<__DataGridViewCell, __DataGridViewRow> InitializeMissingCell =
                (SourceCell, SourceRow) =>
                {
                    // https://connect.microsoft.com/IE/feedback/details/687834/getcomputedstyle-doesnt-implement-2nd-argument-pseudoelt#details

                    //Console.WriteLine("InitializeCell  " + new { SourceCell.ColumnIndex });

                    // is cell index equal to column index?
                    // what happens if we dont have enough columns?
                    // https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle

                    var SourceColumn = this.InternalColumns.InternalItems[SourceCell.ColumnIndex];

                    #region InternalTableColumn
                    SourceCell.InternalTableColumn = SourceRow.InternalTableRow.AddColumn();

                    SourceRow.InternalCells.InternalItemsX.Removed +=
                         (XRemovedCell, XRemovedCellIndex) =>
                         {
                             if (XRemovedCell == SourceCell)
                             {
                                 SourceCell.InternalTableColumn.Orphanize();
                             }
                         };
                    #endregion

                    // 951ms event: dataGridView1 set DataSource { ColumnIndex = 6, SourceRowIndex = 98, ElapsedMilliseconds = 667, a = 6.737373737373737 } 


                    // this wont work if we have multiple datagrids
                    // can we have a test for it?
                    // this div is needed for UI activities?
                    // like :before

                    var InternalTableColumn_relative = new IHTMLDiv
                    {
                    }.AttachTo(SourceCell.InternalTableColumn);

                    SourceCell.InternalTableColumn_div = new IHTMLDiv
                    {
                        tabIndex = (((SourceRow.Index + 1) << 16) + (SourceCell.ColumnIndex + 1))
                    }.AttachTo(InternalTableColumn_relative);

                    SourceCell.InternalTableColumn_div_span = new IHTMLSpan
                    {
                        // unformatted
                        //innerText = (string)SourceCell.Value
                    }.AttachTo(SourceCell.InternalTableColumn_div);

                    var SourceCellType = SourceCell.GetType();
                    //Console.WriteLine(new { SourceCellType });

                    // 25:204ms { SourceCellType = <Namespace>.DataGridViewTextBoxCell } 
                    // what about checkbox? tested by.?
                    #region __DataGridViewButtonCell
                    if (SourceColumn is __DataGridViewButtonColumn)
                    {
                        var InternalButton = new IHTMLButton().AttachTo(SourceCell.InternalTableColumn_div);


                        InternalButton.style.font = this.Font.ToCssString();

                        InternalButton.style.position = IStyle.PositionEnum.absolute;
                        InternalButton.style.left = "0px";
                        InternalButton.style.top = "0px";

                        InternalButton.style.width = "100%";
                        InternalButton.style.height = "100%";

                        SourceCell.InternalTableColumn_div_span.AttachTo(InternalButton);

                        InternalButton.onclick +=
                            delegate
                            {
                                if (this.CellContentClick != null)
                                    this.CellContentClick(this,
                                        new DataGridViewCellEventArgs(SourceCell.ColumnIndex, SourceRow.Index)
                                    );
                            };

                        return;
                    }
                    #endregion


                    #region __DataGridViewButtonCell
                    if (SourceColumn is __DataGridViewCheckBoxColumn)
                    {
                        // do we already also support DataSource DataTable typeof(bool)

                        var InternalButton = new IHTMLInput
                        {
                            type = Shared.HTMLInputTypeEnum.checkbox
                        }.AttachTo(SourceCell.InternalTableColumn_div);

                        SourceCell.InternalTableColumn_div.style.textAlign = IStyle.TextAlignEnum.center;
                        SourceCell.InternalTableColumn_div.style.padding = "2px";

                        //SourceCell.InternalTableColumn_div.style.verticalAlign = "middle";


                        //InternalButton.style.font = this.Font.ToCssString();

                        //InternalButton.style.position = IStyle.PositionEnum.absolute;
                        //InternalButton.style.left = "0px";
                        //InternalButton.style.top = "0px";

                        //InternalButton.style.width = "100%";
                        //InternalButton.style.height = "100%";

                        //InternalButton.style.margin = "auto";


                        SourceCell.InternalTableColumn_div_span.Orphanize();

                        InternalButton.onclick +=
                            delegate
                            {
                                if (this.CellContentClick != null)
                                    this.CellContentClick(this,
                                        new DataGridViewCellEventArgs(SourceCell.ColumnIndex, SourceRow.Index)
                                    );
                            };

                        return;
                    }
                    #endregion


                    // with 9 , 12, 15, 12, 6
                    // without 16, 32, 27,25, 30
#if FCELLEVENTS
                    #region AtInternalValueChanged
                    Action AtInternalValueChanged = delegate
                    {
                        InternalRaiseCellFormatting(SourceCell);

                        //var innerText = SourceCell.Value.ToString();
                        var innerText = SourceCell.FormattedValue.ToString();

                        //Console.WriteLine("AtInternalValueChanged " + new { innerText });
                        SourceCell.InternalTableColumn_div_span.innerText = innerText;

                        // ?
                        InternalRaiseCellValueChanged(SourceCell);

                        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/04-monese/2014/201401/20140104-deploy
                        SourceCell.InternalTableColumn_div_span.title = SourceCell.InternalToolTipText;
                    };




                    AtInternalValueChanged();
                    SourceCell.InternalValueChanged += AtInternalValueChanged;
                    SourceCell.InternalToolTipTextChanged += AtInternalValueChanged;
                    #endregion

                    #region CellAtOffset
                    Func<int, int, __DataGridViewCell> CellAtOffset =
                        (x, y) =>
                        {
                            var value = default(__DataGridViewCell);

                            var Row = this.InternalRows.InternalItems.Source.ElementAtOrDefault(
                                SourceRow.Index + y
                            );

                            if (Row == null)
                                if (SourceRow.Index + y == this.InternalRows.Count)
                                    Row = InternalNewRow;

                            if (Row != null)
                            {
                                value = Row.InternalCells.InternalItems.ElementAtOrDefault(
                                    SourceCell.ColumnIndex + x
                                );
                            }

                            return value;
                        };
                    #endregion

                    bool ExitEditModeDone = true;

                    #region EnterEditMode
                    Action EnterEditMode =
                        delegate
                        {
                            if (this.ReadOnly)
                                return;

                            if (SourceCell.ReadOnly)
                                return;

                            if (SourceColumn.ReadOnly)
                                return;

                            if (!ExitEditModeDone)
                                return;


                            SourceCell.IsInEditMode = true;
                            ExitEditModeDone = false;

                            SourceCell.InternalTableColumn_div.Orphanize();

                            var EditElement = new IHTMLInput(Shared.HTMLInputTypeEnum.text);

                            EditElement.style.backgroundColor = "transparent";



                            EditElement.style.font = this.Font.ToCssString();


                            EditElement.style.borderWidth = "0";
                            EditElement.style.position = IStyle.PositionEnum.relative;
                            EditElement.style.left = "4px";
                            EditElement.style.top = "0";

                            EditElement.style.outline = "0";
                            EditElement.style.padding = "0";
                            EditElement.style.width = (SourceColumn.Width - 4) + "px";
                            EditElement.style.height = (SourceRow.Height - 1) + "px";

                            //EditElement.AttachTo(SourceCell.InternalTableColumn);
                            EditElement.AttachTo(InternalTableColumn_relative);

                            SourceCell.InternalStyle.InternalForeColorChanged +=
                                delegate
                                {
                                    EditElement.style.color = SourceCell.InternalStyle.InternalForeColor.ToString();
                                };

                            var OriginalValue = (string)SourceCell.Value;
                            EditElement.value = OriginalValue;


                            #region CheckChanges
                            Action CheckChanges = delegate
                            {
                                //if (((string)SourceCell.Value) != EditElement.value)
                                //{

                                var args = new __DataGridViewCellValidatingEventArgs(
                                    SourceCell.ColumnIndex,
                                     SourceRow.Index
                                )
                                {

                                    FormattedValue = EditElement.value
                                };

                                // tested by
                                // X:\jsc.svn\examples\javascript\forms\FormsDataGridViewDeleteRow\FormsDataGridViewDeleteRow\ApplicationControl.cs
                                if (this.CellValidating != null)
                                    this.CellValidating(this, (DataGridViewCellValidatingEventArgs)(object)args);

                                //Console.WriteLine("CellValidating " + new { args.Cancel });

                                if (args.Cancel)
                                {
                                    //Console.WriteLine("CellValidating Cancel " + new { OriginalValue });
                                    SourceCell.Value = OriginalValue;

                                    return;
                                }


                                SourceCell.Value = EditElement.value;

                                //}

                            };
                            #endregion

                            #region ExitEditMode
                            Action ExitEditMode = delegate
                            {
                                if (ExitEditModeDone) return;
                                ExitEditModeDone = true;
                                SourceCell.IsInEditMode = false;


                                EditElement.Orphanize();
                                SourceCell.InternalTableColumn_div.AttachTo(InternalTableColumn_relative);

                                //SourceCell.InternalStyle.InternalForeColorChanged +=
                                //    delegate
                                //    {
                                //        SourceCell.InternalContentContainer.style.color = SourceCell.InternalStyle.InternalForeColor.ToString();
                                //    };

                                //SourceCell.InternalContentContainer.style.backgroundColor = SourceCell.InternalStyle.InternalBackColor.ToString();


                                InternalRaiseCellEndEdit(SourceCell);

                                if (OriginalValue == (string)SourceCell.Value)
                                    return;

                                this.AutoResizeColumn(SourceCell.ColumnIndex);

                                //InternalRaiseCellFormatting(SourceCell);

                                Console.WriteLine("ExitEditMode AtInternalValueChanged");
                                AtInternalValueChanged();
                            };
                            #endregion



                            #region CellBeginEdit
                            EditElement.onfocus +=
                                delegate
                                {

                                    EditElement.select();
                                };
                            EditElement.focus();

                            InternalRaiseCellFormatting(SourceCell);

                            InternalRaiseCellBeginEdit(SourceCell);

                            #endregion


                            #region onblur
                            EditElement.onblur +=
                               delegate
                               {
                                   //Console.WriteLine("EditElement.onblur");

                                   if (CheckChanges != null)
                                       CheckChanges();

                                   if (ExitEditMode != null)
                                       ExitEditMode();


                               };
                            #endregion


                            var __selectionStart = -1;
                            var __selectionEnd = -1;
                            #region onkeyup
                            EditElement.onkeyup +=
                              _ev =>
                              {
                                  #region Focus
                                  Action<__DataGridViewCell> Focus =
                                      Cell =>
                                      {
                                          _ev.preventDefault();
                                          _ev.stopPropagation();

                                          if (Cell != null)
                                          {
                                              Cell.InternalTableColumn_div.focus();
                                          }
                                      };
                                  #endregion

                                  if (_ev.IsEscape)
                                  {
                                      CheckChanges = null;

                                      ExitEditMode();

                                      Focus(SourceCell);
                                      return;
                                  }

                                  if (_ev.KeyCode == (int)Keys.Up)
                                  {
                                      Focus(CellAtOffset(0, -1));
                                      return;
                                  }

                                  if (_ev.KeyCode == (int)Keys.Down)
                                  {
                                      Focus(CellAtOffset(0, 1));
                                      return;
                                  }

                                  if (_ev.KeyCode == (int)Keys.Right)
                                      if (EditElement.selectionStart == __selectionStart)
                                          if (EditElement.selectionEnd == __selectionEnd)
                                              if (__selectionEnd == __selectionStart)
                                                  if (__selectionStart == EditElement.value.Length)
                                                  {
                                                      Focus(CellAtOffset(1, 0));
                                                      return;
                                                  }

                                  if (_ev.KeyCode == (int)Keys.Left)
                                      if (EditElement.selectionStart == __selectionStart)
                                          if (EditElement.selectionEnd == __selectionEnd)
                                              if (__selectionEnd == __selectionStart)
                                                  if (__selectionStart == 0)
                                                  {
                                                      Focus(CellAtOffset(-1, 0));
                                                      return;
                                                  }

                                  __selectionEnd = EditElement.selectionEnd;
                                  __selectionStart = EditElement.selectionStart;
                              };
                            #endregion


                            #region onkeypress
                            EditElement.onkeypress +=
                                _ev =>
                                {

                                    if (_ev.IsReturn)
                                    {
                                        _ev.preventDefault();
                                        _ev.stopPropagation();

                                        if (CheckChanges != null)
                                            CheckChanges();

                                        ExitEditMode();
                                        SourceCell.InternalTableColumn_div.focus();

                                    }

                                };
                            #endregion



                        };
                    #endregion

                    #region InternalContentContainer ondblclick
                    SourceCell.InternalTableColumn_div.ondblclick +=
                        ev =>
                        {

                            ev.stopPropagation();
                            ev.preventDefault();

                            if (this.CellDoubleClick != null)
                                this.CellDoubleClick(
                                    this, new DataGridViewCellEventArgs(SourceColumn.Index, SourceRow.Index)
                                );

                            EnterEditMode();


                        };
                    #endregion

                    #region InternalContentContainer android has long taps

                    var TouchstartWatch = new Stopwatch();

                    SourceCell.InternalTableColumn_div.ontouchstart +=
                        delegate
                        {
                            Console.WriteLine("SourceCell.InternalContentContainer.ontouchstart");
                            TouchstartWatch.Restart();
                        };

                    SourceCell.InternalTableColumn_div.ontouchend +=
                        delegate
                        {
                            Console.WriteLine("SourceCell.InternalContentContainer.ontouchend");

                            if (TouchstartWatch.ElapsedMilliseconds > 300)
                            {
                                if (this.CellDoubleClick != null)
                                    this.CellDoubleClick(
                                        this, new DataGridViewCellEventArgs(SourceColumn.Index, SourceRow.Index)
                                    );

                                EnterEditMode();
                            }

                            // script: error JSC1000: No implementation found for this native method, please implement [System.Diagnostics.Stopwatch.Reset()]
                            //TouchstartWatch.Reset();

                            TouchstartWatch = new Stopwatch();
                        };
                    #endregion

                    #region InternalContentContainer onmousedown
                    SourceCell.InternalTableColumn_div.onmousedown +=
                        ev =>
                        {
                            MouseCaptureCell = SourceCell;

                            ev.preventDefault();

                            if (SourceCell.Selected)
                                EnterEditMode();
                            else
                                SourceCell.InternalTableColumn_div.focus();
                        };
                    #endregion

                    #region InternalContentContainer onmousemove
                    SourceCell.InternalTableColumn_div.onmousemove +=
                         ev =>
                         {
                             if (MouseCaptureCell == null) return;

                             if (!this.MultiSelect)
                             {
                                 MouseCaptureCell = SourceCell;
                                 ev.preventDefault();
                                 SourceCell.InternalTableColumn_div.focus();
                                 return;
                             }


                             if (ev.MouseButton == IEvent.MouseButtonEnum.Left)
                             {
                                 if (!this.InternalSelectedCells.Contains(SourceCell))
                                     this.InternalSelectedCells.Add(SourceCell);

                                 ev.preventDefault();
                             }
                         };
                    #endregion

                    #region InternalContentContainer onmouseup


                    SourceCell.InternalTableColumn_div.onmouseup +=
                        ev =>
                        {
                            if (MouseCaptureCell == null)
                                return;

                            MouseCaptureCell = null;

                            if (!ev.ctrlKey)
                                if (ev.MouseButton == IEvent.MouseButtonEnum.Left)
                                {
                                    ev.preventDefault();

                                    if (this.CellClick != null)
                                        this.CellClick(this, new DataGridViewCellEventArgs(SourceCell.ColumnIndex, SourceRow.Index));



                                    SourceCell.InternalTableColumn_div.focus();

                                }
                        };
                    #endregion

                    #region InternalContentContainer onkeydown
                    SourceCell.InternalTableColumn_div.onkeydown +=
                        ev =>
                        {

                            #region KeyNavigateTo
                            Func<Keys, int, int, bool> KeyNavigateTo =
                              (k, x, y) =>
                              {
                                  if (ev.KeyCode == (int)k)
                                  {
                                      // focus the cell on the right

                                      ev.preventDefault();
                                      ev.stopPropagation();

                                      var Cell = CellAtOffset(x, y);
                                      if (Cell != null)
                                      {
                                          Cell.InternalTableColumn_div.focus();
                                          return true;
                                      }



                                  }
                                  return false;
                              };
                            #endregion

                            #region FullRowSelect Delete
                            if (this.SelectionMode == DataGridViewSelectionMode.FullRowSelect)
                            {
                                if (ev.KeyCode == (int)Keys.Delete)
                                {
                                    if (SourceRow == InternalNewRow)
                                        return;

                                    if (!this.InternalAllowUserToDeleteRows)
                                        return;


                                    // tested by
                                    // X:\jsc.svn\examples\javascript\forms\FormsDataGridViewDeleteRow\FormsDataGridViewDeleteRow\ApplicationControl.cs


                                    // script: error JSC1000: No implementation found for this native method, please implement [System.Windows.Forms.DataGridViewRowCollection.Remove(System.Windows.Forms.DataGridViewRow)]

                                    var Cell = CellAtOffset(0, 1);


                                    if (this.InternalBeforeUserDeletedRow != null)
                                        this.InternalBeforeUserDeletedRow(
                                            this,
                                            new DataGridViewRowEventArgs(SourceRow)
                                        );

                                    this.Rows.Remove(SourceRow);

                                    if (this.UserDeletedRow != null)
                                        this.UserDeletedRow(
                                            this,
                                            new DataGridViewRowEventArgs(SourceRow)
                                        );


                                    if (Cell != null)
                                    {
                                        Cell.InternalTableColumn_div.focus();
                                    }



                                    return;
                                }
                            }
                            #endregion



                            if (KeyNavigateTo(Keys.Right, 1, 0)) return;
                            if (KeyNavigateTo(Keys.Left, -1, 0)) return;
                            if (KeyNavigateTo(Keys.Up, 0, -1)) return;
                            if (KeyNavigateTo(Keys.Down, 0, 1)) return;

                            if (ev.IsReturn)
                            {
                                ev.preventDefault();
                                ev.stopPropagation();

                                EnterEditMode();
                                return;
                            }

                            if (ev.KeyCode == (int)Keys.Space)
                            {
                                EnterEditMode();
                                return;
                            }

                            if (char.IsLetter((char)ev.KeyCode))
                            {
                                EnterEditMode();
                                return;
                            }

                            if (char.IsNumber((char)ev.KeyCode))
                            {
                                EnterEditMode();
                                return;
                            }



                        };
                    #endregion

                    #region InternalContentContainer onblur
                    SourceCell.InternalTableColumn_div.onblur +=
                        //SourceCell.InternalTableColumn.onblur +=
                        ev =>
                        {
                            SourceCell.InternalSetSelected(false);

                            if (!ev.ctrlKey)
                            {
                                // clear
                                while (this.InternalSelectedCells.Count > 0)
                                {
                                    var item = this.InternalSelectedCells.InternalItems[0];

                                    //item.InternalContentContainer.style.backgroundColor = item.InternalStyle.InternalBackColor.ToString();
                                    item.InternalTableColumn_div.style.backgroundColor = "";
                                    item.InternalTableColumn_div.style.color = item.InternalStyle.InternalForeColor.ToString();

                                    this.InternalSelectedCells.RemoveAt(0);
                                }

                            }

                            if (this.CellLeave != null)
                                this.CellLeave(this, new DataGridViewCellEventArgs(SourceCell.ColumnIndex, SourceRow.Index));

                        };
                    #endregion

                    #region InternalContentContainer onfocus
                    SourceCell.InternalTableColumn_div.onfocus +=
                        //SourceCell.InternalTableColumn.onfocus +=
                        ev =>
                        {
                            SourceCell.InternalSetSelected(true);

                            ev.preventDefault();
                            ev.stopPropagation();


                            if (this.CellEnter != null)
                                this.CellEnter(
                                    this,
                                    new DataGridViewCellEventArgs(SourceCell.ColumnIndex, SourceRow.Index)
                                );

                            {
                                var NewSelectedCell = SourceCell;

                                if (!this.InternalSelectedCells.Contains(NewSelectedCell))
                                    this.InternalSelectedCells.Add(NewSelectedCell);
                            }

                            if (this.SelectionMode == DataGridViewSelectionMode.FullRowSelect)
                            {
                                // tested by
                                // X:\jsc.svn\examples\javascript\forms\FormsDataGridRowSelect\FormsDataGridRowSelect\ApplicationControl.cs

                                foreach (var NewSelectedCell in SourceRow.InternalCells.InternalItems)
                                {

                                    if (!this.InternalSelectedCells.Contains(NewSelectedCell))
                                        this.InternalSelectedCells.Add(NewSelectedCell);
                                }

                            }

                        };
                    #endregion

                    InternalBindCellMouseEnter(SourceCell);

                    #region InternalContentContainer Font
                    SourceCell.InternalTableColumn_div.style.font = SourceCell.InternalStyle.Font.ToCssString();
                    SourceCell.InternalStyle.InternalFontChanged +=
                        delegate
                        {
                            if (SourceCell.Selected)
                                return;


                            SourceCell.InternalTableColumn_div.style.font = SourceCell.InternalStyle.Font.ToCssString();

                            if (SourceCell.InternalStyle.InternalFont.Underline)
                                SourceCell.InternalTableColumn_div.style.textDecoration = "underline";
                            else
                                SourceCell.InternalTableColumn_div.style.textDecoration = "";
                        };
                    #endregion

                    // need to move this to css
                    //#region InternalContentContainer InternalForeColorChanged
                    //SourceCell.InternalTableColumn_div.style.color = SourceCell.InternalStyle.InternalForeColor.ToString();
                    //SourceCell.InternalStyle.InternalForeColorChanged +=
                    //   delegate
                    //   {
                    //       if (SourceCell.Selected)
                    //           return;


                    //       SourceCell.InternalTableColumn_div.style.color = SourceCell.InternalStyle.InternalForeColor.ToString();
                    //   };
                    //#endregion

                    if (SourceCell.InternalStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
                        SourceCell.InternalTableColumn_div.style.textAlign = IStyle.TextAlignEnum.right;
#endif

                };
            #endregion

            #region CreateMissingCells
            Action<__DataGridViewRow> CreateMissingCells =
                SourceRow =>
                {
                    //Console.WriteLine("CreateMissingCells  " + new
                    //{
                    //    SourceRow.Index,
                    //    CellsCount = SourceRow.InternalCells.InternalItems.Count,
                    //    ColumnsCount = this.InternalColumns.InternalItems.Count


                    //});

                    #region defaults
                    while (SourceRow.InternalCells.InternalItems.Count < this.InternalColumns.InternalItems.Count)
                    {
                        var ColumnIndex = SourceRow.InternalCells.Count;

                        //Console.WriteLine("CreateMissingCells  " + new { SourceRow.Index, ColumnIndex });

                        var __c = this.InternalColumns.InternalItems[ColumnIndex];

                        __DataGridViewCell SourceCell = null;


                        if (__c is __DataGridViewButtonColumn)
                        {
                            //Console.WriteLine("CreateMissingCells __DataGridViewButtonColumn " + new { SourceRow.Index, ColumnIndex });

                            SourceCell = new __DataGridViewButtonCell();
                        }
                        else if (__c is __DataGridViewCheckBoxColumn)
                        {
                            //Console.WriteLine("CreateMissingCells ? " + new { SourceRow.Index, ColumnIndex });

                            // X:\jsc.svn\examples\javascript\forms\Test\TestButtonColumn\TestButtonColumn\ApplicationControl.cs
                            SourceCell = new __DataGridViewCheckBoxCell();

                        }
                        else
                        {
                            //Console.WriteLine("CreateMissingCells ? " + new { SourceRow.Index, ColumnIndex });

                            SourceCell = new __DataGridViewTextBoxCell();
                        }

                        SourceRow.InternalCells.InternalItems.Add(SourceCell);


                    }
                    #endregion


                    //29:295ms CreateMissingCells  { Index = 0, CellsCount = 5, ColumnsCount = 1 }
                    //29:296ms what if SourceRow has more columns than the table? { i = 0 }
                    //29:298ms what if SourceRow has more columns than the table? { i = 1 }

                    for (int i = 0; i < SourceRow.InternalCells.InternalItems.Count; i++)
                    {
                        //Console.WriteLine("what if SourceRow has more columns than the table? " + new { i });

                        // X:\jsc.svn\examples\javascript\forms\FormsHistoricBindingSourcePosition\FormsHistoricBindingSourcePosition\ApplicationControl.cs
                        // SourceRow has more columns? bail? are we showing the correct columns?
                        if (i == this.Columns.Count)
                            break;

                        var SourceColumn = this.InternalColumns.InternalItems[i];
                        var SourceCell = SourceRow.InternalCells.InternalItems[i];

                        if (SourceCell.InternalTableColumn == null)
                        {
                            InitializeMissingCell(
                                SourceCell,
                                SourceRow
                            );
                        }

                        SourceColumn.InternalDefaultCellStyleChanged +=
                            delegate
                            {
                                if (SourceColumn.DefaultCellStyle != null)
                                {
                                    SourceCell.Style.ForeColor = SourceColumn.DefaultCellStyle.ForeColor;
                                    //SourceCell.Style.BackColor = SourceColumn.DefaultCellStyle.BackColor;
                                }
                            };

                        //((__DataGridViewCellStyle)SourceRow.DefaultCellStyle).InternalBackColorChanged +=
                        //    delegate
                        //    {
                        //        // when row style is changed, who overriddes who?
                        //        //SourceCell.Style.BackColor = SourceRow.DefaultCellStyle.BackColor;
                        //    };

                        if (SourceColumn.DefaultCellStyle != null)
                        {
                            SourceCell.Style.ForeColor = SourceColumn.DefaultCellStyle.ForeColor;
                            //SourceCell.Style.BackColor = SourceColumn.DefaultCellStyle.BackColor;
                        }


                    }


                };
            #endregion


            (__ColumnsTableRow.css + IHTMLElement.HTMLElementEnum.div).style.position = IStyle.PositionEnum.relative;

            Console.WriteLine("new DataGridView() before InternalColumns");

            #region InternalColumns
            this.InternalColumns.InternalItemsX.Removed +=
                (SourceColumn, NewIndex) =>
                {
                    foreach (var SourceRow in this.InternalRows.InternalItems.Source)
                    {
                        SourceRow.Cells.RemoveAt(NewIndex);
                    }

                    SourceColumn.InternalTableColumn.Orphanize();

                    SourceColumn.ColumnHorizontalResizer.Orphanize();
                };

            this.InternalColumns.InternalItemsX.Added +=
                (SourceColumn, NewIndex) =>
                {
                    // jsc why is this function slow?

                    //var SourceColumn = this.InternalColumns.InternalItems[_e.NewIndex];

                    var SourceColumnStopwatch = Stopwatch.StartNew();
                    // 1250ms { Name = dataGridView1 } InternalColumns Added { Index = 29, SourceColumnStopwatch = 41 } 

                    SourceColumn.InternalContext = this;

                    //Console.WriteLine(
                    //    new { this.Name }
                    //    + " InternalColumns Added " + new { SourceColumn.Index });


                    //if (c is __DataGridViewButtonColumn)
                    //    Console.WriteLine("InternalColumns __DataGridViewButtonColumn ItemAdded " + new { _e.NewIndex });
                    //else
                    //    Console.WriteLine("InternalColumns ? ItemAdded " + new { _e.NewIndex });


                    SourceColumn.InternalTableColumn = __ColumnsTableRow.AddColumn();

                    // move to .css
                    //SourceColumn.InternalTableColumn.style.position = IStyle.PositionEnum.relative;

                    if (this.InternalRows.Count > 0)
                        foreach (var SourceRow in this.InternalRows.InternalItems.Source)
                        {
                            CreateMissingCells(SourceRow);
                        }


                    #region c1contentcrel, move to css + :before?
                    var c1contentcrel = new IHTMLDiv { }.AttachTo(SourceColumn.InternalTableColumn);
                    c1contentcrel.style.position = IStyle.PositionEnum.relative;
                    c1contentcrel.style.left = "0";
                    c1contentcrel.style.top = "0";
                    c1contentcrel.style.right = "0";
                    c1contentcrel.style.height = "22px";

                    var c1contentc = new IHTMLDiv { }.AttachTo(c1contentcrel);
                    c1contentc.style.overflow = IStyle.OverflowEnum.hidden;
                    c1contentc.style.position = IStyle.PositionEnum.absolute;
                    c1contentc.style.left = "0";
                    c1contentc.style.top = "0";
                    c1contentc.style.right = "0";
                    c1contentc.style.height = "22px";


                    var c1content = new IHTMLSpan { innerText = SourceColumn.HeaderText }.AttachTo(c1contentc);
                    SourceColumn.InternalContent = c1content;
                    c1content.style.marginLeft = "4px";

                    // tested by
                    // X:\jsc.svn\examples\javascript\forms\TTFCurrencyExperment\TTFCurrencyExperment\ApplicationControl.cs

#if FHR
                    c1content.style.font = this.Font.ToCssString();

                    // ? we should use .css here
                    this.FontChanged +=
                        delegate
                        {
                            c1content.style.font = this.Font.ToCssString();
                        };
#endif

                    c1content.style.lineHeight = "22px";
                    #endregion


                    SourceColumn.InternalHeaderTextChanged +=
                        delegate
                        {
                            // would we be better off using :after:content attr()
                            c1content.innerText = SourceColumn.HeaderText;
                        };



                    // setting the size for the headers on top

                    //Console.WriteLine("before SourceColumnWidth_css");
                    var SourceColumnWidth_css = default(CSSStyleRuleMonkier);

                    if (SourceColumn.Index == -1)
                    {
                        // scoped style?

                        SourceColumnWidth_css =
                            this.__RowsTable_css;


                    }
                    else
                    {
                        SourceColumnWidth_css =
                                          this.__ColumnsTable_css_td[SourceColumn.Index] |
                                          this.__ColumnsTable_css_td[SourceColumn.Index][IHTMLElement.HTMLElementEnum.div] |
                                          this.__ContentTable_css_td[SourceColumn.Index] |
                                          this.__ContentTable_css_td[SourceColumn.Index][IHTMLElement.HTMLElementEnum.div];
                    }



                    #region AtInternalWidthChanged
                    Action AtInternalWidthChanged =
                        delegate
                        {
                            var SourceColumnWidthStopwatch = Stopwatch.StartNew();
                            var SourceColumnWidth = SourceColumn.Width;

                            // tested by
                            // X:\jsc.svn\examples\javascript\forms\Test\TestGrowingGrid\TestGrowingGrid\ApplicationControl.cs
                            // X:\jsc.svn\examples\javascript\forms\Test\TestFlowDataGridPadding\TestFlowDataGridPadding\Application.cs

                            // update the designer style
                            SourceColumnWidth_css.style.width = SourceColumnWidth + "px";
                            //// table wants to squeeshe the columns, prevent it


                            if (this.ColumnWidthChanged != null)
                                this.ColumnWidthChanged(this,
                                    new DataGridViewColumnEventArgs(SourceColumn)
                                   );

                            //  AtInternalWidthChanged { ElapsedMilliseconds = 0 } 
                            if (SourceColumnWidthStopwatch.ElapsedMilliseconds > 10)
                                Console.WriteLine("AtInternalWidthChanged " + new { SourceColumnWidthStopwatch.ElapsedMilliseconds });
                        };

                    SourceColumn.InternalWidthChanged += AtInternalWidthChanged;
                    AtInternalWidthChanged();
                    #endregion

                    // should jsc record the last current method before entering console writeline?
                    //Console.WriteLine(
                    //   new { this.Name }
                    //   + " InternalColumns Added step 2");
#if FHR
                    #region InternalVisibleChanged

                    //Console.WriteLine("before SourceColumnVisible__ColumnsTable_css");
                    var SourceColumnVisible__ColumnsTable_css = (__ColumnsTable_css
                     + IHTMLElement.HTMLElementEnum.tbody
                     + IHTMLElement.HTMLElementEnum.tr
                     + IHTMLElement.HTMLElementEnum.td)
                     [NewIndex];
                    //Console.WriteLine("after SourceColumnVisible__ColumnsTable_css");


                    //Console.WriteLine("before SourceColumnVisible__ContentTable_css");
                    var SourceColumnVisible__ContentTable_css = (
                        __ContentTable_css
                            + IHTMLElement.HTMLElementEnum.tbody
                          + IHTMLElement.HTMLElementEnum.tr
                         + IHTMLElement.HTMLElementEnum.td
                     )
                     [NewIndex];
                    //Console.WriteLine("after SourceColumnVisible__ContentTable_css");

                    // xattribute instead?
                    var SourceColumnVisible_css = SourceColumnVisible__ColumnsTable_css | SourceColumnVisible__ContentTable_css;

                    SourceColumn.InternalVisibleChanged +=
                        delegate
                        {
                            if (SourceColumn.Visible)
                                SourceColumnVisible_css.style.display = IStyle.DisplayEnum.empty;
                            else
                                SourceColumnVisible_css.style.display = IStyle.DisplayEnum.none;
                        };
                    #endregion

                    #region ColumnHorizontalResizer CreateHorizontalResizer
                    // should we delay this until resize is enabled?

                    //Console.WriteLine("before CreateHorizontalResizer");

                    SourceColumn.ColumnHorizontalResizer = new IHTMLDiv { className = "HorizontalResizer" };
                    // what about older rules?
                    // shall they stop existing once the new once is used?

                    //Console.WriteLine("before CreateHorizontalResizer onscroll");
                    //onscroll();

                    //Console.WriteLine("after CreateHorizontalResizer");

                    SourceColumn.ColumnHorizontalResizer.AttachTo(InternalElement);
                    //__ColumnsTableContainer.insertNextSibling(SourceColumn.ColumnHorizontalResizer);

                    var ColumnHorizontalResizerDrag = new DragHelper(SourceColumn.ColumnHorizontalResizer)
                    {
                        Enabled = true
                    };

                    SourceColumn.InternalHorizontalDrag = ColumnHorizontalResizerDrag;
                    #endregion


                    #region ColumnUpdateToHorizontalResizerScroll left
                    Action ColumnUpdateToHorizontalResizerScroll = delegate
                    {
                        var x = ColumnHorizontalResizerDrag.Position.X;

                        SourceColumn.ColumnHorizontalResizer.style.left = x + "px";
                    };
                    #endregion

                    #region ColumnUpdateToHorizontalResizerScroll
                    // do we need this?
                    //this.InternalRows.InternalItems.Added +=
                    //    delegate
                    //    {
                    //        this.HTMLTargetRef.requestAnimationFrame +=
                    //            delegate
                    //            {
                    //                ColumnUpdateToHorizontalResizerScroll();
                    //            };

                    //    };

                    this.InternalAtAfterVisibleChanged +=
                        delegate
                        {
                            this.HTMLTargetRef.requestAnimationFrame +=
                                delegate
                                {
                                    ColumnUpdateToHorizontalResizerScroll();
                                };

                        };
                    #endregion

                    #region CompensateFor ZeroHorizontalResizerDrag DragStop
                    Action<DragHelper> CompensateFor =
                        Target =>
                        {
                            var __X = 0;
                            Target.DragStart +=
                                delegate
                                {
                                    __X = Target.Position.X;
                                };

                            Target.DragStop +=
                                delegate
                                {
                                    ColumnHorizontalResizerDrag.Position.X +=
                                        Target.Position.X - __X;

                                    ColumnUpdateToHorizontalResizerScroll();
                                };
                        };

                    CompensateFor(ZeroHorizontalResizerDrag);
                    #endregion

                    #region Reposition
                    Action Reposition =
                        delegate
                        {
                            var RepositionStopwatch = Stopwatch.StartNew();


                            var x = ZeroHorizontalResizerDrag.Position.X - 1;

                            if (!this.RowHeadersVisible)
                            {
                                x = -4;
                            }

                            x -= this.InternalScrollContainerElement.scrollLeft;

                            for (int i = 0; i <= NewIndex; i++)
                            {
                                //x += this.InternalColumns.InternalItems[i].Width;

                                var CandidateColumn = this.InternalColumns.InternalItems[i];


                                // X:\jsc.svn\examples\javascript\forms\Test\TestDataGridPadding\TestDataGridPadding\ApplicationControl.cs
                                if (CandidateColumn.Visible)
                                    x += CandidateColumn.Width + 1;
                            }

                            ColumnHorizontalResizerDrag.Position = new Point(x, 0);

                            ColumnUpdateToHorizontalResizerScroll();

                            // what takes here half a sec?
                            // 1737ms event: Reposition { Index = 0, ElapsedMilliseconds = 447 } 

                            // report slow. 60 is the new slow
                            //if (RepositionStopwatch.ElapsedMilliseconds > 10)
                            if (RepositionStopwatch.ElapsedMilliseconds > 60)
                                Console.WriteLine("reposition " + new { SourceColumn.Index, RepositionStopwatch.ElapsedMilliseconds });
                        };

                    // are we adding columns in bulk? cant have reflow yet
                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140205
                    if (!InternalDataSourceBusy)
                        Reposition();


                    this.InternalScrollContainerElement.onscroll +=
                      e =>
                      {
                          Reposition();
                      };

                    // tested by
                    // X:\jsc.svn\examples\javascript\Test\TestNoZeroColumnHeaderNoScrollbarDateDataGrid\TestNoZeroColumnHeaderNoScrollbarDateDataGrid\ApplicationControl.cs
                    InternalRowHeadersVisibleChanged +=
                       delegate
                       {
                           Reposition();
                       };

                    for (int i = 0; i <= NewIndex; i++)
                    {
                        var item = this.InternalColumns.InternalItems[i];

                        item.InternalWidthChanged +=
                            delegate
                            {
                                if (InternalDataSourceBusy)
                                    return;

                                Reposition();

                            };
                    }
                    #endregion

                    #region ColumnHorizontalResizerDrag DragStart
                    var __DragStartX = 0;

                    ColumnHorizontalResizerDrag.DragStart +=
                        delegate
                        {

                            Native.Document.body.style.cursor = DOM.IStyle.CursorEnum.move;
                            //((IHTMLElement)SourceColumn.ColumnHorizontalResizer.firstChild).style.backgroundColor = JSColor.Blue;

                            __DragStartX = ColumnHorizontalResizerDrag.Position.X;
                        };

                    ColumnHorizontalResizerDrag.DragStop +=
                            delegate
                            {
                                //                                 { Width = 115, cwidth = 1045 } view-source:27892

                                // view-source:27892
                                //{ Width = 1045, cwidth = 1975 } 

                                Native.Document.body.style.cursor = DOM.IStyle.CursorEnum.auto;
                                //((IHTMLElement)SourceColumn.ColumnHorizontalResizer.firstChild).style.backgroundColor = this.InternalBackgroundColor.ToString();
                                //((IHTMLElement)SourceColumn.ColumnHorizontalResizer.firstChild).style.backgroundColor = "";
                                //((IHTMLElement)SourceColumn.ColumnHorizontalResizer.firstChild).style.backgroundColor = "yellow";
                                //SourceColumn.ColumnHorizontalResizer.style.backgroundColor = "red";

                                var ColumnHorizontalResizerDragNewValue = SourceColumn.Width + ColumnHorizontalResizerDrag.Position.X - __DragStartX;
                                Console.WriteLine(new { SourceColumn.Width, ColumnHorizontalResizerDragNewValue });

                                SourceColumn.Width = ColumnHorizontalResizerDragNewValue;
                                InternalAutoSizeWhenFill();
                            };


                    ColumnHorizontalResizerDrag.DragMove +=
                        delegate
                        {
                            ColumnUpdateToHorizontalResizerScroll();

                        };
                    #endregion


                    #region ColumnHorizontalResizer ondblclick AutoResizeColumn
                    SourceColumn.ColumnHorizontalResizer.onmousedown +=
                        e =>
                        {
                            if (e.MouseButton == IEvent.MouseButtonEnum.Middle)
                            {
                                e.preventDefault();
                                e.stopPropagation();

                                this.AutoResizeColumn(SourceColumn.Index, ObeyAutoSizeMode: false);
                                InternalAutoSizeWhenFill();

                            }
                        };

                    SourceColumn.ColumnHorizontalResizer.ondblclick +=
                        delegate
                        {
                            this.AutoResizeColumn(SourceColumn.Index, ObeyAutoSizeMode: false);
                            InternalAutoSizeWhenFill();
                        };
                    #endregion
#endif

                    bool InternalAutoResizeColumnBuzy = false;

                    #region InternalAutoResizeColumn

                    //Console.WriteLine("add InternalAutoResizeColumn");
                    this.InternalAutoResizeColumn +=
                        (SourceColumnIndex, ObeyAutoSizeMode) =>
                        {
                            //Console.WriteLine("at InternalAutoResizeColumn");

                            if (InternalAutoResizeColumnBuzy)
                                return;


                            if (SourceColumnIndex != SourceColumn.Index)
                                return;

                            var rows = this.InternalRows.InternalItems.Source;

                            var InternalAutoResizeColumnStopwatch = Stopwatch.StartNew();

                            // InternalAutoSize { Count = 33, cindex = -1 }
                            //Console.WriteLine(
                            //    new { this.Name }
                            //    + " InternalAutoResizeColumn "
                            //    + new
                            //    {
                            //        RowCount = rows.Count,
                            //        SourceColumnIndex,

                            //        // are we even supposed to do autoresize?
                            //        SourceColumn.AutoSizeMode
                            //    }
                            //);



                            #region Fill last column
                            if (this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill)
                            {
                                var FillColumn = InternalGetVisibleColumns().LastOrDefault();

                                if (FillColumn != null)
                                    if (SourceColumnIndex == FillColumn.Index)
                                    {
                                        //Console.WriteLine("InternalAutoResizeColumn " + new { FillColumn.Index, FillColumn.Name });

                                        //SourceColumn.le
                                        var SourceColumnLeft = InternalGetVisibleColumns()
                                            .Where(c => c.Index < FillColumn.Index)
                                            .Select(c => c.Width)
                                            .Sum();

                                        var ZeroRight = (ZeroHorizontalResizerDrag.Position.X + 4);


                                        // X:\jsc.svn\examples\javascript\forms\FormsHistoricBindingSourcePosition\FormsHistoricBindingSourcePosition\ApplicationControl.cs
                                        // tested by?
                                        if (!this.RowHeadersVisible)
                                        {
                                            // we are missing the left border!
                                            SourceColumnLeft = 0;
                                            ZeroRight = -4;
                                        }


                                        // { cindex = 0, w = 0, all = 1600, WidthByFill = 1600 } 

                                        var all = this.InternalScrollContainerElement.clientWidth;

                                        var WidthByFill = all - SourceColumnLeft - ZeroRight - 5;

                                        WidthByFill -= 1;

                                        //Console.WriteLine(
                                        //    " InternalAutoResizeColumn Fill "
                                        //    + new
                                        //    {
                                        //        SourceColumnIndex,
                                        //        SourceColumnLeft,
                                        //        value = ZeroRight,
                                        //        all,
                                        //        WidthByFill
                                        //    }

                                        //    );

                                        //{ cindex = 0, w = 0, value = 99, all = 753, WidthByFill = 654 } 

#if FHR
                                        __DragStartX = ColumnHorizontalResizerDrag.Position.X + (WidthByFill - SourceColumn.Width);
#endif

                                        InternalAutoResizeColumnBuzy = true;
                                        SourceColumn.Width = Math.Max(20, WidthByFill);
                                        InternalAutoResizeColumnBuzy = false;

                                        return;
                                    }
                            }
                            #endregion



                            if (SourceColumnIndex < 0)
                                return;

                            if (SourceColumn.AutoSizeMode == DataGridViewAutoSizeColumnMode.None)
                            {
                                if (ObeyAutoSizeMode)
                                    return;
                            }


                            //Console.WriteLine("before max");
                            #region SetColumnWidth

                            //1268ms before max view-source:35829
                            //1707ms after max 

                            // we should only look at currently visible rows?
                            var WidthByRowsInThisColumn = rows.Take(16).Max(
                                rr =>
                                {
                                    //1774ms at rr view-source:35829
                                    //2273ms at rr 

                                    //Console.WriteLine("enter rr");

                                    //                                    33736ms before max view-source:35829
                                    //33736ms enter rr view-source:35829
                                    //34202ms exit rr { value = 228 } 

                                    __DataGridViewCell cc = rr.Cells[SourceColumnIndex];

                                    //Console.WriteLine("got cc");

                                    //Console.WriteLine("InternalAutoSize " + new { rows.Count, cindex, cc.InternalContent.offsetWidth });

                                    //2717ms got cc view-source:35829
                                    //3165ms exit rr { value = 228 } 

                                    var s = Stopwatch.StartNew();

                                    // !!! accessing DOM is expensive!
                                    var value = cc.InternalTableColumn_div_span.offsetWidth;

                                    //2717ms got cc view-source:35829
                                    //3165ms exit rr { value = 228 } 

                                    if (s.ElapsedMilliseconds > 10)
                                        Console.WriteLine("got offsetWidth in " + new { s.ElapsedMilliseconds });

                                    return value;
                                }
                            );
                            //Console.WriteLine("after max");


                            WidthByRowsInThisColumn = Math.Max(WidthByRowsInThisColumn, this.InternalColumns.InternalItems[SourceColumnIndex].InternalContent.offsetWidth);
                            if (WidthByRowsInThisColumn == 0)
                            {
                                // no DOM?
                                //Console.WriteLine("InternalAutoSize skipped");
                                return;
                            }

                            // extra padding?
                            WidthByRowsInThisColumn += 8 + 24;

                            //Console.WriteLine("InternalAutoSize" + new { SourceColumn.Width, cwidth = WidthByRowsInThisColumn });

#if FHR
                            __DragStartX = ColumnHorizontalResizerDrag.Position.X + (WidthByRowsInThisColumn - SourceColumn.Width);
#endif

                            var NewWidth = Math.Max(20, WidthByRowsInThisColumn);



                            // 15248ms { Name = dataGridView2 }InternalAutoResizeColumn { RowCount = 2, SourceColumnIndex = 0, NewWidth = 154, ElapsedMilliseconds = 2 } 
                            // 14818ms { Name = dataGridView2 } InternalAutoResizeColumn { RowCount = 2, SourceColumnIndex = 2, NewWidth = 120, ElapsedMilliseconds = 1 } 

                            // 1745ms event: { Name = dataGridView1 } InternalAutoResizeColumn { RowCount = 9, SourceColumnIndex = 1, NewWidth = 260, ElapsedMilliseconds = 447 } 


                            // report only slow https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201404/20140413

                            if (InternalAutoResizeColumnStopwatch.ElapsedMilliseconds > 20)
                                Console.WriteLine(
                                    "event: " +
                                    new { this.Name }
                                    + " InternalAutoResizeColumn " + new
                                    {
                                        RowCount = rows.Count,
                                        SourceColumnIndex,
                                        NewWidth,
                                        InternalAutoResizeColumnStopwatch.ElapsedMilliseconds
                                    });

                            // why does this cost us 600ms?
                            SourceColumn.Width = NewWidth;
                            #endregion

                        };
                    #endregion





#if FHR
                    if (ColumnAdded != null)
                        ColumnAdded(this, new DataGridViewColumnEventArgs((DataGridViewColumn)(object)SourceColumn));
#endif

                    // 1135ms { Name = dataGridView1 } InternalColumns Added { Index = 29, SourceColumnStopwatch = 7 } 
                    // 888 ??
                    // 244382ms event: dataGridView2 set DataSource columns { SourceDataTableColumnCount = 7, ElapsedMilliseconds = 869 } 
                    // 2135ms { Name = dataGridView2 } InternalColumns Added { Index = 0, Name = , SourceColumnStopwatch = 123 } 

                    //120:5572ms { Name = dataGridView2 } InternalColumns Added { Index = 1, SourceColumnStopwatch = 8 } 

                    // 112:371747ms { Name = dataGridView1 } InternalColumns Added { Index = 1, SourceColumnStopwatch = 31 } 

                    if (SourceColumnStopwatch.ElapsedMilliseconds > 40)
                        Console.WriteLine(
                            new { this.Name }
                            + " InternalColumns Added " + new
                            {
                                SourceColumn.Index,
                                SourceColumnStopwatch = SourceColumnStopwatch.ElapsedMilliseconds
                            });

                };

            #endregion


            new IStyle(__RowsTable_css_td)
            {
                width = "100%",
                height = "21px",
                position = IStyle.PositionEnum.relative
            };






            #region DataGridNewRow
            {
                var DataGridNewRow = new IHTMLImage("assets/ScriptCoreLib.Windows.Forms/DataGridNewRow.png");
                var xDataGridViewCellIsInEditMode = new XAttribute("DataGridViewCellIsInEditMode", global::System.Convert.ToString(true));

                var __RowsTable_css_td_after = __RowsTable_css
                   [IHTMLElement.HTMLElementEnum.tbody]
                   .last[IHTMLElement.HTMLElementEnum.tr]
                    //[e => e.getAttribute("DataGridViewCellSelected") == true]
                   [IHTMLElement.HTMLElementEnum.td]
                   .after;

                __RowsTable_css_td_after.style.position = IStyle.PositionEnum.absolute;
                __RowsTable_css_td_after.style.left = "12px";
                __RowsTable_css_td_after.style.top = "0px";
                __RowsTable_css_td_after.style.right = "0";
                __RowsTable_css_td_after.style.height = "21px";
                __RowsTable_css_td_after.content = "";
                __RowsTable_css_td_after.style.backgroundPosition = "left center";
                DataGridNewRow.ToBackground(__RowsTable_css_td_after.style, false);
            }
            #endregion

            #region DataGridEditRow
            {
                var DataGridEditRow = new IHTMLImage("assets/ScriptCoreLib.Windows.Forms/DataGridEditRow.png");
                var xDataGridViewCellIsInEditMode = new XAttribute("DataGridViewCellIsInEditMode", global::System.Convert.ToString(true));

                var __RowsTable_css_td_after = __RowsTable_css
                   [IHTMLElement.HTMLElementEnum.tbody]
                   [IHTMLElement.HTMLElementEnum.tr]
                    //[e => e.getAttribute("DataGridViewCellSelected") == true]
                   [xDataGridViewCellIsInEditMode]
                   [IHTMLElement.HTMLElementEnum.td]
                   .after;

                __RowsTable_css_td_after.style.position = IStyle.PositionEnum.absolute;
                __RowsTable_css_td_after.style.left = "12px";
                __RowsTable_css_td_after.style.top = "0px";
                __RowsTable_css_td_after.style.right = "0";
                __RowsTable_css_td_after.style.height = "21px";
                __RowsTable_css_td_after.content = "";
                __RowsTable_css_td_after.style.backgroundPosition = "left center";
                DataGridEditRow.ToBackground(__RowsTable_css_td_after.style, false);
            }
            #endregion

            #region DataGridFocusRow
            {
                var xDataGridViewCellSelected = new XAttribute("DataGridViewCellSelected", global::System.Convert.ToString(true));
                var DataGridFocusRow = new IHTMLImage("assets/ScriptCoreLib.Windows.Forms/DataGridFocusRow.png");
                var __RowsTable_css_td_before = __RowsTable_css
                    [IHTMLElement.HTMLElementEnum.tbody]
                    [IHTMLElement.HTMLElementEnum.tr]
                    //[e => e.getAttribute("DataGridViewCellSelected") == true]
                    [xDataGridViewCellSelected]
                    [IHTMLElement.HTMLElementEnum.td]
                    .before;


                __RowsTable_css_td_before.style.position = IStyle.PositionEnum.absolute;
                __RowsTable_css_td_before.style.left = "4px";
                __RowsTable_css_td_before.style.top = "0px";
                __RowsTable_css_td_before.style.right = "0";
                __RowsTable_css_td_before.style.height = "21px";
                __RowsTable_css_td_before.content = "";
                __RowsTable_css_td_before.style.backgroundPosition = "left center";
                DataGridFocusRow.ToBackground(__RowsTable_css_td_before.style, false);
            }
            #endregion

            #region InitializeZeroColumnCell

            // we need to reduce this!
            Action<__DataGridViewRow> InitializeZeroColumnCell =
                SourceRow =>
                {
                    #region InternalTableColumn
                    var __tr = default(IHTMLTableRow);


                    if (InternalPrerenderZeroRows.Count > 0)
                    {
                        // datasource already prepped a row for us
                        __tr = InternalPrerenderZeroRows.Dequeue();
                        __tr.Clear();
                    }
                    else
                    {
                        __tr = new IHTMLTableRow { };

                        // Failed to execute 'insertBefore' on 'Node': The new child element is null. 
                        if (InternalNewRow != null)
                        {
                            __RowsTableBody.insertBefore(__tr, InternalNewRow.InternalZeroColumnTableRow);
                        }
                        else
                        {
                            __RowsTableBody.appendChild(__tr);
                        }
                    }

                    SourceRow.InternalZeroColumnTableRow = __tr;


                    //var __tr = __RowsTableBody.AddRow();
                    var InternalTableColumn = __tr.AddColumn();
                    #endregion

                    // X:\jsc.svn\examples\javascript\forms\FormsGridCellStyle\FormsGridCellStyle\Application.cs

                    InternalTableColumn.title = new { SourceRow.Index }.ToString();

                    //#region AtInternalHeightChanged
                    //Action AtInternalHeightChanged = delegate
                    //{
                    //    //c1.style.height = (SourceRow.InternalHeight - 1) + "px";
                    //    c1img.style.height = (SourceRow.InternalHeight - 1) + "px";
                    //    c2img.style.height = (SourceRow.InternalHeight - 1) + "px";

                    //    c1contentcrel.style.height = (SourceRow.InternalHeight - 1) + "px";
                    //    __tr.style.height = SourceRow.InternalHeight + "px";
                    //};

                    //AtInternalHeightChanged();
                    //SourceRow.InternalHeightChanged += AtInternalHeightChanged;
                    //#endregion
                };
            #endregion

            InitializeZeroColumnCell(InternalNewRow);

            Console.WriteLine("new DataGridView() after InitializeZeroColumnCell");


            #region InternalAutoResizeColumn
            var t = new global::System.Windows.Forms.Timer();
            t.Interval = 100;
            t.Tick +=
                delegate
                {
                    t.Stop();

                    InternalAutoResizeAll();
                };
            #endregion

            this.InternalRowHeadersVisibleChanged +=
                delegate
                {
                    InternalAutoSizeWhenFill();
                };

            #region ClientSizeChanged
            // whatif we are in autosize mode?
            this.ClientSizeChanged +=
                delegate
                {

                    InternalAutoSizeWhenFill();
                };
            #endregion

            Console.WriteLine("new DataGridView() before InternalRows.Added");


            #region InternalRows.Added

            this.InternalRows.InternalItems.Added +=
                  (SourceRow, CurrentRowIndex) =>
                  {
                      if (SourceRow == InternalNewRow)
                      {
                          // do we have a test for readding rows?

                          SourceRow.InternalTableRow.AttachTo(__ContentTableBody);
                          SourceRow.InternalZeroColumnTableRow.AttachTo(__RowsTableBody);

                      }

                      if (SourceRow.InternalTableRow != null)
                          return;

                      //Console.WriteLine("InternalRows Added");

                      if (InternalNewRow == null)
                      {
                          // when is this happening?
                          SourceRow.InternalTableRow = __ContentTableBody.AddRow();
                      }
                      else
                      {
                          // how much time are we spending per row?
                          // what about bulk entry?
                          // could we adapt a preexisting table?

                          // how much time do we spend on moving the new row thingy?




                          if (InternalPrerenderRows.Count > 0)
                          {
                              // datasource already prepped a row for us
                              SourceRow.InternalTableRow = InternalPrerenderRows.Dequeue();
                              SourceRow.InternalTableRow.Clear();
                          }
                          else
                          {
                              SourceRow.InternalTableRow = new IHTMLTableRow();


                              // Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. 
                              if (InternalNewRow.InternalTableRow.parentNode == null)
                              {
                                  // where is our new row?
                                  __ContentTableBody.appendChild(InternalNewRow.InternalTableRow);
                                  InternalNewRow.InternalZeroColumnTableRow.AttachTo(__RowsTableBody);
                              }


                              __ContentTableBody.insertBefore(
                                  // is it part of the rows still?
                                  SourceRow.InternalTableRow,
                                  InternalNewRow.InternalTableRow

                                );
                          }

                          //Console.WriteLine("InternalRows reposition InternalNewRow");

                          // make sure the RowIndex -1 is the last element
                          this.InternalRows.InternalItems.Source.Remove(InternalNewRow);
                          this.InternalRows.InternalItems.Source.Add(InternalNewRow);

                          //Console.WriteLine("InternalRows reposition InternalNewRow done");
                      }



                      // disabled for now, until we get a newer test
                      //#region AtInternalHeightChanged
                      //Action AtInternalHeightChanged = delegate
                      //{
                      //    SourceRow.InternalTableRow.style.height = SourceRow.InternalHeight + "px";
                      //};

                      //AtInternalHeightChanged();
                      //SourceRow.InternalHeightChanged += AtInternalHeightChanged;
                      //#endregion


                      CreateMissingCells(SourceRow);



                      if (!InternalSkipAutoSize)
                          if (!InternalDataSourceBusy)
                              if (this.AutoSizeColumnsMode != DataGridViewAutoSizeColumnsMode.None)
                              {
                                  //Console.WriteLine("a new row was added, auto resize?");
                                  t.Stop();
                                  t.Start();
                              }





                      InitializeZeroColumnCell(SourceRow);

                  };
            #endregion

            #region InternalRows Removed
            this.InternalRows.InternalItems.Removed +=
                (SourceRow, i) =>
                {
                    //Console.WriteLine("InternalRows Removed");

                    SourceRow.InternalTableRow.Orphanize();
                    SourceRow.InternalZeroColumnTableRow.Orphanize();

                    // raise any events
                };
            #endregion


            __DataGridViewRow PendingNewRow = null;

            #region UserAddedRow
            this.InternalRaiseCellBeginEdit =
                (SourceCell) =>
                {
                    //Console.WriteLine("InternalRaiseCellBeginEdit " + new { SourceCell.ColumnIndex, SourceCell.OwningRow.Index });

                    var SourceRow = SourceCell.InternalOwningRow;

                    if (SourceRow.IsNewRow)
                    {
                        var n = new __DataGridViewRow();
                        InternalNewRow = null;
                        PendingNewRow = SourceRow;

                        InternalSkipAutoSize = true;
                        this.InternalRows.InternalItems.Source.Add(n);
                        InternalSkipAutoSize = false;

                        InternalNewRow = n;

                        if (this.UserAddedRow != null)
                            this.UserAddedRow(this, new DataGridViewRowEventArgs((DataGridViewRow)(object)SourceRow));
                    }


                    if (this.CellBeginEdit != null)
                        this.CellBeginEdit(this,
                            new DataGridViewCellCancelEventArgs(SourceCell.ColumnIndex, SourceRow.Index)
                        );
                };
            #endregion

            #region CellEndEdit

            this.InternalRaiseCellValueChanged =
                (SourceCell) =>
                {
                    var SourceRow = SourceCell.InternalOwningRow;

                    if (SourceRow.IsNewRow)
                    {
                        // if there is now content on the new row then we need another new row downt we?
                        return;
                    }

                    //Console.WriteLine("InternalRaiseCellValueChanged " + new { SourceCell.ColumnIndex, SourceCell.OwningRow.Index });


                    if (PendingNewRow == SourceRow)
                        PendingNewRow = null;

                    if (this.CellValueChanged != null)
                        this.CellValueChanged(this,
                            new DataGridViewCellEventArgs(SourceCell.ColumnIndex, SourceCell.OwningRow.Index)
                        );
                };

            this.InternalRaiseCellEndEdit =
                (SourceCell) =>
                {
                    //Console.WriteLine("InternalRaiseCellEndEdit " + new { SourceCell.ColumnIndex, SourceCell.OwningRow.Index });

                    var SourceRow = SourceCell.InternalOwningRow;

                    #region  PendingNewRow
                    if (PendingNewRow == SourceRow)
                    {
                        var ColumnIndex = SourceCell.ColumnIndex;
                        var RowIndex = SourceRow.Index;

                        this.InternalRows.InternalItems.Source.Remove(SourceRow);

                        SourceRow.InternalTableRow.Orphanize();
                        SourceRow.InternalZeroColumnTableRow.Orphanize();

                        //if (this.UserDeletedRow != null)
                        //    this.UserDeletedRow(this, new DataGridViewRowEventArgs((DataGridViewRow)(object)SourceRow));

                        PendingNewRow = null;

                        this.InternalRows.InternalItems.Source[RowIndex].InternalCells.InternalItems[ColumnIndex].InternalTableColumn_div.focus();
                        //this[SourceCell.ColumnIndex, SourceRow.Index].Selected = true;
                    }
                    #endregion


                    if (this.CellEndEdit != null)
                        this.CellEndEdit(this,
                            new DataGridViewCellEventArgs(SourceCell.ColumnIndex, SourceRow.Index)
                        );
                };
            #endregion



            this.GridColor = global::System.Drawing.Color.FromArgb(0xa0, 0xa0, 0xa0);
            this.Height = 400;


            // 2901ms exit DataGridView .ctor { ElapsedMilliseconds = 923 } 
            // 25:584ms event: exit DataGridView .ctor { ElapsedMilliseconds = 525 } 
            Console.WriteLine("event: new DataGridView() " + new { DataGridViewConstructorStopwatch.ElapsedMilliseconds });
        }
		public StudioView()
		{
			Content.style.position = IStyle.PositionEnum.absolute;
			Content.style.left = "0px";
			Content.style.right = "0px";
			Content.style.top = "0px";
			Content.style.bottom = "0px";

			new TwentyTenWorkspace().ToBackground(Content.style, true);

			var WorkspaceHeader = default(IHTMLSpan);

			@"jsc-solutions.net studio".ToDocumentTitle().With(
				title =>
				{
					WorkspaceHeader = new IHTMLSpan { innerText = title };

					WorkspaceHeader.AttachTo(Content);
					WorkspaceHeader.style.SetLocation(16, 8);
					WorkspaceHeader.style.color = Color.White;

					// http://www.quirksmode.org/css/textshadow.html
					WorkspaceHeader.style.textShadow = "#808080 4px 2px 2px";

				}
			);

			// em + px :)
			var Workspace0 = new IHTMLDiv().With(
				div =>
				{
					div.style.position = IStyle.PositionEnum.absolute;
					div.style.left = "0px";
					div.style.right = "0px";
					div.style.bottom = "0px";
					div.style.top = "3em";
				}
			).AttachTo(Content);

			// workspace contains the split views
			var Workspace = new IHTMLDiv().With(
				div =>
				{
					div.style.position = IStyle.PositionEnum.absolute;
					div.style.left = "6px";
					div.style.right = "6px";
					div.style.bottom = "6px";
					div.style.top = "6px";
				}
			).AttachTo(Workspace0);


			Action<HorizontalSplit> ApplyStyle =
			t =>
			{
				t.Split.Splitter.style.backgroundColor = Color.None;
				t.SplitImageContainer.Orphanize();
				t.SplitArea.Target.style.borderLeft = "0";
				t.SplitArea.Target.style.borderRight = "0";
				t.SplitArea.Target.style.width = "6px";
				t.SplitArea.Target.style.Opacity = 0.7;

				// should we obselete JSColor already?
				t.SelectionColor = JSColor.Black;
			};

			var Split = new HorizontalSplit
			{
				Minimum = 0,
				Maximum = 1,
				Value = 0.2,
			};

			Split.With(ApplyStyle);

			Split.Split.Splitter.style.backgroundColor = Color.None;

			Split.Container.AttachTo(Workspace);



			var SolutionToolbox = new SolutionDockWindowPage();

			SolutionToolbox.HeaderText.innerText = "Toolbox";
			SolutionToolbox.Content.style.backgroundColor = Color.White;
			SolutionToolbox.Content.style.padding = "2px";
			SolutionToolbox.Content.style.overflow = IStyle.OverflowEnum.auto;
			SolutionToolbox.Content.Clear();


			var vv = new SolutionToolboxListView();

			vv.Container.AttachTo(SolutionToolbox.Content);

			var items = new StockToolboxTabsForHTMLDocument();

			items.WithEach(vv.Add);


			var Viewer = new SolutionDocumentViewer();
			SolutionDocumentViewerTab AboutTab = "About";
			Viewer.Add(AboutTab);

			var CurrentDesigner = new SolutionFileDesigner();




			var HTMLDesigner = new SolutionFileDesignerHTMLElementTabs();

			CurrentDesigner.Add(HTMLDesigner);

			#region CodeSource
			var CodeSourceTab =
				new SolutionFileDesignerTab
				{
					Image = new ScriptCoreLib.Ultra.Components.HTML.Images.FromAssets.ClassViewer(),
					Text = "XDefaultPage"
				};

			var CodeSourceView = new SolutionFileView();


			CodeSourceView.Container.style.position = IStyle.PositionEnum.absolute;
			CodeSourceView.Container.style.left = "0px";
			CodeSourceView.Container.style.right = "0px";
			CodeSourceView.Container.style.top = "0px";
			CodeSourceView.Container.style.bottom = "0px";

			CodeSourceView.Container.style.display = IStyle.DisplayEnum.none;
			CodeSourceView.Container.AttachTo(CurrentDesigner.Content);

			CodeSourceTab.Deactivated +=
				delegate
				{
					CodeSourceView.Container.style.display = IStyle.DisplayEnum.none;
				};

			CodeSourceTab.Activated +=
				delegate
				{
					HTMLDesigner.HTMLDesignerContent.WhenContentReady(
						body =>
						{
							var CodeSourceFile = new SolutionFile();

							var Type = new SolutionProjectLanguageType
							{
								Namespace = "HTML.Pages",
								Name = "IDefaultPage",
								IsInterface = true,
							};

							(from n in body.AsXElement().DescendantsAndSelf()
							 let id = n.Attribute("id")
							 where id != null
							 select new { n, id }
							).WithEach(
								k =>
								{
									Type.Properties.Add(
										new SolutionProjectLanguageProperty
										{
											Name = k.id.Value,
											GetMethod = new SolutionProjectLanguageMethod(),
											SetMethod = new SolutionProjectLanguageMethod(),
											PropertyType = new SolutionProjectLanguageType
											{
												Namespace = "ScriptCoreLib.JavaScript.DOM.HTML",
												Name = "IHTMLElement"
											}
										}
									);
								}
							);

							KnownLanguages.VisualCSharp.WriteType(CodeSourceFile, Type, null);

							CodeSourceView.File = CodeSourceFile;

							CodeSourceView.Container.style.display = IStyle.DisplayEnum.empty;
						}
					);
				};


			#endregion


			CurrentDesigner.Add(CodeSourceTab);




			CurrentDesigner.First().RaiseActivated();

			AboutTab.Activated +=
				delegate
				{
					Viewer.Content.ReplaceContentWith(CurrentDesigner.Container);
				};

			Viewer.First().Activate();

			Split.Split.LeftScrollable = SolutionToolbox.Container;
			Split.Split.RightScrollable = Viewer.Container;
		}
        public void DrawTextToInfo(string text, Point p, Color c)
        {
            var box = new IHTMLSpan(text);

            box.style.SetLocation(p.X, p.Y);
            box.style.color = c;

            this.Layers.Info.appendChild(box);
        }
 private void InternalDisableAutoSize()
 {
     this.InternalTextField_ShadowContainer.Orphanize();
     this.InternalTextField_ShadowContainer = null;
     this.InternalTextField_Shadow = null;
 }
        public __TextBox()
        {
            #region InternalContainer
            //this.InternalContainer = new IHTMLDiv();
            this.InternalContainer = new IHTMLElement(ElementName);

            // are we excluding older browsers? does the app analyzer let the developer know what devices can be used now?
            this.InternalContainer_shadow = this.InternalContainer.createShadowRoot();
            // if we only create shadow, empty, other children dissapear dont they. as there are no insertion points

            this.InternalContainer.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;

            // in Forms we use typeof() because we see Component. WPF objects are more like XElements..
            this.InternalContainer.name = "__TextBox";

            this.InternalContainer.style.left = "0px";
            this.InternalContainer.style.top = "0px";

            // do we create any new havoc?
            this.InternalContainer.style.zIndex = 0;
            #endregion


            #region InternalTextField_ShadowContainer

            // when is it attached?
            this.InternalTextField_ShadowContainer = new IHTMLDiv();


            this.InternalTextField_ShadowContainer.style.position = IStyle.PositionEnum.absolute;
            this.InternalTextField_ShadowContainer.style.overflow = IStyle.OverflowEnum.hidden;
            this.InternalTextField_ShadowContainer.style.SetSize(0, 0);

            this.InternalTextField_Shadow = new IHTMLSpan();
            this.InternalTextField_Shadow.AttachTo(this.InternalTextField_ShadowContainer);
            this.InternalTextField_Shadow.style.whiteSpace = IStyle.WhiteSpaceEnum.pre;
            this.InternalTextField_Shadow.style.display = IStyle.DisplayEnum.inline_block;
            this.InternalTextField_Shadow.style.position = IStyle.PositionEnum.absolute;
            #endregion

            #region InternalTextField
            this.InternalTextField = new IHTMLInput(ScriptCoreLib.Shared.HTMLInputTypeEnum.text)
            {

                //}.AttachTo(this.InternalContainer);
                // public static T AttachTo<T>(this T e, IHTMLElement c) where T : INodeConvertible<IHTMLElement>;
            }.AttachTo(this.InternalContainer_shadow);

            this.InternalSetDefaultFont();

            this.InternalTextField.style.position = IStyle.PositionEnum.absolute;
            this.InternalTextField.style.margin = "0";
            this.InternalTextField.style.paddingTop = "0";
            this.InternalTextField.style.paddingBottom = "0";
            this.InternalTextField.style.border = "1px solid gray";
            #endregion


            Action InternalAutoSizeUpdate =
                delegate
                {
                    if (this.InternalTextField_Shadow == null)
                        return;

                    InternalAutoSizeToText(this.InternalTextField.value);
                };

            this.InternalTextField.onchange +=
                delegate
                {
                    InternalAutoSizeUpdate();
                };

            this.InternalTextField.onkeyup +=
                delegate
                {
                    InternalAutoSizeUpdate();
                };
        }
        public __TextBoxBase()
        {
            #region InternalContainer
            this.InternalContainer = new IHTMLDiv();

            this.InternalContainer.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            this.InternalContainer.name = "__TextBox";

            this.InternalContainer.style.left = "0px";
            this.InternalContainer.style.top = "0px";

            // do we create any new havoc?
            this.InternalContainer.style.zIndex = 0;
            #endregion


            #region InternalTextField_ShadowContainer
            this.InternalTextField_ShadowContainer = new IHTMLDiv();


            this.InternalTextField_ShadowContainer.style.position = IStyle.PositionEnum.absolute;
            this.InternalTextField_ShadowContainer.style.overflow = IStyle.OverflowEnum.hidden;
            this.InternalTextField_ShadowContainer.style.SetSize(0, 0);

            this.InternalTextField_Shadow = new IHTMLSpan();
            this.InternalTextField_Shadow.AttachTo(this.InternalTextField_ShadowContainer);
            this.InternalTextField_Shadow.style.whiteSpace = IStyle.WhiteSpaceEnum.pre;
            this.InternalTextField_Shadow.style.display = IStyle.DisplayEnum.inline_block;
            this.InternalTextField_Shadow.style.position = IStyle.PositionEnum.absolute;
            #endregion

            #region InternalTextField
            this.InternalTextField = new IHTMLInput(ScriptCoreLib.Shared.HTMLInputTypeEnum.text)
            {

            }.AttachTo(this.InternalContainer);

            // boxstyle. will it break layout?
            this.InternalTextField.style.padding = "0.4em";

            //Need to test/document
            this.InternalNameChanged += delegate
            {
                this.InternalTextField.name = InternalName;
                if (InternalName.ToUpper().Contains(("email").ToUpper()))
                    this.InternalTextField.type = Shared.HTMLInputTypeEnum.email;
                if (InternalName.ToUpper().Contains(("phone").ToUpper()))
                    this.InternalTextField.type = Shared.HTMLInputTypeEnum.tel;
            };

            this.InternalSetDefaultFont();

            this.InternalTextField.style.position = IStyle.PositionEnum.absolute;
            this.InternalTextField.style.margin = "0";
            this.InternalTextField.style.paddingTop = "0";
            this.InternalTextField.style.paddingBottom = "0";

            // what about inheritance chain?
            // X:\jsc.svn\examples\javascript\forms\Test\CSSLastTextBox\CSSLastTextBox\Application.cs
            IStyleSheet.all[typeof(TextBox)][IHTMLElement.HTMLElementEnum.input].style.border = "1px solid gray";
            #endregion

            // what about padding?
            // X:\jsc.svn\examples\javascript\forms\Test\TestTextBoxPadding\TestTextBoxPadding\Application.cs
            // http://stackoverflow.com/questions/628500/can-i-stop-100-width-text-boxes-from-extending-beyond-their-containers/628912#628912

            //box-sizing: border-box;
            (this.InternalTextField.style as dynamic).boxSizing = "border-box";
            //this.InternalTextField.style.boxSizing = "border-box";
            this.InternalTextField.style.width = "100%";
            this.InternalTextField.style.height = "100%";

            //this.ClientSizeChanged +=
            //    delegate
            //    {
            //        this.InternalTextField.style.width = this.ClientSize.Width + "px";
            //        this.InternalTextField.style.height = this.ClientSize.Height + "px";
            //    };

            #region InternalRaiseTextChanged
            Action InternalAutoSizeUpdate =
                delegate
            {
                if (this.InternalTextField_Shadow == null)
                    return;

                //InternalAutoSizeToText(this.InternalTextField.value);
            };

            this.InternalTextField.onchange +=
                delegate
            {
                InternalAutoSizeUpdate();
                this.InternalRaiseTextChanged();
            };

            this.InternalTextField.onkeyup +=
                delegate
            {
                InternalAutoSizeUpdate();
                this.InternalRaiseTextChanged();
            };
            #endregion




            this.Size = new global::System.Drawing.Size(100, 20);


        }
		/// <summary>
		/// This is a javascript application.
		/// </summary>
		/// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
		public Application(IApp page)
		{
			// X:\jsc.svn\examples\javascript\async\AsyncWindowUncaughtError\AsyncWindowUncaughtError\ApplicationWebService.cs

			// intellitrace
			// a self debugging programe?
			// can we have buttons for debugging?
			// https://www.youtube.com/watch?v=4vtKRE9an_I
			// could we have live patching, remote debugging via udp?

			var Next = new IHTMLButton { "Next" }.AttachToDocument();
			Next.disabled = true;

			Func<Task> Next_onclick = async delegate
			{

				Next.disabled = false;
				await Next.async.onclick;
				Next.disabled = true;
			};

			trace trace = async (string filepath, int linenumber, string line) =>
			{
				// could we go backwards in time too?
				// like intellitrace?

				var debugged = new IHTMLPre { }.AttachToDocument();




				// should we allow chaning constants?
				// by patching const load opcodes?

				var l = new IHTMLSpan { "" + linenumber }.AttachToDocument();




				l.title = filepath;

				l.style.marginRight = "2em";
				l.style.color = "darkcyan";

				l.AttachTo(debugged);

				// could we use css to do syntax highlight?
				var prefixToHide = "await trace();";

				// perhaps the next step would be to send us the origina stack usage IL 
				// we see in the jsc reflector?
				var c = new IHTMLSpan { line.Replace(prefixToHide, "") };

				c.style.marginRight = "2em";
				//c.style.color = "blue";
				c.style.backgroundColor = "yellow";

				c.AttachTo(debugged);

				await Next_onclick();

				c.style.backgroundColor = "";
			};

			interactive<string> __string = async (string data, string filepath, int linenumber, string line) =>
			{
				var i = new IHTMLInput { value = data }.AttachToDocument();

				await Next_onclick();

				return i.value;
			};


			//Func<>
			Func<string, Task<string>> program =
			// a simulaton of a program
			async data =>
			{
				await trace(); new IHTMLPre { await __string("hello") }.AttachToDocument();
				await trace(); new IHTMLPre { await __string("world") }.AttachToDocument();


				await trace(); return "done!";
			};

			new IHTMLButton { "Step Into" }.AttachToDocument().onclick +=
				async e =>
				{
					new IHTMLHorizontalRule().AttachToDocument();

					e.Element.disabled = true;
					var value = await program("data");
					e.Element.disabled = false;

					new IHTMLPre { new { value } }.AttachToDocument();

				};


			new IHTMLButton { "Run" }.AttachToDocument().onclick +=
				async e =>
				{
					// enum to string?
					new IHTMLHorizontalRule().AttachToDocument();

					var x = Next_onclick;
					// slow down the program
					Next_onclick = async delegate { await Task.Delay(300); };


					e.Element.disabled = true;
					var value = await program("data");
					e.Element.disabled = false;

					Next_onclick = x;

					new IHTMLPre { new { value } }.AttachToDocument();

				};
		}
 // Error	4	The call is ambiguous between the following methods or properties: 'ScriptCoreLib.JavaScript.DOM.CSSStyleRuleMonkier.this[int]' and 'ScriptCoreLib.JavaScript.DOM.CSSStyleRuleMonkier.this[ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement]'	X:\jsc.svn\examples\javascript\CSS\CSSSpecificDescendant\CSSSpecificDescendant\Application.cs	44	13	CSSSpecificDescendant
 // span has conficting operators?
 public CSSStyleRuleMonkier this[IHTMLSpan e]
 {
     get
     {
         return this[(IHTMLElement)e];
     }
 }
        //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 TreeNode ApplyLocalName(TreeNode t, XElement cc)
		{
			t.IsExpanded = true;
			t.Element.TextArea.Clear();
			var c = new IHTMLCode();
			t.Element.TextArea.Add(c);

			t.Element.ButtonArea.Hide();
			t.Element.IconArea.Hide();

			Action<string, JSColor> Write =
				(Text, Color) =>
				{
					var cs = new IHTMLSpan { innerText = Text };

					cs.style.color = Color;

					cs.AttachTo(c);
				};

			Write("<", JSColor.Blue);
			Write(cc.Name.LocalName, JSColor.FromRGB(0xa0, 0, 0));

			foreach (var item in cc.Attributes().ToArray())
			{
				Write(" ", JSColor.None);

				Write("foo", JSColor.Red);
				Write("='", JSColor.Blue);
				Write(item.Value, JSColor.Blue);
				Write("'", JSColor.Blue);
			}

			if (!cc.Elements().Any())
			{
				Write(">", JSColor.Blue);

				Write(cc.Value, JSColor.None);

				Write("</", JSColor.Blue);
				Write(cc.Name.LocalName, JSColor.FromRGB(0xa0, 0, 0));
				Write(">", JSColor.Blue);

			}
			else
			{
				Write("/>", JSColor.Blue);
			}

			return t;
		}