using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using Telerik.WinControls;
using Telerik.WinControls.Commands;
using Telerik.WinControls.Primitives;
using Telerik.WinControls.RadControlSpy;
using Telerik.WinControls.UI;
using Telerik.QuickStart.WinControls.Properties;
using ArrowDirection=Telerik.WinControls.ArrowDirection;

namespace Telerik.QuickStart.WinControls
{
    /// <summary>
    /// QSF's main form
    /// </summary>
    public partial class MainForm : ShapedForm
    {
        public const string DefaultTheme = "Breeze";
        // Fields
        private Image imageGrip;
        private ExamplesForm exampleInstance;
        private static Assembly entryAssembly;
        private RadTreeNode lastSelectedNode;
        private ExamplesTreeNode exampleTreeNode;
#if !DEBUG
        private SplashForm splashForm;
#endif

        public static string WorkingPath
        {
            get
            {
                return Path.GetDirectoryName( Application.ExecutablePath) + "\\..\\";
            }
        }
        
        //For Test purposes only
        private Color[] buttonColors =
            new Color[] { Color.Purple, Color.Pink, Color.Red, Color.OrangeRed, Color.Yellow, Color.YellowGreen, Color.Green, Color.Blue, Color.RoyalBlue, Color.Aqua };

        private QsfShape myShape = new QsfShape();

        private RadPanel demoContainer;

        const int qsfSplitterHeight = 80;
        private const int treeViewSplitterWidth = 8;
        internal const int settingsPanelWidth = 200;
        private const int settingsPanelExpandedWidth = settingsPanelWidth + treeViewSplitterWidth - 2;
        private const int settingsPanelCollapsedWidth = treeViewSplitterWidth;
        private bool settingsPanelExpanded = false;

        private bool treeViewCollapsed = false;
        private Image categoryNodeImage;
        private Image categoryNodeExpandedImage;
        private Image exampleNodeImage;
        private Image nodeNewImage;
        const int paddingLeft = 6;
        const int paddingHorizontal = 2 * paddingLeft;

        
        // welcome screen and images        
        private WelcomeScreenTop welcomeScreen;
        private Image imageDemosBack;
        private Image imageWelcomeBack;

        private Image imageMainBottomLeft;
        private Image imageMainBottomCenter;
        private Image imageMainBottomRight;

        bool welcomeImagesLoaded = false;

        private Image imageWelcomeBottomLeft;
        private Image imageWelcomeBottomCenter;
        private Image imageWelcomeBottomRight;

        private int originalBottomImagePanelHeight;
        private WelcomeScreenBottom welcomeScreenBottom;

        private Image smallTelerikIcon;
        private Image bigTelerikIcon;
        private ExamplesTreeNode welcomeScreenNode;

        /// <summary>
        /// The QSF's Entry Assembly
        /// </summary>
        public static Assembly EntryAssembly
        {
            get
            {
                if (entryAssembly == null)
                    entryAssembly = Assembly.GetEntryAssembly();

                return entryAssembly;
            }
            set
            {
                entryAssembly = value;
            }
        }

        /// <summary>
        /// Gets the current Example's form
        /// </summary>
        public ExamplesForm Example
        {
            get
            {
                return exampleInstance;
            }
        }
        private delegate void InvokeDelegate();
        public MainForm()
        {
#if !DEBUG
			splashForm = new SplashForm();
			splashForm.BackgroundImage = Resources.splash;
			splashForm.Show();
#endif
            InitializeComponent();


            this.Shape = myShape;
            this.radTitleBar1.ImageIcon = null;

            this.treeViewDemoNavigation.ItemHeight = 18;
            this.treeViewDemoNavigation.ToggleMode = ToggleMode.SingleClick;
			this.treeViewDemoNavigation.ExpandMode = ExpandMode.Single;
            this.treeViewDemoNavigation.NodeExpandedChanged += new RadTreeView.TreeViewEventHandler(treeViewDemoNavigation_NodeExpandedChanged);

            SetupExamplesCarousel();

            this.demoContainer = this.radPanel7;

            this.demoContainer.ThemeClassName = "QsfPanel";

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.ExamplesThemeButton.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.ButtonExamplesBreeze.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.DropDownButtonExamplesBreeze.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.TabStripExamplesBreeze.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.TreeViewExamplesBreeze.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.TitleBarExamplesBreeze.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.ScrollBarExamplesBreeze.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.QsfPanelBreeze.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.QsfPanelControlDefault.xml");

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.QsfPanelDesert.xml");

            this.treeViewDemoNavigation.ThemeName = "ExamplesBreeze";     

            this.toggleSettingsSplitter.Width = treeViewSplitterWidth;
            this.CollapseSettingsPanel();

            this.topImagePanel.BackgroundImage = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.MainTopCenter.png");
            this.topImagePanel.TopLeftImage = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.MainTopLeft.png");
            this.topImagePanel.TopRightImage = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.MainTopRight.png");

            RerouteMoseEventsToTitleBar(this.radControlsLabel);

#if DEBUG
            this.btnLoadTheme.Visible = true;
#endif
        }

        void treeViewDemoNavigation_NodeExpandedChanged(object sender, RadTreeViewEventArgs e)
        {
            this.treeViewDemoNavigation.BringIntoView(this.treeViewDemoNavigation.SelectedNode);
        }


        private bool themesLoaded = false;

        //load themes from files
        private void LoadAllThemes()
        {
            if (themesLoaded)
            {
                return;
            }

            themesLoaded = true;

            Application.DoEvents();

            ThemeResolutionService.RegisterThemeFromStorage(ThemeStorageType.Resource,
                "Telerik.QuickStart.WinControls.Resources.SplitterBreeze.xml");            

            new Telerik.WinControls.Themes.DesertTheme();
            new Telerik.WinControls.Themes.AquaTheme();
            new Telerik.WinControls.Themes.MiscellaneousTheme();

            //check why if theme is not loaded in the designer.cs file, an issue appears with treeview scrollbar
            new Telerik.WinControls.Themes.Office2007BlackTheme();

            new Telerik.WinControls.Themes.Office2007SilverTheme();
            new Telerik.WinControls.Themes.TelerikTheme();
            new Telerik.WinControls.Themes.VistaTheme();
            new Telerik.WinControls.Themes.BreezeTheme();
        }

