protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
        {
            if (Gui2UtilConnector.Instance.IsBusy || BufferingPlayerFactory != null) return; // wait for any background action e.g. dynamic category discovery to finish
            if (control == GUI_facadeView)
            {
                if (actionType == Action.ActionType.ACTION_SELECT_ITEM)
                {
                    currentFilter.Clear();
                    GUIPropertyManager.SetProperty("#OnlineVideos.filter", string.Empty);
                    switch (CurrentState)
                    {
                        case State.groups:
                            selectedSitesGroup = GUI_facadeView.SelectedListItem as OnlineVideosGuiListItem;
                            if (selectedSitesGroup.Item is SitesGroup)
                                DisplaySites();
                            else
                            {
                                SelectedSite = selectedSitesGroup.Item as Sites.SiteUtilBase;
                                DisplayCategories(null, true);
                            }
                            break;
                        case State.sites:
                            if (GUI_facadeView.SelectedListItem.Label == "..")
                            {
                                ShowPreviousMenu();
                            }
                            else
                            {
                                SelectedSite = (GUI_facadeView.SelectedListItem as OnlineVideosGuiListItem).Item as Sites.SiteUtilBase;
                                DisplayCategories(null, true);
                            }
                            break;
                        case State.categories:
                            if (GUI_facadeView.SelectedListItem.Label == "..")
                            {
                                ShowPreviousMenu();
                            }
                            else
                            {
                                Category categoryToDisplay = (GUI_facadeView.SelectedListItem as OnlineVideosGuiListItem).Item as Category;
                                if (categoryToDisplay is NextPageCategory)
                                {
                                    DisplayCategories_NextPage(categoryToDisplay as NextPageCategory);
                                }
                                else if (categoryToDisplay is Sites.FavoriteUtil.FavoriteCategory)
                                {
                                    Gui2UtilConnector.Instance.ExecuteInBackgroundAndCallback(delegate()
                                    {
                                        var favCat = categoryToDisplay as Sites.FavoriteUtil.FavoriteCategory;
                                        if (favCat.SiteCategory == null) favCat.DiscoverSiteCategory();
                                        return favCat;
                                    },
                                    delegate(bool success, object result)
                                    {
                                        if (success)
                                        {
                                            var favCat = result as Sites.FavoriteUtil.FavoriteCategory;
                                            if (favCat != null && favCat.SiteCategory != null)
                                            {
                                                currentNavigationContextSwitch = new NavigationContextSwitch()
                                                {
                                                    ReturnToUtil = SelectedSite,
                                                    ReturnToCategory = categoryToDisplay.ParentCategory,
                                                    GoToUtil = favCat.Site,
                                                    GoToCategory = favCat.SiteCategory,
                                                    BridgeCategory = favCat
                                                };
                                                SelectedSite = currentNavigationContextSwitch.GoToUtil;
                                                if (currentNavigationContextSwitch.GoToCategory.HasSubCategories)
                                                    DisplayCategories(currentNavigationContextSwitch.GoToCategory, true);
                                                else
                                                    DisplayVideos_Category(currentNavigationContextSwitch.GoToCategory, false);
                                            }
                                            else
                                            {
                                                GUIDialogNotify dlg_error = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                                                if (dlg_error != null)
                                                {
                                                    dlg_error.Reset();
                                                    dlg_error.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                                                    dlg_error.SetHeading(PluginConfiguration.Instance.BasicHomeScreenName);
                                                    dlg_error.SetText(string.Format("{0}: {1}", Translation.Instance.Error, Translation.Instance.CategoryNotFound));
                                                    dlg_error.DoModal(GUIWindowManager.ActiveWindow);
                                                }
                                            }
                                        }
                                    },
                                    Translation.Instance.GettingDynamicCategories, true);
                                }
                                else if (categoryToDisplay.HasSubCategories)
                                {
                                    DisplayCategories(categoryToDisplay, true);
                                }
                                else
                                {
                                    DisplayVideos_Category(categoryToDisplay, false);
                                }
                            }
                            break;
                        case State.videos:
                            ImageDownloader.StopDownload = true;
                            if (GUI_facadeView.SelectedListItem.Label == "..")
                            {
                                ShowPreviousMenu();
                            }
                            else if (GUI_facadeView.SelectedListItem.Label == Translation.Instance.NextPage)
                            {
                                DisplayVideos_NextPage();
                            }
                            else
                            {
                                selectedVideo = (GUI_facadeView.SelectedListItem as OnlineVideosGuiListItem).Item as VideoInfo;
                                if (SelectedSite is IChoice && selectedVideo.HasDetails)
                                {
                                    // show details view
                                    DisplayDetails();
                                }
                                else if (SelectedSite is Sites.FavoriteUtil && selectedVideo.HasDetails &&
                                    (selectedCategory is Sites.FavoriteUtil.FavoriteCategory && (selectedCategory as Sites.FavoriteUtil.FavoriteCategory).Site is IChoice))
                                {
                                    SelectedSite = (selectedCategory as Sites.FavoriteUtil.FavoriteCategory).Site;
                                    // show details view
                                    DisplayDetails();
                                }
                                else
                                {
                                    //play the video
                                    currentPlaylist = null;
                                    currentPlayingItem = null;

                                    Play_Step1(new PlayListItem(null, null)
                                            {
                                                Type = MediaPortal.Playlists.PlayListItem.PlayListItemType.VideoStream,
                                                Video = selectedVideo,
                                                Util = selectedSite is Sites.FavoriteUtil ? OnlineVideoSettings.Instance.SiteUtilsList[(selectedVideo as FavoriteDbVideoInfo).SiteName] : selectedSite
                                            }, true);
                                }
                            }
                            break;
                    }
                }
                else if (CurrentState == State.videos && !(SelectedSite is IChoice && selectedVideo.HasDetails) &&
                    (actionType == Action.ActionType.ACTION_MUSIC_PLAY || actionType == Action.ActionType.ACTION_PLAY))
                {
                    VideoInfo videoPressedPlayOn = (GUI_facadeView.SelectedListItem as OnlineVideosGuiListItem).Item as VideoInfo;
                    if (videoPressedPlayOn != null)
                    {
                        ImageDownloader.StopDownload = true;

                        currentFilter.Clear();
                        GUIPropertyManager.SetProperty("#OnlineVideos.filter", string.Empty);

                        selectedVideo = videoPressedPlayOn;

                        //play the video
                        currentPlaylist = null;
                        currentPlayingItem = null;

                        Play_Step1(new PlayListItem(null, null)
                        {
                            Type = MediaPortal.Playlists.PlayListItem.PlayListItemType.VideoStream,
                            Video = selectedVideo,
                            Util = selectedSite is Sites.FavoriteUtil ? OnlineVideoSettings.Instance.SiteUtilsList[(selectedVideo as FavoriteDbVideoInfo).SiteName] : selectedSite
                        }, true, true);
                    }
                }
                else if (CurrentState == State.videos && actionType == Action.ActionType.ACTION_SHOW_INFO)
                {
                    // toggles showing detailed info about a selectected video - is automatically reset when leaving videos view
                    ExtendedVideoInfo = !ExtendedVideoInfo;
                }
            }
            else if (control == GUI_infoList && CurrentState == State.details &&
                (actionType == Action.ActionType.ACTION_SELECT_ITEM || actionType == Action.ActionType.ACTION_MUSIC_PLAY || actionType == Action.ActionType.ACTION_PLAY))
            {
                ImageDownloader.StopDownload = true;
                if (GUI_infoList.SelectedListItemIndex == 0)
                {
                    ShowPreviousMenu();
                }
                else
                {
                    selectedClipIndex = GUI_infoList.SelectedListItemIndex;
                    //play the video
                    currentPlaylist = null;
                    currentPlayingItem = null;
                    Play_Step1(new PlayListItem(null, null)
                    {
                        Type = MediaPortal.Playlists.PlayListItem.PlayListItemType.VideoStream,
                        Video = (GUI_infoList.SelectedListItem as OnlineVideosGuiListItem).Item as VideoInfo,
                        Util = selectedSite is Sites.FavoriteUtil ? OnlineVideoSettings.Instance.SiteUtilsList[(selectedVideo as FavoriteDbVideoInfo).SiteName] : selectedSite
                    }, true, actionType != Action.ActionType.ACTION_SELECT_ITEM);
                }
            }
            else if (control == GUI_btnViewAs)
            {
                ToggleFacadeViewMode();
                // store as preferred layout in DB
                if (SelectedSite != null && PluginConfiguration.Instance.StoreLayoutPerCategory && (currentState == State.categories || currentState == State.videos))
                {
                    FavoritesDatabase.Instance.SetPreferredLayout(SelectedSite.Settings.Name, selectedCategory, (int)currentView);
                }
            }
            else if (control == GUI_btnMaxResult)
            {
                GUIControl.SelectItemControl(GetID, GUI_btnMaxResult.GetID, GUI_btnMaxResult.SelectedItem);
            }
            else if (control == GUI_btnOrderBy)
            {
                GUIControl.SelectItemControl(GetID, GUI_btnOrderBy.GetID, GUI_btnOrderBy.SelectedItem);
                if (CurrentState == State.sites) PluginConfiguration.Instance.siteOrder = (PluginConfiguration.SiteOrder)GUI_btnOrderBy.SelectedItem;
            }
            else if (control == GUI_btnTimeFrame)
            {
                GUIControl.SelectItemControl(GetID, GUI_btnTimeFrame.GetID, GUI_btnTimeFrame.SelectedItem);
            }
            else if (control == GUI_btnUpdate)
            {
                GUIControl.UnfocusControl(GetID, GUI_btnUpdate.GetID);
                switch (CurrentState)
                {
                    case State.sites: DisplaySites(); break;
                    case State.videos: DisplayVideos_Filter(); break;
                }
            }
            else if (control == GUI_btnSearchCategories)
            {
                GUIControl.SelectItemControl(GetID, GUI_btnSearchCategories.GetID, GUI_btnSearchCategories.SelectedItem);
            }
            else if (control == GUI_btnSearch)
            {
                Display_SearchResults();
            }
            else if (control == GUI_btnEnterPin)
            {
                string pin = String.Empty;
                if (GetUserInputString(ref pin, true))
                {
                    if (pin == PluginConfiguration.Instance.pinAgeConfirmation)
                    {
                        OnlineVideoSettings.Instance.AgeConfirmed = true;
                        GUIControl.UnfocusControl(GetID, GUI_btnEnterPin.GetID);
                        if (CurrentState == State.groups) DisplayGroups();
                        else DisplaySites();
                    }
                }
            }
            else if (control == GUI_btnCurrentDownloads)
            {
                // go to current downloads
                Sites.SiteUtilBase aSite = null;
                if (OnlineVideoSettings.Instance.SiteUtilsList.TryGetValue(Translation.Instance.DownloadedVideos, out aSite))
                {
                    Gui2UtilConnector.Instance.ExecuteInBackgroundAndCallback(delegate()
                    {
                        if (!aSite.Settings.DynamicCategoriesDiscovered)
                        {
                            Log.Instance.Info("Looking for dynamic categories on Site '{0}'", aSite.Settings.Name);
                            int foundCategories = aSite.DiscoverDynamicCategories();
                            Log.Instance.Info("Found {0} dynamic categories on Site '{1}'", foundCategories, aSite.Settings.Name);
                        }
                        return aSite.Settings.Categories;
                    },
                    delegate(bool success, object result)
                    {
                        if (success)
                        {
                            Category aCategory = aSite.Settings.Categories.FirstOrDefault(c => c.Name == Translation.Instance.Downloading);
                            if (aCategory != null)
                            {
                                SelectedSite = aSite;
                                selectedCategory = aCategory;
                                DisplayVideos_Category(aCategory, true);
                            }
                        }
                    },
                    Translation.Instance.GettingDynamicCategories, true);
                }
            }
            base.OnClicked(controlId, control, actionType);
        }
        private bool SetVideosToFacade(List<VideoInfo> videos, VideosMode mode, bool append = false)
        {
            // Check for received data
            if (videos == null || videos.Count == 0)
            {
                GUIDialogNotify dlg_error = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                if (dlg_error != null)
                {
                    dlg_error.Reset();
                    dlg_error.SetImage(SiteImageExistenceCache.GetImageForSite("OnlineVideos", type: "Icon"));
                    dlg_error.SetHeading(PluginConfiguration.Instance.BasicHomeScreenName);
                    dlg_error.SetText(Translation.Instance.NoVideoFound);
                    dlg_error.DoModal(GUIWindowManager.ActiveWindow);
                }
                return false;
            }

            int indextoSelect = -1;
            if (append)
            {
                currentFilter.Clear();
                indextoSelect = currentVideoList.Count + 1;
                currentVideoList.AddRange(videos);
            }
            else
            {
                currentVideoList = videos;
            }

            GUIControl.ClearControl(GetID, GUI_facadeView.GetID);
            currentFacadeItems.Clear();

            // add the first item that will go to the previous menu
            OnlineVideosGuiListItem backItem = new OnlineVideosGuiListItem("..");
            backItem.ItemId = 0;
            backItem.IsFolder = true;
            backItem.OnItemSelected += OnItemSelected;
            MediaPortal.Util.Utils.SetDefaultIcons(backItem);
            GUI_facadeView.Add(backItem);
            currentFacadeItems.Add(backItem);

            // add the items
            Dictionary<string, bool> imageHash = new Dictionary<string, bool>();
            currentFilter.StartMatching();

            foreach (VideoInfo videoInfo in currentVideoList)
            {
                videoInfo.CleanDescriptionAndTitle();
                if (!currentFilter.Matches(videoInfo.Title) || FilterOut(videoInfo.Title) || FilterOut(videoInfo.Description)) continue;
                if (!string.IsNullOrEmpty(videosVKfilter) && !videoInfo.Title.ToLower().Contains(videosVKfilter.ToLower())) continue;

                OnlineVideosGuiListItem listItem = new OnlineVideosGuiListItem(videoInfo);
                listItem.ItemId = GUI_facadeView.Count;
                listItem.OnItemSelected += OnItemSelected;
                GUI_facadeView.Add(listItem);
                currentFacadeItems.Add(listItem);

                if (listItem.Item == selectedVideo) GUI_facadeView.SelectedListItemIndex = GUI_facadeView.Count - 1;
                if (!string.IsNullOrEmpty(videoInfo.Thumb)) imageHash[videoInfo.Thumb] = true;
            }
            // fall back to list view if there are no items with thumbs or more than one item and all have the same thumb
            suggestedView = null;
            if ((GUI_facadeView.Count > 1 && imageHash.Count == 0) || (GUI_facadeView.Count > 2 && imageHash.Count == 1)) suggestedView = GUIFacadeControl.Layout.List;

            if (SelectedSite.HasNextPage)
            {
                OnlineVideosGuiListItem nextPageItem = new OnlineVideosGuiListItem(Translation.Instance.NextPage);
                nextPageItem.ItemId = GUI_facadeView.Count;
                nextPageItem.IsFolder = true;
                nextPageItem.IconImage = "OnlineVideos\\NextPage.png";
                nextPageItem.IconImageBig = "OnlineVideos\\NextPage.png";
                nextPageItem.ThumbnailImage = "OnlineVideos\\NextPage.png";
                nextPageItem.OnItemSelected += OnItemSelected;
                GUI_facadeView.Add(nextPageItem);
                currentFacadeItems.Add(nextPageItem);
            }

            if (indextoSelect > -1 && indextoSelect < GUI_facadeView.Count) GUI_facadeView.SelectedListItemIndex = indextoSelect;

            if (imageHash.Count > 0) ImageDownloader.GetImages<VideoInfo>(currentVideoList);

            string filterstring = currentFilter.ToString();
            if (!string.IsNullOrEmpty(filterstring) && !string.IsNullOrEmpty(videosVKfilter)) filterstring += " & ";
            filterstring += videosVKfilter;
            GUIPropertyManager.SetProperty("#OnlineVideos.filter", filterstring);

            currentVideosDisplayMode = mode;
            CurrentState = State.videos;
            if (PluginConfiguration.Instance.StoreLayoutPerCategory) suggestedView = FavoritesDatabase.Instance.GetPreferredLayout(SelectedSite.Settings.Name, selectedCategory) ?? suggestedView;
            UpdateViewState();
            return true;
        }
 public void ResetToFirstView()
 {
     selectedSitesGroup = null;
     SelectedSite = null;
     selectedCategory = null;
     selectedVideo = null;
     currentVideoList = new List<VideoInfo>();
     currentTrailerList = new List<DetailVideoInfo>();
     currentNavigationContextSwitch = null;
     currentPlaylist = null;
     currentPlayingItem = null;
     CurrentState = State.groups;
 }
        private void SetCategoriesToFacade(Category parentCategory, IList<Category> categories, bool? diveDownOrUpIfSingle, bool append = false)
        {
            if (loadParamInfo != null && loadParamInfo.Site == SelectedSite.Settings.Name && parentCategory == null && !string.IsNullOrEmpty(loadParamInfo.Category))
            {
                var foundCat = categories.FirstOrDefault(r => r.Name == loadParamInfo.Category);
                if (foundCat != null)
                {
                    if (foundCat.HasSubCategories)
                    {
                        DisplayCategories(foundCat, true);
                    }
                    else
                    {
                        DisplayVideos_Category(foundCat, false);
                    }
                }
                return;
            }

            int categoryIndexToSelect = (categories != null && categories.Count > 0) ? 1 : 0; // select the first category by default if there is one
            if (append)
            {
                currentFilter.Clear();
                categoryIndexToSelect = GUI_facadeView.Count - 1;
            }

            GUIControl.ClearControl(GetID, GUI_facadeView.GetID);
            currentFacadeItems.Clear();

            // add the first item that will go to the previous menu
            OnlineVideosGuiListItem loListItem;
            loListItem = new OnlineVideosGuiListItem("..");
            loListItem.IsFolder = true;
            loListItem.ItemId = 0;
            loListItem.OnItemSelected += OnItemSelected;
            MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
            GUI_facadeView.Add(loListItem);
            currentFacadeItems.Add(loListItem);

            Dictionary<string, bool> imageHash = new Dictionary<string, bool>();
            suggestedView = null;
            currentFilter.StartMatching();
            if (categories != null)
            {
                foreach (Category loCat in categories)
                {
                    if (currentFilter.Matches(loCat.Name))
                    {
                        loListItem = new OnlineVideosGuiListItem(loCat);
                        loListItem.ItemId = GUI_facadeView.Count;
                        if (loCat is NextPageCategory)
                        {
                            loListItem.IconImage = "OnlineVideos\\NextPage.png";
                            loListItem.IconImageBig = "OnlineVideos\\NextPage.png";
                            loListItem.ThumbnailImage = "OnlineVideos\\NextPage.png";
                        }
                        else
                        {
                            if (FavoritedCategoriesOfSelectedSite.Contains(loCat.RecursiveName("|")))
                            {
                                loListItem.IsPlayed = true;
                                loListItem.PinImage = SiteImageExistenceCache.GetImageForSite(Translation.Instance.Favourites, type: "Icon");
                            }
                        }
                        if (!string.IsNullOrEmpty(loCat.Thumb)) imageHash[loCat.Thumb] = true;
                        loListItem.OnItemSelected += OnItemSelected;
                        if (loCat == selectedCategory) categoryIndexToSelect = GUI_facadeView.Count; // select the category that was previously selected
                        GUI_facadeView.Add(loListItem);
                        currentFacadeItems.Add(loListItem);
                    }
                }

                if (imageHash.Count > 0) ImageDownloader.GetImages<Category>(categories);
                if ((GUI_facadeView.Count > 1 && imageHash.Count == 0) || (GUI_facadeView.Count > 2 && imageHash.Count == 1)) suggestedView = GUIFacadeControl.Layout.List;
                // only set selected index when not doing an automatic dive up (MediaPortal would set the old selected index asynchroneously)
                if (!(categories.Count == 1 && diveDownOrUpIfSingle == false)) GUI_facadeView.SelectedListItemIndex = categoryIndexToSelect;
            }

            GUIPropertyManager.SetProperty("#OnlineVideos.filter", currentFilter.ToString());
            CurrentState = State.categories;
            selectedCategory = parentCategory;
            if (PluginConfiguration.Instance.StoreLayoutPerCategory) suggestedView = FavoritesDatabase.Instance.GetPreferredLayout(SelectedSite.Settings.Name, selectedCategory) ?? suggestedView;
            UpdateViewState();

            // automatically browse up or down if only showing a single category and parameter was set
            if (categories.Count == 1 && diveDownOrUpIfSingle != null && SelectedSite.AllowDiveDownOrUpIfSingle)
            {
                if (diveDownOrUpIfSingle.Value)
                    OnClicked(GUI_facadeView.GetID, GUI_facadeView, Action.ActionType.ACTION_SELECT_ITEM);
                else
                    ShowPreviousMenu();
            }
        }
        private void SetVideosToInfoList(List<DetailVideoInfo> videos)
        {
            SetGuiProperties_ExtendedVideoInfo(null, false);
            currentTrailerList = videos;
            GUIControl.ClearControl(GetID, GUI_facadeView.GetID);
            GUIControl.ClearControl(GetID, GUI_infoList.GetID);
            OnlineVideosGuiListItem loListItem = new OnlineVideosGuiListItem("..");
            loListItem.IsFolder = true;
            loListItem.ItemId = 0;
            loListItem.OnItemSelected += OnItemSelected;
            MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
            GUI_infoList.Add(loListItem);
            Dictionary<string, bool> imageHash = new Dictionary<string, bool>();
            if (videos != null)
            {
                foreach (var video in videos)
                {
                    loListItem = new OnlineVideosGuiListItem(video);
                    loListItem.ItemId = GUI_infoList.Count;
                    loListItem.OnItemSelected += OnItemSelected;
                    GUI_infoList.Add(loListItem);
                    if (!string.IsNullOrEmpty(video.Thumb)) imageHash[video.Thumb] = true;
                }
            }
            if (imageHash.Count > 0) ImageDownloader.GetImages<DetailVideoInfo>(currentTrailerList);

            if (videos.Count > 0)
            {
                if (selectedClipIndex == 0 || selectedClipIndex >= GUI_infoList.Count) selectedClipIndex = 1;
                GUI_infoList.SelectedListItemIndex = selectedClipIndex;
                OnItemSelected(GUI_infoList[selectedClipIndex], GUI_infoList);
            }

            UpdateViewState();
        }
        private void DisplaySites()
        {
            lastSearchQuery = string.Empty;
            selectedCategory = null;
            ResetSelectedSite();
            GUIControl.ClearControl(GetID, GUI_facadeView.GetID);
            currentFacadeItems.Clear();

            // set order by options
            GUI_btnOrderBy.Clear();
            GUIControl.AddItemLabelControl(GetID, GUI_btnOrderBy.GetID, Translation.Instance.Default);
            GUIControl.AddItemLabelControl(GetID, GUI_btnOrderBy.GetID, Translation.Instance.Name);
            GUIControl.AddItemLabelControl(GetID, GUI_btnOrderBy.GetID, Translation.Instance.Language);
            GUI_btnOrderBy.SelectedItem = (int)PluginConfiguration.Instance.siteOrder;

            // previous selected group was actually a site or currently selected site Fav or Downl and groups enabled -> skip this step
            if (GroupsEnabled &&
                ((selectedSitesGroup != null && selectedSitesGroup.Item is Sites.SiteUtilBase) ||
                (selectedSite is Sites.FavoriteUtil || selectedSite is Sites.DownloadedVideoUtil)))
            {
                DisplayGroups();
                return;
            }
            var siteutils = OnlineVideoSettings.Instance.SiteUtilsList;
            string[] names = selectedSitesGroup == null ? siteutils.Keys.ToArray() : (selectedSitesGroup.Item as SitesGroup).Sites.ToArray();

            // get names in right order
            switch (PluginConfiguration.Instance.siteOrder)
            {
                case PluginConfiguration.SiteOrder.Name:
                    Array.Sort(names);
                    break;
                case PluginConfiguration.SiteOrder.Language:
                    Dictionary<string, List<string>> sitenames = new Dictionary<string, List<string>>();
                    foreach (string name in names)
                    {
                        Sites.SiteUtilBase aSite;
                        if (siteutils.TryGetValue(name, out aSite))
                        {
                            string key = string.IsNullOrEmpty(aSite.Settings.Language) ? "zzzzz" : aSite.Settings.Language; // puts empty lang at the end
                            List<string> listForLang = null;
                            if (!sitenames.TryGetValue(key, out listForLang)) { listForLang = new List<string>(); sitenames.Add(key, listForLang); }
                            listForLang.Add(aSite.Settings.Name);
                        }
                    }
                    string[] langs = new string[sitenames.Count];
                    sitenames.Keys.CopyTo(langs, 0);
                    Array.Sort(langs);
                    List<string> sortedByLang = new List<string>();
                    foreach (string lang in langs) sortedByLang.AddRange(sitenames[lang]);
                    names = sortedByLang.ToArray();
                    break;
            }

            if (GroupsEnabled)
            {
                // add the first item that will go to the groups menu
                OnlineVideosGuiListItem loListItem;
                loListItem = new OnlineVideosGuiListItem("..");
                loListItem.ItemId = 0;
                loListItem.IsFolder = true;
                loListItem.OnItemSelected += OnItemSelected;
                MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
                GUI_facadeView.Add(loListItem);
                currentFacadeItems.Add(loListItem);
            }

            int selectedSiteIndex = 0;  // used to remember the position of the last selected site
            currentFilter.StartMatching();
            foreach (string name in names)
            {
                Sites.SiteUtilBase aSite;
                if (currentFilter.Matches(name) &&
                    siteutils.TryGetValue(name, out aSite) &&
                    aSite.Settings.IsEnabled &&
                    !(GroupsEnabled & (aSite is Sites.FavoriteUtil | aSite is Sites.DownloadedVideoUtil)) && // don't show Favorites and Downloads site if groups are enabled (because they are added as groups)
                    (!aSite.Settings.ConfirmAge || !OnlineVideoSettings.Instance.UseAgeConfirmation || OnlineVideoSettings.Instance.AgeConfirmed))
                {
                    OnlineVideosGuiListItem loListItem = new OnlineVideosGuiListItem(aSite);
                    loListItem.OnItemSelected += OnItemSelected;
                    if (loListItem.Item == SelectedSite) selectedSiteIndex = GUI_facadeView.Count;
                    loListItem.ItemId = GUI_facadeView.Count;
                    GUI_facadeView.Add(loListItem);
                    currentFacadeItems.Add(loListItem);
                }
            }
            SelectedMaxResultIndex = -1;
            SelectedOrderByIndex = -1;
            SelectedSearchCategoryIndex = -1;
            SelectedTimeFrameIndex = -1;

            if (selectedSiteIndex < GUI_facadeView.Count)
                GUI_facadeView.SelectedListItemIndex = selectedSiteIndex;
            GUIPropertyManager.SetProperty("#OnlineVideos.filter", currentFilter.ToString());
            CurrentState = State.sites;
            UpdateViewState();
        }
 private void AddFavoritesAndDownloadsSitesToFacade()
 {
     Sites.SiteUtilBase aSite;
     if (OnlineVideoSettings.Instance.SiteUtilsList.TryGetValue(Translation.Instance.Favourites, out aSite))
     {
         OnlineVideosGuiListItem listItem = new OnlineVideosGuiListItem(aSite);
         listItem.OnItemSelected += OnItemSelected;
         listItem.ItemId = GUI_facadeView.Count;
         GUI_facadeView.Add(listItem);
         if (selectedSitesGroup != null && selectedSitesGroup.Label == listItem.Label) GUI_facadeView.SelectedListItemIndex = GUI_facadeView.Count - 1;
     }
     if (OnlineVideoSettings.Instance.SiteUtilsList.TryGetValue(Translation.Instance.DownloadedVideos, out aSite))
     {
         OnlineVideosGuiListItem listItem = new OnlineVideosGuiListItem(aSite);
         listItem.OnItemSelected += OnItemSelected;
         listItem.ItemId = GUI_facadeView.Count;
         GUI_facadeView.Add(listItem);
         if (selectedSitesGroup != null && selectedSitesGroup.Label == listItem.Label) GUI_facadeView.SelectedListItemIndex = GUI_facadeView.Count - 1;
     }
 }
        private void DisplayGroups()
        {
            var sitesGroups = PluginConfiguration.Instance.SitesGroups;
            if ((sitesGroups == null || sitesGroups.Count == 0) && PluginConfiguration.Instance.autoGroupByLang) sitesGroups = PluginConfiguration.Instance.CachedAutomaticSitesGroups;

            SelectedSite = null;
            GUIControl.ClearControl(GetID, GUI_facadeView.GetID);

            // add Favorites and Downloads Site as first two Groups (if they are available and user configured them to be first)
            if (OnlineVideoSettings.Instance.FavoritesFirst) AddFavoritesAndDownloadsSitesToFacade();

            HashSet<string> groupedSites = new HashSet<string>();
            foreach (SitesGroup sitesGroup in sitesGroups)
            {
                if (sitesGroup.Sites != null && sitesGroup.Sites.Count > 0)
                {
                    OnlineVideosGuiListItem loListItem = new OnlineVideosGuiListItem(sitesGroup);
                    loListItem.OnItemSelected += OnItemSelected;
                    loListItem.ItemId = GUI_facadeView.Count;
                    GUI_facadeView.Add(loListItem);
                    if (selectedSitesGroup != null && selectedSitesGroup.Label == sitesGroup.Name) GUI_facadeView.SelectedListItemIndex = GUI_facadeView.Count - 1;
                }

                foreach (string site in sitesGroup.Sites) groupedSites.Add(site);
            }

            // add the item for all ungrouped sites if there are any
            SitesGroup othersGroup = new SitesGroup() { Name = Translation.Instance.Others };
            foreach (string site in OnlineVideoSettings.Instance.SiteUtilsList.Keys)
                if (!groupedSites.Contains(site) && site != Translation.Instance.Favourites && site != Translation.Instance.DownloadedVideos)
                    othersGroup.Sites.Add(site);
            if (othersGroup.Sites.Count > 0)
            {
                OnlineVideosGuiListItem listItem = new OnlineVideosGuiListItem(othersGroup);
                listItem.OnItemSelected += OnItemSelected;
                listItem.ItemId = GUI_facadeView.Count;
                GUI_facadeView.Add(listItem);
                if (selectedSitesGroup != null && selectedSitesGroup.Label == othersGroup.Name) GUI_facadeView.SelectedListItemIndex = GUI_facadeView.Count - 1;
            }

            // add Favorites and Downloads Site as last two Groups (if they are available)
            if (!OnlineVideoSettings.Instance.FavoritesFirst) AddFavoritesAndDownloadsSitesToFacade();

            CurrentState = State.groups;
            UpdateViewState();
        }
        void DoPageLoad()
        {
            // called everytime the plugin is shown, after some other window was shown (also after fullscreen playback)
            if (PreviousWindowId != OnlineVideos.MediaPortal1.Player.GUIOnlineVideoFullscreen.WINDOW_FULLSCREEN_ONLINEVIDEO)
            {
                // reload settings that can be modified with the MPEI plugin
                PluginConfiguration.Instance.ReLoadRuntimeSettings();

                // if groups are now enabled/disabled we need to set the states accordingly
                if (GroupsEnabled)
                {
                    // showing sites, but groups are enabled and no group is selected -> show groups
                    if (CurrentState == State.sites && selectedSitesGroup == null)
                    {
                        CurrentState = State.groups;
                    }

                    // we might have to generate automatic groups if it is enabled now
                    if (PluginConfiguration.Instance.CachedAutomaticSitesGroups.Count == 0)
                    {
                        PluginConfiguration.Instance.BuildAutomaticSitesGroups();
                    }
                }
                else
                {
                    // showing groups, but groups are disabled -> show sites
                    if (CurrentState == State.groups)
                    {
                        CurrentState = State.sites;
                    }
                    selectedSitesGroup = null;
                }

                // reset the LoadParameterInfo
                loadParamInfo = null;

                string loadParam = null;
                // check if running version of mediaportal supports loading with parameter and handle _loadParameter
                System.Reflection.FieldInfo fi = typeof(GUIWindow).GetField("_loadParameter", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                if (fi != null)
                {
                    loadParam = (string)fi.GetValue(this);
                }
                // check for LoadParameters by GUIproperties if nothing was set by the _loadParameter
                if (string.IsNullOrEmpty(loadParam))
                {
                    loadParam = LoadParameterInfo.FromGuiProperties();
                }

                if (!string.IsNullOrEmpty(loadParam))
                {
                    Log.Instance.Info("Called with LoadParameter: '{0}'", loadParam);
                    loadParamInfo = new LoadParameterInfo(loadParam);

                    // set all state variables to reflect the state we were called with
                    currentNavigationContextSwitch = null;
                    if (!string.IsNullOrEmpty(loadParamInfo.Group))
                    {
                        SitesGroup group = PluginConfiguration.Instance.SitesGroups.FirstOrDefault(sg => sg.Name == loadParamInfo.Group);
                        if (group == null)
                        {
                            group = PluginConfiguration.Instance.CachedAutomaticSitesGroups.FirstOrDefault(sg => sg.Name == loadParamInfo.Group);
                        }
                        if (group != null)
                        {
                            selectedSitesGroup = new OnlineVideosGuiListItem(group);
                            CurrentState       = State.sites;
                        }
                    }
                    if (!string.IsNullOrEmpty(loadParamInfo.Site) && OnlineVideoSettings.Instance.SiteUtilsList.ContainsKey(loadParamInfo.Site))
                    {
                        SelectedSite     = OnlineVideoSettings.Instance.SiteUtilsList[loadParamInfo.Site];
                        CurrentState     = State.categories;
                        selectedCategory = null;
                    }
                    if (SelectedSite != null && SelectedSite.CanSearch && !string.IsNullOrEmpty(loadParamInfo.Search))
                    {
                        Display_SearchResults(loadParamInfo.Search);
                        return;
                    }
                }
            }

            Log.Instance.Info("DoPageLoad with CurrentState '{0}', PreviousWindowId '{1}'", CurrentState, PreviousWindowId);
            switch (CurrentState)
            {
            case State.groups: DisplayGroups(); break;

            case State.sites: DisplaySites(); break;

            case State.categories: DisplayCategories(selectedCategory); break;

            case State.videos: SetVideosToFacade(currentVideoList, currentVideosDisplayMode); break;

            default: SetVideosToInfoList(currentTrailerList); break;
            }
        }
		void DoPageLoad()
		{
			// called everytime the plugin is shown, after some other window was shown (also after fullscreen playback)
			if (PreviousWindowId != OnlineVideos.MediaPortal1.Player.GUIOnlineVideoFullscreen.WINDOW_FULLSCREEN_ONLINEVIDEO)
			{
				// reload settings that can be modified with the MPEI plugin
				PluginConfiguration.Instance.ReLoadRuntimeSettings();

				// if groups are now enabled/disabled we need to set the states accordingly
				if (GroupsEnabled)
				{
					// showing sites, but groups are enabled and no group is selected -> show groups
					if (CurrentState == State.sites && selectedSitesGroup == null) CurrentState = State.groups;

					// we might have to generate automatic groups if it is enabled now
					if (PluginConfiguration.Instance.CachedAutomaticSitesGroups.Count == 0)
						PluginConfiguration.Instance.BuildAutomaticSitesGroups();
				}
				else
				{
					// showing groups, but groups are disabled -> show sites
					if (CurrentState == State.groups) CurrentState = State.sites;
					selectedSitesGroup = null;
				}

				// reset the LoadParameterInfo
				loadParamInfo = null;

				string loadParam = null;
				// check if running version of mediaportal supports loading with parameter and handle _loadParameter
				System.Reflection.FieldInfo fi = typeof(GUIWindow).GetField("_loadParameter", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
				if (fi != null)
				{
					loadParam = (string)fi.GetValue(this);
				}
				// check for LoadParameters by GUIproperties if nothing was set by the _loadParameter
				if (string.IsNullOrEmpty(loadParam)) loadParam = LoadParameterInfo.FromGuiProperties();

				if (!string.IsNullOrEmpty(loadParam))
				{
					Log.Instance.Info("Called with LoadParameter: '{0}'", loadParam);
					loadParamInfo = new LoadParameterInfo(loadParam);

                    // set all state variables to reflect the state we were called with
                    currentNavigationContextSwitch = null;
					if (!string.IsNullOrEmpty(loadParamInfo.Group))
					{
						SitesGroup group = PluginConfiguration.Instance.SitesGroups.FirstOrDefault(sg => sg.Name == loadParamInfo.Group);
						if (group == null) group = PluginConfiguration.Instance.CachedAutomaticSitesGroups.FirstOrDefault(sg => sg.Name == loadParamInfo.Group);
						if (group != null)
						{
							selectedSitesGroup = new OnlineVideosGuiListItem(group);
							CurrentState = State.sites;
						}
					}
					if (!string.IsNullOrEmpty(loadParamInfo.Site) && OnlineVideoSettings.Instance.SiteUtilsList.ContainsKey(loadParamInfo.Site))
					{
						SelectedSite = OnlineVideoSettings.Instance.SiteUtilsList[loadParamInfo.Site];
						CurrentState = State.categories;
						selectedCategory = null;
					}
					if (SelectedSite != null && SelectedSite.CanSearch && !string.IsNullOrEmpty(loadParamInfo.Search))
					{
						Display_SearchResults(loadParamInfo.Search);
						return;
					}
				}
			}

			Log.Instance.Info("DoPageLoad with CurrentState '{0}', PreviousWindowId '{1}'", CurrentState, PreviousWindowId);
			switch (CurrentState)
			{
				case State.groups: DisplayGroups(); break;
				case State.sites: DisplaySites(); break;
				case State.categories: DisplayCategories(selectedCategory); break;
				case State.videos: SetVideosToFacade(currentVideoList, currentVideosDisplayMode); break;
				default: SetVideosToInfoList(currentTrailerList); break;
			}
		}