        private void SetupExamplesCarousel()
        {
            this.examplesCarousel.LoadElementTree();
            this.examplesCarousel.BackColor = Color.Transparent;

            //item height includes the reflection;

            const int itemBorderSize = 6;

            this.examplesCarousel.CarouselElement.MaxItemSize = new Size(245 + itemBorderSize * 2, 241 + itemBorderSize * 2);
            this.examplesCarousel.CarouselElement.TextDescriptionElement.Font = new Font( "Arial", 9.5f );
            this.examplesCarousel.CarouselElement.TextDescriptionElement.ForeColor = Color.FromArgb( 95, 149, 146 );
            this.examplesCarousel.CarouselElement.TextTitleElement.Font = new Font( "Arial", 14 );
            this.examplesCarousel.CarouselElement.TextTitleElement.ForeColor = Color.FromArgb(255, 255, 255);
            this.examplesCarousel.CarouselElement.TextTitleElement.TextAlignment = ContentAlignment.TopCenter;

            this.examplesCarousel.CarouselElement.ItemDisplayOffset = new Size(0, -50);
            this.examplesCarousel.CarouselElement.TextDisplayOffset = new System.Drawing.Size(200, 200);

            SetupCarouselNavigationButton(this.examplesCarousel.CarouselElement.BtnLeft,
                "Telerik.QuickStart.WinControls.Resources.Carousel.arrow_left.png",
                "Telerik.QuickStart.WinControls.Resources.Carousel.arrow_leftHovered.png");

            SetupCarouselNavigationButton(this.examplesCarousel.CarouselElement.BtnRight,
                "Telerik.QuickStart.WinControls.Resources.Carousel.arrow_right.png",
                "Telerik.QuickStart.WinControls.Resources.Carousel.arrow_rightHovered.png");


            FillPrimitive fill = (FillPrimitive) this.examplesCarousel.CarouselElement.Children[0];
            fill.Visibility = ElementVisibility.Collapsed;

            FillPrimitive spotLight = (FillPrimitive)this.examplesCarousel.CarouselElement.Children[1];
            spotLight.Visibility = ElementVisibility.Collapsed;
        }

        private void SetupCarouselNavigationButton(RadButtonElement button, string imageNormalResourceName, string imageHoveredResourceName)
        {
            button.DisplayStyle = DisplayStyle.Image;
            button.ImageAlignment = ContentAlignment.MiddleCenter;

            Image normalImage = ResourceHelper.ImageFromResource(GetType(), imageNormalResourceName);
            Image hotImage = ResourceHelper.ImageFromResource(GetType(), imageHoveredResourceName);
            
            StyleSheet carouselButtonStyle = new StyleSheet();

            carouselButtonStyle.PropertySettingGroups.Add(new PropertySettingGroup(
                typeof(RadButtonElement),
                new PropertySetting(RadButtonElement.ImageProperty, normalImage)
                ));

            carouselButtonStyle.PropertySettingGroups.Add(new PropertySettingGroup(
                typeof(RadButtonElement),
                new SimpleCondition(RadElement.IsMouseOverProperty, true),
                new PropertySetting(RadButtonElement.ImageProperty, hotImage)
                ));

            carouselButtonStyle.PropertySettingGroups.Add(new PropertySettingGroup(
                typeof(RadButtonElement),
                new SimpleCondition(RadElement.IsMouseOverProperty, true, UnaryOperator.NotOperator),
                new PropertySetting(RadButtonElement.ImageProperty, normalImage)
                ));

            button.Style = carouselButtonStyle;

            button.ButtonFillElement.Visibility = ElementVisibility.Hidden;
            button.BorderElement.Visibility = ElementVisibility.Hidden;
        }

        public static Image ImageFromResource(string resourceName)
        {
            using (
                Stream stream =
                    Assembly.GetExecutingAssembly().GetManifestResourceStream( resourceName ))
            {
                if (stream != null)
                    return new Bitmap( Image.FromStream( stream ) );
            }

            return null;
        }

        public static RadControl FindRadControl(Control form)
        {
            foreach (Control control in form.Controls)
                if (control is RadControl)
                {
                    return control as RadControl;
                }
                else if (control is Panel || control is GroupBox)
                {
                    RadControl found = FindRadControl(control);
                    if (found != null)
                    {
                        return found;
                    }
                }
            return null;
        }

        protected override void PaintFrame(Graphics g)
        {
            base.PaintFrame(g);

            if (imageGrip != null)
            {
                g.DrawImage(imageGrip, this.Width - imageGrip.Width - 8, this.Height - imageGrip.Height - 8);
            }
        }

        protected override int GetHitTest(Point point)
        {
            Rectangle r = new Rectangle(this.Width - imageGrip.Width - 8, this.Height - imageGrip.Height - 8,
                imageGrip.Width, imageGrip.Height);

            if (r.Contains(point))
                return 17;

            return base.GetHitTest(point);
        }

        protected override void ApplicationThemeChanged(object sender, ThemeChangedEventArgs args)
        {
        }

        /// <summary>
        /// Gets the main form's RadTreeView
        /// </summary>
        public RadTreeView TreeView
        {
            get
            {
                return this.treeViewDemoNavigation;
            }
        }

        public Image CategoryNodeImage
        {
            get
            {
                //TODO: dispose image
                if (categoryNodeImage == null)
                {
                    categoryNodeImage = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.arrow_r.png");
                }

                return categoryNodeImage;
            }
        }

        public Image CategoryNodeExpandedImage
        {
            get
            {
                //TODO: dispose image
                if (categoryNodeExpandedImage == null)
                {
                    categoryNodeExpandedImage = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.arrow_down.png");
                }
                return categoryNodeExpandedImage;
            }
        }

        public Image ExampleNodeImage
        {
            get
            {
                //TODO: dispose image
                if (exampleNodeImage == null)
                {
                    exampleNodeImage = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.bullet.png");
                }

                return exampleNodeImage;
            }
        }

        public Image NodeNewImage
        {
            get
            {
                //TODO: dispose image
                if (nodeNewImage == null)
                {
                    nodeNewImage = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.label_new.png");
                }
                return nodeNewImage;
            }
        }

        private void CreatePictureBoxShape()
        {
            if (this.telerikPicture.Region != null)
            {
                this.telerikPicture.Region.Dispose();
            }

            if (this.WindowState != FormWindowState.Maximized)
            {
                IntPtr pictureBoxRegion =
                    UnsafeNativeMethods.CreateRoundRectRgn(0,
                    0,
                    this.telerikPicture.Width + 1, this.telerikPicture.Height, 14, 16);

                this.telerikPicture.Region = Region.FromHrgn(pictureBoxRegion);
            }
            else
            {
                IntPtr pictureBoxRegion =
                   UnsafeNativeMethods.CreateRoundRectRgn(0,
                   0,
                   this.telerikPicture.Width + 1, this.telerikPicture.Height, 9, 9);

                this.telerikPicture.Region = Region.FromHrgn(pictureBoxRegion);
            }
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            this.CreatePictureBoxShape();
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += delegate { this.LoadAllThemes(); };

            BeginInvoke(new MethodInvoker(worker.RunWorkerAsync));

            // The following code is used to dynamicaly adjust MainForm's size and position on large screens
            Size screenSize = Screen.GetWorkingArea(this).Size;
            Size newFormSize = Size.Subtract(screenSize, new Size(50, 0));

            //set best-view proportions
            newFormSize = new Size(Math.Min(newFormSize.Width, 1280), 
                Math.Min(Math.Min( newFormSize.Height, (int)(newFormSize.Width * 3d / 4d)), 900));

            this.Bounds =
                new Rectangle(
                    new Point((screenSize.Width - newFormSize.Width)/2, (screenSize.Height - newFormSize.Height)/2),
                    newFormSize);

            imageGrip = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.grip.bmp");            
            
            ExamplesLoader loader = new ExamplesLoader();
            try
            {
                loader.Load(Path.Combine(WorkingPath, "QuickStart.xml"), this.treeViewDemoNavigation);
            }
            catch(Exception ex)
            {
                RadMessageBox.Show("An error occured while loading demo configuration xml file. " + ex.ToString());
            }

            if (!string.IsNullOrEmpty(loader.ExamplesTitle))
            {
                this.Text = loader.ExamplesTitle;
            }

            this.welcomeScreenNode = new ExamplesTreeNode("Home", NodeType.Category);
            this.welcomeScreenNode.Image = LoadImage("Telerik.QuickStart.WinControls.Resources.TreeViewImages.Home.png");
            this.welcomeScreenNode.ItemHeight = this.welcomeScreenNode.Image.Height + 4;
            this.welcomeScreenNode.Selected = true;

            SetWelcomeScreenNodeProperties();

            this.treeViewDemoNavigation.Nodes.Insert(0, welcomeScreenNode);

            this.treeViewDemoNavigation.VScrollBar.BackColor = Color.Transparent;
            this.treeViewDemoNavigation.VScrollBar.ScrollBarElement.ThumbElement.Margin = new Padding(1, 0, 1, 0);

            this.treeViewDemoNavigation.HScrollBar.ScrollBarElement.Visibility = ElementVisibility.Collapsed;

            this.examplesCarousel.CarouselElement.ExampleStart += new RadCarouselElement.ExampleStartEventHandler( CarouselElement_ExampleStart );            

            this.LoadWelcomeScreen();
            ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.Icon = resources.GetObject("$this.Icon") as Icon;

#if !DEBUG
			this.splashForm.Hide();
		    this.splashForm.Dispose();
            this.splashForm = null;
#endif
        }

        private void SetWelcomeScreenNodeProperties()
        {
            Image res = MainForm.ImageFromResource("Telerik.QuickStart.WinControls.Resources.Images.WelcomeScreenNode.png");
            if (res != null)
            {
                welcomeScreenNode.Image = res;
                welcomeScreenNode.ItemHeight = res.Height + 2;
                welcomeScreenNode.ForeColor = Color.White;
            }

            welcomeScreenNode.ItemHeight += 4;
            welcomeScreenNode.Font = new Font("Lucida Sans Unicode", 10.5f);
            welcomeScreenNode.ForeColor = Color.White;
        }

        private void selectSkin_Click(object sender, EventArgs e)
        {
            RadMenuItem menuItem = sender as RadMenuItem;
            if (menuItem != null)
            {
                SetTheme(menuItem.Text, exampleInstance, menuItem.Tag as Type);
            }
        }

        private void GetAvailableRadControls(Control control, Hashtable radControls)
        {
            if (control is RadControl &&
                !radControls.Contains(control.GetType()) )
            {
                radControls.Add(control.GetType(), control);
            }

            if (control is Panel || control is RadPanel || !(control is RadControl))
            {
                foreach (Control subControl in control.Controls)
                {
                    GetAvailableRadControls(subControl, radControls);
                }
            }
        }

        private void SetTheme(string themeName, Control form, Type type)
        {
            if (form != null)
            {
                foreach (Control control in form.Controls)
                {
                    if (type == control.GetType())
                    {
                        ((RadControl)control).ThemeName = themeName;
                    }
                    else if (control is Panel)
                    {
                        SetTheme(themeName, control, type);
                    }
                    else if (control is GroupBox)
                    {
                        SetTheme(themeName, control, type);
                    }
                    else if (control is TabControl)
                    {
                        SetTheme( themeName, control, type );
                    }
                    else if (control is RadPanel)
                    {
                        SetTheme(themeName, control, type);
                    }
                }
            }
        }

        private Image LoadImage(string name)
        {
            Stream stream = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream(name);
            if (stream == null)
            {
                throw new NullReferenceException("Cannot find " + name);
            }
            return new Bitmap(stream);
        }

        private void NavigateToExample(ExamplesTreeNode treeNode)
        {
            EnsureCodeViewModeUnloaded();
            this.EnsureWelcomeScreenHidden();
            //todo add support for edit-description with Double-click on descrition 
            //file text
            //explorer /select,fullPath

            this.exampleSplitContainer.Visible = true;

            this.examplesCarousel.Visible = false;

            this.UpdateBreadcrumb(treeNode);
            this.UpdateSelectedExampleDesciption(treeNode);

            this.ToggleVisibleCarouselModeTools(false);
            this.ToggleVisibleExampleModeTools(true);

            if (lastSelectedNode == treeNode)
                return;

            exampleTreeNode = treeNode;
            UseWaitCursor = true;
            this.Cursor = Cursors.WaitCursor;                        

            if (exampleInstance != null)
            {
                exampleInstance.Dispose();
                exampleInstance = null;
            }

            Theme breeze = ThemeResolutionService.GetTheme(MainForm.DefaultTheme);
            if (breeze != null)
            {
                breeze.RemoveAllColorBlends();
            }

            //todo added only for the beta            
            //if ((treeNode.Text == "Theming" || treeNode.Theming ) &&
            //    typeof( ExamplesForm ).IsAssignableFrom( treeNode.FormType ))
            //{
            //    this.radDropDownButton1.Visible = true;
            //}
            //else
            //{
            //    this.radDropDownButton1.Visible = false;
            //}

            if (typeof(ExamplesForm).IsAssignableFrom(treeNode.FormType))
            {
                exampleInstance = treeNode.Form as ExamplesForm;
                //this.UpdateThemes();


                if ((exampleInstance.EnabledQSFButtons & QSFButtons.TransparentBackground) == QSFButtons.TransparentBackground)
                {
                    this.demoContainer.PanelElement.Visibility = ElementVisibility.Hidden;
                }
                else
                {
                    this.demoContainer.PanelElement.Visibility = ElementVisibility.Visible;
                }

                this.EnableButtons(exampleInstance.EnabledQSFButtons);
                //this.radRotator1.Stop();
                //this.radRotator1.Visible = false;
                //this.productivityTools.Visible = true;
                //this.descriptionLabel.Text = "Productivity Tools";

            }
            else
            {
                this.demoContainer.PanelElement.Visibility = ElementVisibility.Hidden;
                
                PreviewForm previewForm = new PreviewForm();
                previewForm.ExampleNode = treeNode;
                previewForm.PreviewImage = treeNode.ExampleImage;
                exampleInstance = previewForm;

                this.panelThemes.Visible = false;
            }

            if (exampleInstance != null)
            {
                //this.webBrowser1.Hide();
                demoContainer.Controls.Add(exampleInstance);
                exampleInstance.Dock = DockStyle.Fill;

                //Check if there are settings in the settings panel to expand it
                //otherwise it should not be expanded
                if (this.exampleSplitContainer.Panel2.Controls.Count > 1 &&
                    this.exampleSplitContainer.Panel2.Controls[1].Controls.Count > 1)
                {
                    this.ExpandSettingsPanel();
                }
                else
                {
                    this.CollapseSettingsPanel();
                }

                //exampleInstance.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
            }

            GC.Collect(3);

            lastSelectedNode = treeNode;
            this.Cursor = Cursors.Arrow;
            UseWaitCursor = false;
        }

        private void ToggleVisibleCarouselModeTools(bool visible)
        {
            this.btnSearch.Visible = visible;
            this.btnHelp.Visible = visible;
            this.btnForums.Visible = visible;  
        }

        private void ToggleVisibleExampleModeTools(bool visible)
        {
            this.codeViewTabStrip.Visible = visible;
            this.panelThemes.Visible = visible;
        }

        private void UpdateSelectedExampleDesciption(ExamplesTreeNode treeNode)
        {
            this.examplesCarousel.CarouselElement.RemoveOuterDescriptionDisplay();

            //((TextPrimitive)descriptionLabel.LabelElement.Children[2].Children[1]).
            //    BindProperty(TextPrimitive.TextProperty, descriptionLabel.LabelElement, RadLabelElement.TextProperty, PropertyBindingOptions.OneWay);

            descriptionLabel.Text = "<html>";
            //descriptionLabel.Text += "<size=+4>";
            //descriptionLabel.Text += treeNode.Text + "<size=-4><br>";
            descriptionLabel.Text += treeNode.Description;

            //descriptionPanel1.ExampleTitle = treeNode.Text;
            //descriptionPanel1.InnerHtml = treeNode.Description;
        }

        private void UpdateBreadcrumb(RadTreeNode treeNode)
        {
            if (treeNode == null)
            {
                this.labelBreadcrumb.Image = null;
                this.labelBreadcrumb.Text = string.Empty;
                this.labelBreadcrumb.Visible = false;
                return;
            }

            this.labelBreadcrumb.Visible = true;

            RadTreeNode rootNode = GetRootNode(treeNode);

            this.labelBreadcrumb.Image = rootNode.Image;
            this.labelBreadcrumb.Text = rootNode.Text;            

            if (rootNode != treeNode) //seleted is a non-root node
            {
                this.labelBreadcrumb.Text += "/" + treeNode.Text;
            }
        }

        private RadTreeNode GetRootNode(RadTreeNode treeNode)
        {
            RadTreeNode rootNode = treeNode;
            for (RadTreeNode node = treeNode; node.Parent != null; node = node.Parent )
            {
                rootNode = node.Parent;
            }
            return rootNode;
        }

        #region Navigation & History
        private bool internalChange = false;
        private List<ExamplesTreeNode> history = new List<ExamplesTreeNode>();
        private int currentHistoryPosition = -1;

        private void btnFor_Click(object sender, EventArgs e)
        {
            this.NavigateForward();
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.NavigateBackward();
        }

        private void NavigateForward()
        {
            //Debug.WriteLine("NavigateFor");
            if (this.history.Count == 0)
            {
                return;
            }
            int lastIndex = this.history.Count - 1;
            this.currentHistoryPosition++;
            if (this.currentHistoryPosition > lastIndex)
            {
                this.currentHistoryPosition = lastIndex;
            }
            if (this.treeViewDemoNavigation.SelectedNode !=
                this.history[this.currentHistoryPosition])
            {
                this.internalChange = true;
                this.treeViewDemoNavigation.SelectedNode = this.history[this.currentHistoryPosition];
                this.treeViewDemoNavigation.BringIntoView(this.treeViewDemoNavigation.SelectedNode);
                this.internalChange = false;
                if (this.history[this.currentHistoryPosition].NodeType == NodeType.Example)
                {
                    this.NavigateToExample(this.history[this.currentHistoryPosition]);
                }
                else
                {
                    this.NavigateToCarousel(this.history[this.currentHistoryPosition]);
                }
                ChangeNavigationEnabled();
            }
        }

        private void NavigateBackward()
        {
            //Debug.WriteLine("NavigateBack");
            if (this.history.Count == 0)
            {
                return;
            }
            int firstIndex = 0;
            this.currentHistoryPosition--;
            if (this.currentHistoryPosition < firstIndex)
            {
                this.currentHistoryPosition = firstIndex;
            }

            if (this.treeViewDemoNavigation.SelectedNode !=
                this.history[this.currentHistoryPosition])
            {
                this.internalChange = true;
                this.treeViewDemoNavigation.SelectedNode = this.history[this.currentHistoryPosition];
                this.treeViewDemoNavigation.BringIntoView(this.treeViewDemoNavigation.SelectedNode);
                this.internalChange = false;
                if (this.history[this.currentHistoryPosition].NodeType == NodeType.Example)
                {
                    this.NavigateToExample(this.history[this.currentHistoryPosition]);
                }
                else
                {
                    NavigateToCarousel(this.history[this.currentHistoryPosition]);
                }
                ChangeNavigationEnabled();
            }
        }

        private void ChangeNavigationEnabled()
        {
            if (this.history.Count == 0)
            {
                this.btnBackward.Enabled = false;
                this.btnForward.Enabled = false;
            }
            bool backwardState = this.currentHistoryPosition > 0;
            bool forwardState = this.currentHistoryPosition < (this.history.Count - 1);
            if (this.btnBackward.Enabled != backwardState)
            {
                this.btnBackward.Enabled = backwardState;
            }
            if (this.btnForward.Enabled != forwardState)
            {
                this.btnForward.Enabled = forwardState;
            }
        }

        internal void AddCurrentNodeToHistory()
        {
            if (this.history.Count > 0 &&
                this.treeViewDemoNavigation.SelectedNode == this.history[this.history.Count - 1])
            {
                return;
            }
            if (this.treeViewDemoNavigation.SelectedNode != null)
            {
                this.AddNodeToHistory(this.treeViewDemoNavigation.SelectedNode as ExamplesTreeNode);
            }
        }

        private void AddNodeToHistory(ExamplesTreeNode treeNode)
        {
            //Debug.WriteLine("add to stack.");
            this.history.Add(treeNode);
            this.currentHistoryPosition = (this.history.Count - 1);
            ChangeNavigationEnabled();
        }

        private void treeView1_BeforeSelect(object sender, RadTreeViewCancelEventArgs e)
        {
            if (this.internalChange)
            { 
                return;
            }
            if (this.history.Count != 0 &&
                this.currentHistoryPosition < (this.history.Count - 1))
            {
                this.history.RemoveRange((this.currentHistoryPosition + 1), this.history.Count - (this.currentHistoryPosition + 1));
                //this.currentHistoryPosition--;
            }
        }

        private void treeView1_AfterSelect(object sender, RadTreeViewEventArgs e)
        {
            if (this.internalChange)
            {
                return;
            }
            this.AddCurrentNodeToHistory();

            // Example  setup code
            ExamplesTreeNode treeNode = e.Node as ExamplesTreeNode;
            if (treeNode == null)
            {
                return;
            }

            this.EnableButtons(QSFButtons.None);

            if (treeNode != null)
            {
                if (treeNode.NodeType == NodeType.Example)
                {
                    if (!string.IsNullOrEmpty(treeNode.ExampleTypeName))
                    {
                        NavigateToExample(treeNode);
                    }
                }
                else
                {
                    NavigateToCarousel(treeNode);
                }
            }
        } 
        #endregion

        private void NavigateToCarousel(ExamplesTreeNode rootNode)
        {
            if (rootNode == this.welcomeScreenNode)
            {
                this.LoadWelcomeScreen();
                return;
            }
            else
            {
                this.EnsureWelcomeScreenHidden();
            }

            EnsureCodeViewModeUnloaded();

            this.examplesCarousel.CarouselElement.SetOuterDescriptionDisplay(this.descriptionLabel.LabelElement);

            this.exampleSplitContainer.Visible = false;
            if (this.exampleInstance != null)
            {
                this.exampleInstance.Unload();
            }

            for (int i = this.examplesCarousel.Items.Count - 1; i >= 0; i--)
            {
                RadItem item = this.examplesCarousel.Items[i];
                item.Dispose();
            }

            RadTreeNode selectedNode = this.treeViewDemoNavigation.SelectedNode;

            if (selectedNode != null && 
                this.treeViewDemoNavigation.Nodes.Count > 0 &&
                this.treeViewDemoNavigation.Nodes[0] != selectedNode)
            {
                //Category carousel
                SetupCategoryScreenCarousel( rootNode );
            }
            else
            {
                for (int i = 0; i < this.treeViewDemoNavigation.Nodes.Count; ++i)
                {
                    SetupHomeScreenCarousel( (ExamplesTreeNode)this.treeViewDemoNavigation.Nodes[i]);
                }
            }

            UpdateBreadcrumb(selectedNode);
            
            if (this.examplesCarousel.Items.Count == 0)
            {
                this.SetupEmptyScreenCarousel( rootNode );
            }

            this.examplesCarousel.BringToFront();
            this.examplesCarousel.Visible = true;

            this.ToggleVisibleCarouselModeTools(true);
            this.ToggleVisibleExampleModeTools(false);
        }

        private void SetupEmptyScreenCarousel( ExamplesTreeNode rootNode )
        {            
            RadCarouselItem item = CreateCarouselItemFromNode(rootNode, true);
            string description = rootNode.DescriptionText;
            Bitmap image = (Bitmap)rootNode.ExampleImage;
            
            item.Image = image;
            
            item.Description = description;            
            this.examplesCarousel.Items.Add( item );
        }

        private void SetupHomeScreenCarousel(ExamplesTreeNode rootNode)
        {
            if (rootNode.ShowInHomeCarousel &&
               rootNode.NodeType == NodeType.Example)
            {
                RadCarouselItem item = CreateCarouselItemFromNode(rootNode, false);
                if (item.Image != null)
                {
                    this.examplesCarousel.Items.Add(item);
                    //this.examplesCarousel.Items.Add(item);
                }                
            }
            for (int i = 0; i < rootNode.Nodes.Count; i++)
            {
                SetupHomeScreenCarousel((ExamplesTreeNode)rootNode.Nodes[i]);
            }
        }

        private void SetupCategoryScreenCarousel(ExamplesTreeNode rootNode)
        {
            for (int i = 0; i < rootNode.Nodes.Count; i++)
            {
                ExamplesTreeNode node = (ExamplesTreeNode)rootNode.Nodes[i];
                if (node.ShowInCarousel && node.NodeType == NodeType.Example)
                {
                    RadCarouselItem item = CreateCarouselItemFromNode(node, false);
                    if (item.Image != null)
                    {
                        this.examplesCarousel.Items.Add(item);
                    }
                }

                if (node.NodeType == NodeType.Category)
                {
                    SetupCategoryScreenCarousel(node);
                }
            }
        }

        private RadCarouselItem CreateCarouselItemFromNode(ExamplesTreeNode node, bool singleIcon)
        {
            Bitmap testImage = null;

            string filePath = node.GetFilePath("CarouselImage.png");
            if (File.Exists(filePath))
            {
                testImage = Image.FromFile(filePath) as Bitmap;
            }

            //TODO: This image should be disposed
            RadCarouselItem item = new RadCarouselItem();
            item.Image = testImage;
            item.DisplayStyle = DisplayStyle.Image;
            //item.Children[1].Padding = new Padding(2);

            if (string.IsNullOrEmpty( node.CarouselTitle ))
            {
                item.Title = node.Text;
            }
            else
            {
                item.Title = node.CarouselTitle;
            }
            item.TreeNodeText = node.Text;//use for carousel 

            item.Description = node.DescriptionText;
            item.Font = new Font( "Arial", 12 );
            
            item.ForeColor = Color.FromArgb( 153, 153, 153 );

            BorderPrimitive border = (BorderPrimitive)item.BorderElement;

            const int itemBorderWidth = 6;

            if (singleIcon)
            {
                border.Visibility = ElementVisibility.Hidden;
            }
            else
            {
                border.ForeColor = Color.FromArgb(10, 0, 0, 0);
                border.ForeColor2 = Color.FromArgb(12, 0, 0, 0);
                border.ForeColor3 = Color.FromArgb(12, 0, 0, 0);
                border.ForeColor4 = Color.FromArgb(0, 0, 0, 0);

                border.InnerColor = Color.FromArgb(20, 0, 0, 0);
                border.InnerColor2 = Color.FromArgb(55, 0, 0, 0);
                border.InnerColor3 = Color.FromArgb(55, 0, 0, 0);
                border.InnerColor4 = Color.FromArgb(0, 0, 0, 0);

                border.BoxStyle = BorderBoxStyle.OuterInnerBorders;
                border.GradientAngle = 90f;
                border.Width = itemBorderWidth;
                border.GradientStyle = GradientStyles.Linear;
            }


            item.Shape = new RoundRectShape(6);

            float scalef = 1.0f;

            if (testImage != null)
            {
                scalef = Math.Min(
                   (this.examplesCarousel.CarouselElement.MaxItemSize.Width - itemBorderWidth * 2) / testImage.Size.Width,
                   (this.examplesCarousel.CarouselElement.MaxItemSize.Height - itemBorderWidth * 2) / testImage.Size.Height);
            }

            SizeF scale = new SizeF(scalef, scalef);

            ((ImagePrimitive)item.Children[1].Children[0]).ScaleTransform = scale;
            return item;
        }
        
        private void FillDropWithSourceFiles(string[] files, RadItemCollection items)
        {
            foreach (string name in files)
            {
                RadMenuItem item = new RadMenuItem(name);
                item.Click += new EventHandler(codeFileMenuItem_Click);// += new EventHandler( selectFile_Click );
                items.Add(item);
            }
        }

        private WebBrowser codeViewer;

        void codeFileMenuItem_Click( object sender, EventArgs e )
        {
            RadMenuItem menuItem = (sender as RadMenuItem);
            string fileName = menuItem.Text;

            LoadFileInCodeViewer(fileName);
        }

        private void LoadFileInCodeViewer(string fileName)
        {
            ExamplesTreeNode node = this.exampleTreeNode;
            if (node != null)
            {
                EnsureCodeViewerLoaded();

                this.btnSelectCodeFile.Text = "Current file: " + fileName + " . Click to select another file";

                string fileWithPath = node.GetSourceFilePath(fileName);

                //if (codeViewer.Url == null)
                {
                    codeViewer.Navigate("about:blank");
                    codeViewer.Navigated +=
                        delegate
                            {
                                codeViewer.Document.Write("<body></body>");
                                codeViewer.Document.Body.Style = "background-color: #F8F8F8;";


                                codeViewer.Document.Body.InnerHtml =
                                    CodeViewerHelper.RenderFile(fileWithPath);
                            };

                }
            }
        }

        private void EnsureCodeViewerLoaded()
        {
            if (codeViewer == null)
            {
                codeViewer = new WebBrowser();
                this.demoCenterPanel.Controls.Add(codeViewer);
                codeViewer.Bounds = new Rectangle(
                    5, 
                    130,
                    this.demoCenterPanel.Width - 10,
                    this.demoCenterPanel.Height - 130
                    );

                codeViewer.Anchor = (AnchorStyles)15; //All
            }
        }

        private void EnsureCodeViewerUnloaded()
        {
            if (codeViewer != null)
            {
                this.demoCenterPanel.Controls.Add(codeViewer);
                codeViewer.Dispose();
                codeViewer = null;
            }
        }

        bool codeViewMode;

        private void LoadCodeView(bool cSharp)
        {
            if (this.exampleTreeNode != null)
            {
                codeViewMode = true;
                this.btnSelectCodeFile.Visible = true;
                this.exampleSplitContainer.Visible = false;
                this.descriptionPanel.Visible = false;
                this.demoCenterPanel.Height = this.mainDemoPanel.Height - 30;
                this.bottomImagePanel.SendToBack();

                this.btnSelectCodeFile.Items.Clear();

                ExamplesTreeNode treeNode = this.exampleTreeNode;

                string[] files;
                if (cSharp)
                {
                    files = treeNode.ExampleFiles;
                }
                else
                {
                    files = treeNode.ExampleFilesVB;
                }

                if (files.Length > 0)
                {
                    btnSelectCodeFile.Visible = true;
                    this.FillDropWithSourceFiles(files, btnSelectCodeFile.Items);
                    LoadFileInCodeViewer(files[0]);
                }
                else
                {
                    btnSelectCodeFile.Visible = false;
                }
            }
        }

        private void EnsureCodeViewModeUnloaded()
        {
            if (codeViewMode)
            {
                codeViewMode = false;
                this.btnSelectCodeFile.Visible = false;
                this.exampleSplitContainer.Visible = true;
                this.btnSelectCodeFile.Items.Clear();
                this.descriptionPanel.Visible = true;

                this.demoCenterPanel.Height = this.mainDemoPanel.Height - 152;
                this.bottomImagePanel.BringToFront();
                //this.panel6.BringToFront();

                EnsureCodeViewerUnloaded();

                if (this.codeViewTabStrip.SelectedTab != tabItemDemo)
                {
                    internalChange = true;
                    this.codeViewTabStrip.SelectedTab = tabItemDemo;
                    internalChange = false;
                }
            }
        }


        public void EnableButtons(QSFButtons enabled)
        {
            this.panelThemes.Visible = (enabled & QSFButtons.ChangeTheme) == QSFButtons.ChangeTheme;
        }

        private void radRotator1_ItemClicked(object sender, EventArgs e)
        {
            RadQSFRotatorFrame item = sender != null ? sender as RadQSFRotatorFrame : null;
            if (item == null || string.IsNullOrEmpty( item.ExecutionPath ))
                return;
            try
            {
                Process.Start( item.ExecutionPath );                
            }
            catch
            { }
        }

        void CarouselElement_ExampleStart( object sender, string selectedExampleText )
        {
            this.StartExampleInternal( selectedExampleText );
        }

        private void StartExampleInternal( string selectedExampleText )
        {
            
            RadTreeNode node = null;
            if (this.TreeView.SelectedNode != null)
            {                
                node = RadTreeView.ExecuteScalarCommand(
                this.TreeView.SelectedNode,
                -1,
                new FindByTextCommand(),
                 selectedExampleText ) as RadTreeNode;
            }
            else
            {                
                node = RadTreeView.ExecuteScalarCommand(
                this.TreeView.Nodes,
                -1,
                new FindByTextCommand(),
                 selectedExampleText ) as RadTreeNode;
            }

            if (node == null)
            {
                node = RadTreeView.ExecuteScalarCommand(
                this.TreeView.Nodes,
                -1,
                new FindByTextCommand(),
                 selectedExampleText) as RadTreeNode;
            }

            if (node != null)
            {
                this.TreeView.SelectedNode = node;
                this.TreeView.BringIntoView( node );
                //this.AddCurrentNodeToHistory();

                ExamplesTreeNode exampleNode = node as ExamplesTreeNode;
                if (exampleNode != null && exampleNode.NodeType == NodeType.Example && exampleNode.Form!=null)
                {
                    Form form = exampleNode.Form as Form;

                    if (form != null)
                    {
                        form.StartPosition = FormStartPosition.CenterScreen;
                        form.Show();
                    }
                }
                else
                {
                    RadTreeNode firstNode = node.Nodes[0];
                    if (firstNode!=null)
                    {
                        this.TreeView.SelectedNode = firstNode;
                        this.TreeView.BringIntoView( firstNode );
                    }
                }
            }
        }

        private void splitContainer2_Panel1_Layout(object sender, LayoutEventArgs e)        
        {
        }

        private void toggleSettingsSplitter_Click(object sender, EventArgs e)
        {
            if (settingsPanelExpanded)
            {
                CollapseSettingsPanel();
            }
            else
            {
                ExpandSettingsPanel();
            }
        }

        private void ExpandSettingsPanel()
        {
            this.exampleSplitContainer.SplitterDistance = this.exampleSplitContainer.Width - settingsPanelExpandedWidth;
            this.toggleSettingsSplitter.SplitterArrowDirection = ArrowDirection.Right;
            settingsPanelExpanded = true;
        }

        private void CollapseSettingsPanel()
        {
            this.exampleSplitContainer.SplitterDistance = this.exampleSplitContainer.Width - settingsPanelCollapsedWidth;
            this.toggleSettingsSplitter.SplitterArrowDirection = ArrowDirection.Left;
            settingsPanelExpanded = false;
        }        

        private Image GetSmallTelerikIcon()
        {
            if (this.smallTelerikIcon == null)
            {
                this.smallTelerikIcon = LoadImage("Telerik.QuickStart.WinControls.Resources.Images.TelerikIconSmall.png");
            }

            return this.smallTelerikIcon;
        }

        private Image GetBigTelerikIcon()
        {
            if (this.bigTelerikIcon == null)
            {
                this.bigTelerikIcon = this.telerikPicture.Image;
            }

            return this.bigTelerikIcon;
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.Padding = new Padding(0, 0, 0, 0);
                this.Shape = null;
                this.Region = null;

                this.telerikPicture.Bounds = new Rectangle(12, 12, 44, 44);
                this.telerikPicture.Image = GetSmallTelerikIcon();
                this.CreatePictureBoxShape();
                this.radControlsLabel.Location = new Point(62, 8);
            }
            else
            {
                this.Padding = new Padding(0, 8, 0, 0);
                this.Shape = myShape;

                this.telerikPicture.Bounds = new Rectangle(16, 0, 63, 63);
                this.telerikPicture.Image = GetBigTelerikIcon();
                this.CreatePictureBoxShape();
                this.radControlsLabel.Location = new Point(88, 3);
            }
        }

        private void pictureBox2_DoubleClick(object sender, EventArgs e)
        {
#if DEBUG
            new RadControlSpyForm().Show();
#endif
        }

        private void exampleSplitContainer_Panel2_Layout(object sender, LayoutEventArgs e)
        {
            toggleSettingsSplitter.Height = exampleSplitContainer.Panel2.Height - exampleSplitContainer.Panel2.Padding.Vertical;
            this.toggleSettingsSplitter.Location =
                new Point(0,(exampleSplitContainer.Panel1.Height - toggleSettingsSplitter.Height) / 2);
        }

        private void MainForm_Layout(object sender, LayoutEventArgs e)
        {
            int splitterLeft = this.panelNavigationContainer.Right - 1;

            if (treeViewCollapsed)
            {
                splitterLeft = paddingLeft;
            }

            this.treeViewSplitter.Bounds = new Rectangle(
                splitterLeft + 1,
                (this.Height - this.radTitleBar1.Height - qsfSplitterHeight) / 2 + 40,
                treeViewSplitterWidth,
                qsfSplitterHeight
                );
        }

        private void treeViewSplitter_Click(object sender, EventArgs e)
        {
            treeViewCollapsed = !treeViewCollapsed;

            UpdateTreeViewExpanded();

            this.PerformLayout();
        }

        private void UpdateTreeViewExpanded()
        {
            int demoPanelOffset = paddingLeft + panelNavigationContainer.Width;

            if (!treeViewCollapsed)
            {
                //expand treeview
                this.panelNavigationContainer.Visible = true;

                demoTopPanel.Left = demoPanelOffset + paddingLeft;
                demoTopPanel.Width = this.radTitleBar1.Width - demoPanelOffset - paddingHorizontal;

                this.mainDemoPanel.Left = 0;
                this.mainDemoPanel.Width = this.Width;

                this.treeViewSplitter.SplitterArrowDirection = ArrowDirection.Left;
            }
            else
            {
                //collapse treeview
                this.panelNavigationContainer.Visible = false;

                demoTopPanel.Left = paddingLeft;
                demoTopPanel.Width = this.Width - paddingHorizontal;

                this.mainDemoPanel.Left = -demoPanelOffset;
                this.mainDemoPanel.Width = this.Width + demoPanelOffset;

                this.treeViewSplitter.SplitterArrowDirection = ArrowDirection.Right;
            }
        }

        private void RerouteMoseEventsToTitleBar(Control control)
        {
            control.MouseMove += this.reroute_MouseMove;
            control.MouseDown += this.reroute_MouseDown;
            control.MouseUp += this.reroute_MouseUp;
            control.MouseDoubleClick += this.reroute_MouseDoubleClick;
        }

        void reroute_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.radTitleBar1.TitleBarElement.HandleDoubleClickClick();
        }

        void reroute_MouseUp(object sender, MouseEventArgs e)
        {
            this.radTitleBar1.TitleBarElement.HandleMouseUp();
        }

        void reroute_MouseMove(object sender, MouseEventArgs e)
        {
            Point point = this.PointToClient(Cursor.Position);
            MouseEventArgs args = new MouseEventArgs(e.Button, e.Clicks, point.X, point.Y, e.Delta);
            this.radTitleBar1.TitleBarElement.HandleMouseMove(args, this);
        }

        void reroute_MouseDown(object sender, MouseEventArgs e)
        {
            Point point = this.PointToClient(Cursor.Position);
            MouseEventArgs args = new MouseEventArgs(e.Button, e.Clicks, point.X, point.Y, e.Delta);
            this.radTitleBar1.TitleBarElement.HandleMouseDown(args);
        }

        private void EnsureWelcomeScreenImagesLoaded()
        {
            if (welcomeImagesLoaded)
            {
                return;
            }

            imageWelcomeBottomLeft =
                this.LoadImage("Telerik.QuickStart.WinControls.Resources.Images.WelcomeBottomLeft.png");
            imageWelcomeBottomCenter =this.LoadImage("Telerik.QuickStart.WinControls.Resources.Images.WelcomeBottomCenter.png");
            imageWelcomeBottomRight =
                this.LoadImage("Telerik.QuickStart.WinControls.Resources.Images.WelcomeBottomRight.png");

            welcomeImagesLoaded = true;
        }

        private void EnsureMainImagesLoaded()
        {
            if (imageMainBottomLeft == null)
            {
                imageMainBottomLeft =
                    LoadImage("Telerik.QuickStart.WinControls.Resources.Images.MainBottomLeft.png");
                imageMainBottomCenter =
                    LoadImage("Telerik.QuickStart.WinControls.Resources.Images.MainBottomCenter.png");
                imageMainBottomRight =
                    LoadImage("Telerik.QuickStart.WinControls.Resources.Images.MainBottomRight.png");
            }
        }
        
        private void LoadWelcomeScreen()
        {
            this.treeViewCollapsed = false;
            UpdateTreeViewExpanded();
            EnsureCodeViewModeUnloaded();

            if (imageWelcomeBack == null)
            {
                imageWelcomeBack = this.LoadImage("Telerik.QuickStart.WinControls.Resources.Images.WelcomeMainBack.png");                
            }

            this.EnsureWelcomeScreenImagesLoaded();

            if (this.imageDemosBack == null)
            {
                this.imageDemosBack = this.mainDemoPanel.BackgroundImage;
            }

            if (welcomeScreen == null)
            {
                this.welcomeScreen = new WelcomeScreenTop();
                this.mainDemoPanel.Controls.Add(this.welcomeScreen);
            }
            else
            {
                welcomeScreen.AnimateFlyIn();
            }

            if (welcomeScreenBottom == null)
            {
                this.welcomeScreenBottom = new WelcomeScreenBottom();
                this.bottomImagePanel.Controls.Add(this.welcomeScreenBottom);
            }

            if (originalBottomImagePanelHeight == 0)
            {
                originalBottomImagePanelHeight = this.bottomImagePanel.Height;
            }

            this.bottomImagePanel.Height = 209;

            this.mainDemoPanel.BackgroundImage = this.imageWelcomeBack;

            this.bottomImagePanel.TopLeftImage = this.imageWelcomeBottomLeft;
            this.bottomImagePanel.BackgroundImage = this.imageWelcomeBottomCenter;
            this.bottomImagePanel.TopRightImage = this.imageWelcomeBottomRight;

            this.descriptionPanel.Visible = false;

            welcomeScreen.Bounds = new Rectangle(
                paddingLeft + panelNavigationContainer.Width + treeViewSplitterWidth - 2,
                0,
                this.Width - treeViewSplitterWidth - panelNavigationContainer.Width - paddingLeft,
                mainDemoPanel.Height - this.bottomImagePanel.Height);

            welcomeScreen.Anchor = (AnchorStyles)(15); //All
            welcomeScreen.BringToFront();

            welcomeScreenBottom.Location = new Point(
                descriptionPanel.Left +
                ((this.bottomImagePanel.Width - descriptionPanel.Left) - welcomeScreenBottom.Width)/2,
                descriptionPanel.Top);

            welcomeScreenBottom.Anchor = AnchorStyles.Top;

            this.topImagePanel.Height = 82;
            this.demoTopPanel.Visible = false;
            this.demoCenterPanel.Visible = false;
            this.treeViewSplitter.Visible = false;
        }

        private void EnsureWelcomeScreenHidden()
        {
            if (this.welcomeScreen != null)
            {
                this.UnloadWelcomeScreen();
            }
        }

        private void UnloadWelcomeScreen()
        {
            if (welcomeScreen == null)
            {
                return;
            }

            EnsureMainImagesLoaded();

            this.Controls.Remove(this.welcomeScreen);
            this.bottomImagePanel.Controls.Remove(this.welcomeScreenBottom);

            this.mainDemoPanel.BackgroundImage = this.imageDemosBack;

            this.bottomImagePanel.TopLeftImage = this.imageMainBottomLeft;
            this.bottomImagePanel.BackgroundImage = this.imageMainBottomCenter;
            this.bottomImagePanel.TopRightImage = this.imageMainBottomRight;

            this.bottomImagePanel.Height = originalBottomImagePanelHeight;

            this.topImagePanel.Height = 160;
            this.demoTopPanel.Visible = true;
            this.demoCenterPanel.Visible = true;
            this.treeViewSplitter.Visible = true;

            this.descriptionPanel.Visible = true;

            this.welcomeScreen.Dispose();
            this.welcomeScreen = null;

            this.welcomeScreenBottom.Dispose();
            this.welcomeScreenBottom = null;

            GC.Collect(3);
        }

        private void telerikPicture_Click(object sender, EventArgs e)
        {
            this.welcomeScreenNode.Selected = true;
        }

        private void labelBreadcrumb_Click(object sender, EventArgs e)
        {
            if (exampleTreeNode != null)
            {
                RadTreeNode rootNode = this.GetRootNode(exampleTreeNode);

                this.treeViewDemoNavigation.SelectedNode = rootNode;
            }
        }

        private void codeViewTabStrip_TabSelected(object sender, TabEventArgs args)
        {
            if (internalChange)
            {
                return;
            }

            if (args.TabItem == this.tabItemCSharp)
            {
                this.LoadCodeView(true);
            }
            else if (args.TabItem == this.tabItemVB)
            {
                this.LoadCodeView(false);
            }
            else if (args.TabItem == this.tabItemDemo)
            {
                this.EnsureCodeViewModeUnloaded();
            }
        }

        private void btnSetBreezeRed_Click(object sender, EventArgs e)
        {

        }

        private void treeViewDemoNavigation_NodeMouseDown(object sender, RadTreeViewMouseEventArgs e)
        {
           
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.telerik.com");
        }

        private void btnForums_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.telerik.com/community/forums.aspx");
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.telerik.com/search.aspx");
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.telerik.com/help/winforms/overview.html");
        }

        private void btnLoadTheme_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (ofd.FileName.EndsWith(".tssp"))
                {
                    ThemeResolutionService.LoadPackageFile(ofd.FileName);
                    return;
                }
                
                using (XmlReader reader = XmlReader.Create(ofd.FileName) )
                {
                    XmlTheme theme = XmlTheme.LoadFromReader(reader);
                    Theme.Deserialize(theme);
                }
            }
        }

        private void radButton1_Click(object sender, EventArgs e)
        {

        }
    }

	public class RadControlNameComparer : IComparer<RadControl>
	{
		#region IComparer<RadControl> Members

		public int Compare(RadControl x, RadControl y)
		{
			return x.GetType().Name.CompareTo(y.GetType().Name);
		}

		#endregion
	}
}
