public static FederationDisplay GetFederationDisplay(Guid id)
        {
            FederationDisplay fed = new FederationDisplay();
            var dc = new ManagementContext();
            var f = dc.Federations.Where(x => x.FederationId == id).FirstOrDefault();
            fed.FederationId = f.FederationId;
            fed.FederationName = f.Name;

            if (f.ContactCard != null)
            {
                if (f.ContactCard.Addresses.FirstOrDefault() != null)
                {
                    fed.Address = f.ContactCard.Addresses.FirstOrDefault().Address1;
                    fed.City = f.ContactCard.Addresses.FirstOrDefault().CityRaw;
                    fed.State = f.ContactCard.Addresses.FirstOrDefault().StateRaw;
                    if (f.ContactCard.Addresses.FirstOrDefault().Country != null)
                        fed.Country = f.ContactCard.Addresses.FirstOrDefault().Country.Code;
                }
                if (f.ContactCard.Emails.FirstOrDefault() != null)
                {
                    fed.Email = f.ContactCard.Emails.FirstOrDefault().EmailAddress;
                }
            }
            fed.Founded = f.Founded;
            fed.Website = f.Website;
            if (f.Logo != null)
                fed.Logo = new PhotoItem(f.Logo.ImageUrl, f.Logo.IsPrimaryPhoto, f.Logo.AlternativeText);

            fed.Members.AddRange(MemberDisplayFactory.IterateMembersForDisplay(f.Members.Where(x => x.IsRemoved == false).ToList()).OrderBy(x => x.DerbyName));
            fed.Leagues.AddRange(League.LeagueFactory.IterateThroughLeaguesForDisplay(f.Leagues.Select(x => x.League).ToList()));
            return fed;
        }
        public static RDN.Portable.Classes.League.Classes.League GetLeagueForFederation(Guid federationId, Guid leagueId)
        {
            try
            {
                var dc = new ManagementContext();
                var league = dc.FederationLeagues.Include("Federation").Include("League").Include("League.Owners").Include("League.Teams").Include("League.Members").Include("League.ContactCard").Where(x => x.League.LeagueId == leagueId && x.Federation.FederationId == federationId).FirstOrDefault();

                RDN.Portable.Classes.League.Classes.League leagueTemp = new RDN.Portable.Classes.League.Classes.League();
                leagueTemp.LeagueId = league.League.LeagueId;
                leagueTemp.Name = league.League.Name;
                leagueTemp.Website = league.League.WebSite;
                //we use the contact card Id as the join code for "making contact with the league" 
                //instead of creating a new id 
                //and when I don't want to release to use the public LeagueId as the join key.
                leagueTemp.JoinCode = league.League.LeagueJoinCode;
                leagueTemp.SubscriptionPeriodEnds = league.League.SubscriptionPeriodEnds.GetValueOrDefault();

                if (league.League.Founded.HasValue)
                    leagueTemp.Founded = league.League.Founded.Value;
                if (league.League.ContactCard.Addresses.FirstOrDefault() != null)
                {
                    leagueTemp.TimeZone = league.League.ContactCard.Addresses.FirstOrDefault().TimeZone;
                    leagueTemp.Address = league.League.ContactCard.Addresses.FirstOrDefault().Address1;
                    leagueTemp.City = league.League.ContactCard.Addresses.FirstOrDefault().CityRaw;
                    leagueTemp.State = league.League.ContactCard.Addresses.FirstOrDefault().StateRaw;
                    if (league.League.ContactCard.Addresses.FirstOrDefault().Country != null)
                    {
                        leagueTemp.Country = league.League.ContactCard.Addresses.FirstOrDefault().Country.Name;
                        leagueTemp.CountryId = league.League.ContactCard.Addresses.FirstOrDefault().Country.CountryId;
                    }
                }
                if (league.League.ContactCard.Emails.FirstOrDefault() != null)
                    leagueTemp.Email = league.League.ContactCard.Emails.Where(x => x.IsDefault == true).FirstOrDefault().EmailAddress;
                //int numberType = Convert.ToInt32(CommunicationTypeEnum.PhoneNumber);
                var phone = league.League.ContactCard.Communications.Where(x => x.CommunicationTypeEnum == (byte)CommunicationTypeEnum.PhoneNumber).FirstOrDefault();
                if (phone != null)
                    leagueTemp.PhoneNumber = phone.Data;

                if (league.League.Logo != null)
                    leagueTemp.Logo = new PhotoItem(league.League.Logo.ImageUrl, league.League.Logo.IsPrimaryPhoto, league.League.Logo.AlternativeText);

                if (league.League.InternalWelcomePicture != null)
                    leagueTemp.InternalWelcomeImage = new PhotoItem(league.League.InternalWelcomePicture.ImageUrl, league.League.InternalWelcomePicture.IsPrimaryPhoto, league.League.InternalWelcomePicture.AlternativeText);

                leagueTemp.InternalWelcomeMessage = league.League.InternalWelcomeMessage;

                var members = league.League.Members.ToList();

                leagueTemp.LeagueMembers.AddRange(MemberDisplayFactory.IterateMembersForDisplay(members).OrderBy(x => x.DerbyName));

                foreach (var team in league.League.Teams)
                {
                    TeamDisplay teamTemp = new TeamDisplay();
                    teamTemp.TeamName = team.Name;
                    teamTemp.TeamId = team.TeamId;
                    teamTemp.Description = team.Description;
                    leagueTemp.Teams.Add(teamTemp);
                }

                //foreach (var owner in league.League.Owners)
                //{
                //    MemberDisplay mem = new MemberDisplay();
                //    mem.DerbyName = owner.Member.DerbyName;
                //    mem.MemberId = owner.Member.MemberId;
                //    leagueTemp.Owners.Add(mem);
                //}

                FederationDisplay fed = new FederationDisplay();
                fed.FederationId = league.Federation.FederationId;
                fed.FederationName = league.Federation.Name;
                fed.MembershipId = league.InternalLeagueIdForFederation;
                leagueTemp.Federations.Add(fed);
                leagueTemp.InternalFederationIdForLeague = league.InternalLeagueIdForFederation;
                leagueTemp.FederationIdForLeague = league.Federation.FederationId;
                return leagueTemp;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }
        public static RDN.Portable.Classes.League.Classes.League DisplayLeague(DataModels.League.League league, bool isPublic = false, bool isRemovedFromLeague = false)
        {
            try
            {
                RDN.Portable.Classes.League.Classes.League leagueTemp = new Portable.Classes.League.Classes.League();
                leagueTemp.LeagueId = league.LeagueId;
                leagueTemp.Name = league.Name;
                //leagues don't put the http in their profile.
                if (!String.IsNullOrEmpty(league.WebSite) && !league.WebSite.Contains("http://"))
                    leagueTemp.Website = "http://" + league.WebSite;
                else
                    leagueTemp.Website = league.WebSite;
                if (!String.IsNullOrEmpty(league.Twitter) && !league.Twitter.Contains("http://"))
                    leagueTemp.Twitter = "http://" + league.Twitter;
                else
                    leagueTemp.Twitter = league.Twitter;
                if (!String.IsNullOrEmpty(league.Instagram) && !league.Instagram.Contains("http://"))
                    leagueTemp.Instagram = "http://" + league.Instagram;
                else
                    leagueTemp.Instagram = league.Instagram;
                if (!String.IsNullOrEmpty(league.Facebook) && !league.Facebook.Contains("http://"))
                    leagueTemp.Facebook = "http://" + league.Facebook;
                else
                    leagueTemp.Facebook = league.Facebook;
                leagueTemp.RuleSetsPlayedEnum = (RuleSetsUsedEnum)league.RuleSetsPlayedEnum;
                leagueTemp.ShopUrl = StoreGateway.GetShopUrl(league.LeagueId);

                leagueTemp.SubscriptionPeriodEnds = league.SubscriptionPeriodEnds.GetValueOrDefault();
                leagueTemp.Groups = LeagueGroupFactory.DisplayGroups(league.Groups.Where(x => x.IsGroupRemoved == false).ToList());
                if (league.Founded.HasValue)
                    leagueTemp.Founded = league.Founded.Value;
                //we use the contact card Id as the join code for "making contact with the league" 
                //instead of creating a new id 
                //and when I don't want to release to use the public LeagueId as the join key.
                leagueTemp.JoinCode = league.LeagueJoinCode;

                if (league.ContactCard != null)
                {
                    if (league.ContactCard.Addresses.FirstOrDefault() != null)
                    {
                        leagueTemp.TimeZone = league.ContactCard.Addresses.FirstOrDefault().TimeZone;
                        leagueTemp.Address = league.ContactCard.Addresses.FirstOrDefault().Address1;
                        leagueTemp.City = league.ContactCard.Addresses.FirstOrDefault().CityRaw;
                        leagueTemp.State = league.ContactCard.Addresses.FirstOrDefault().StateRaw;
                        leagueTemp.ZipCode = league.ContactCard.Addresses.FirstOrDefault().Zip;
                        if (league.ContactCard.Addresses.FirstOrDefault().Country != null)
                        {
                            leagueTemp.Country = league.ContactCard.Addresses.FirstOrDefault().Country.Name;
                            leagueTemp.CountryId = league.ContactCard.Addresses.FirstOrDefault().Country.CountryId;
                        }
                    }
                    if (league.ContactCard.Emails.FirstOrDefault() != null)
                        leagueTemp.Email = league.ContactCard.Emails.Where(x => x.IsDefault == true).FirstOrDefault().EmailAddress;
                    //int numberType = Convert.ToInt32(CommunicationTypeEnum.PhoneNumber);
                    var phone = league.ContactCard.Communications.Where(x => x.CommunicationTypeEnum == (byte)CommunicationTypeEnum.PhoneNumber).FirstOrDefault();
                    if (phone != null)
                        leagueTemp.PhoneNumber = phone.Data;

                }
                if (league.Logo != null)
                    leagueTemp.Logo = new PhotoItem(league.Logo.ImageUrl, league.Logo.IsPrimaryPhoto, league.Logo.AlternativeText);

                if (league.InternalWelcomePicture != null)
                    leagueTemp.InternalWelcomeImage = new PhotoItem(league.InternalWelcomePicture.ImageUrl, league.InternalWelcomePicture.IsPrimaryPhoto, league.InternalWelcomePicture.AlternativeText);

                leagueTemp.InternalWelcomeMessage = league.InternalWelcomeMessage;

                //sets culture as united states english
                if (league.CultureLCID == 0)
                    leagueTemp.CultureSelected = 1033;
                else
                    leagueTemp.CultureSelected = league.CultureLCID;

                if (league.LastModified > new DateTime(2013, 11, 23) || league.Created > new DateTime(2013, 11, 23))
                {
                    leagueTemp.InternalWelcomeMessageHtml = leagueTemp.InternalWelcomeMessage;
                }
                else if (league.Created < new DateTime(2013, 11, 23))
                {
                    RDN.Library.Util.MarkdownSharp.Markdown markdown = new RDN.Library.Util.MarkdownSharp.Markdown();
                    markdown.AutoHyperlink = true;
                    markdown.AutoNewLines = true;
                    markdown.LinkEmails = true;
                    if (!String.IsNullOrEmpty(leagueTemp.InternalWelcomeMessage))
                    {
                        leagueTemp.InternalWelcomeMessageHtml = markdown.Transform(HtmlSanitize.FilterHtmlToWhitelist(leagueTemp.InternalWelcomeMessage));
                        leagueTemp.InternalWelcomeMessageHtml = leagueTemp.InternalWelcomeMessageHtml.Replace("</p>", "</p><br/>");
                    }
                }

                List<LeagueMember> members = new List<LeagueMember>();
                if (isPublic)
                    members = league.Members.Where(x => x.HasLeftLeague == isRemovedFromLeague && x.Member.IsProfileRemovedFromPublic == false).ToList();
                else
                    members = league.Members.Where(x => x.HasLeftLeague == isRemovedFromLeague).ToList();

                leagueTemp.LeagueMembers.AddRange(MemberDisplayFactory.IterateMembersForDisplay(members).OrderBy(x => x.DerbyName));

                try
                {
                    foreach (var color in league.Colors)
                    {
                        if (color != null)
                        {
                            var c = Color.FromArgb(color.Color.ColorIdCSharp);
                            var hex = ColorTranslator.ToHtml(c);
                            ColorDisplay d = new ColorDisplay();
                            d.ColorId = color.ColorId;
                            d.CSharpColor = color.Color.ColorIdCSharp;
                            d.HexColor = hex;
                            d.NameOfColor = color.Color.ColorName;
                            leagueTemp.ColorTempSelected += d.HexColor + ";";
                            leagueTemp.ColorsSelected += d.HexColor + ";";
                            leagueTemp.Colors.Add(d);
                        }

                    }
                }
                catch (Exception exception)
                {
                    ErrorDatabaseManager.AddException(exception, exception.GetType());
                }


                foreach (var team in league.Teams)
                {
                    TeamDisplay teamTemp = new TeamDisplay();
                    teamTemp.TeamName = team.Name;
                    teamTemp.TeamId = team.TeamId;
                    teamTemp.Description = team.Description;
                    leagueTemp.Teams.Add(teamTemp);
                }
                foreach (var con in league.Contacts)
                {
                    try
                    {
                        ContactDisplayBasic c = new ContactDisplayBasic();
                        c.ContactId = con.Contact.ContactId;
                        c.FirstName = con.Contact.Firstname;
                        c.LastName = con.Contact.Lastname;
                        c.ContactTypeForOrg = (ContactTypeForOrganizationEnum)con.ContactTypeEnum;
                        c.ContactTypeSelected = c.ContactTypeForOrg.ToString();
                        if (con.Contact.ContactCard.Addresses.FirstOrDefault() != null)
                        {
                            c.ContactCard = new Portable.Classes.ContactCard.ContactCard();
                            Portable.Classes.ContactCard.Address add = new Portable.Classes.ContactCard.Address();

                            add.Address1 = con.Contact.ContactCard.Addresses.FirstOrDefault().Address1;
                            add.Address2 = con.Contact.ContactCard.Addresses.FirstOrDefault().Address2;
                            add.CityRaw = con.Contact.ContactCard.Addresses.FirstOrDefault().CityRaw;
                            add.Zip = con.Contact.ContactCard.Addresses.FirstOrDefault().Zip;
                            add.StateRaw = con.Contact.ContactCard.Addresses.FirstOrDefault().StateRaw;
                            if (con.Contact.ContactCard.Addresses.FirstOrDefault().Country != null)
                                add.Country = con.Contact.ContactCard.Addresses.FirstOrDefault().Country.Name;
                            c.Address1 = con.Contact.ContactCard.Addresses.FirstOrDefault().Address1;
                            c.Address2 = con.Contact.ContactCard.Addresses.FirstOrDefault().Address2;
                            c.CityRaw = con.Contact.ContactCard.Addresses.FirstOrDefault().CityRaw;
                            c.Zip = con.Contact.ContactCard.Addresses.FirstOrDefault().Zip;
                            c.StateRaw = con.Contact.ContactCard.Addresses.FirstOrDefault().StateRaw;
                            if (con.Contact.ContactCard.Addresses.FirstOrDefault().Country != null)
                            {
                                c.CountryId = con.Contact.ContactCard.Addresses.FirstOrDefault().Country.CountryId;
                                c.CountryName = con.Contact.ContactCard.Addresses.FirstOrDefault().Country.Name;
                            }
                            c.ContactCard.Addresses.Add(add);
                        }
                        if (con.Contact.ContactCard.Emails.FirstOrDefault() != null)
                            c.Email = con.Contact.ContactCard.Emails.FirstOrDefault().EmailAddress;

                        var phone = con.Contact.ContactCard.Communications.OrderByDescending(x => x.Created).FirstOrDefault();
                        if (phone != null)
                            c.PhoneNumber = phone.Data;
                        c.CompanyName = con.Contact.CompanyName;
                        c.Notes = con.Notes;
                        c.Link = con.Contact.Link;
                        leagueTemp.Contacts.Add(c);
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }


                foreach (var federation in league.Federations)
                {
                    FederationDisplay fed = new FederationDisplay();
                    fed.FederationId = federation.Federation.FederationId;
                    fed.FederationName = federation.Federation.Name;
                    fed.MembershipId = federation.InternalLeagueIdForFederation;

                    leagueTemp.Federations.Add(fed);
                }

                return leagueTemp;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }
        /// <summary>
        /// builds up the member object to display out to the world.
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public static MemberDisplay GetMemberDisplay(Guid memberId, bool isPublicProfile = false, bool pullGameData = true)
        {
            try
            {
                var dc = new ManagementContext();
                var member = dc.Members.Include("Notifications").Include("Settings").Include("Leagues").Include("Leagues.SkaterClass").Include("InsuranceNumbers").Include("ContactCard").Include("ContactCard.Emails").Include("ContactCard.Communications").Include("Photos").Include("Federations").Include("MedicalInformation").FirstOrDefault(x => x.MemberId.Equals(memberId));
                if (member == null)
                    return null;



                MemberDisplay mem = new MemberDisplay();

                mem.IsProfileRemovedFromPublicView = member.IsProfileRemovedFromPublic;
                if (member.IsProfileRemovedFromPublic && isPublicProfile)
                    return null;

                foreach (var photo in member.Photos.OrderBy(x => x.Created))
                {
                    mem.Photos.Add(new PhotoItem(photo.ImageUrl, photo.IsPrimaryPhoto, member.DerbyName));
                }
                if (member.YearStartedSkating != null && member.YearStartedSkating != new DateTime())
                    mem.StartedSkating = member.YearStartedSkating.Value;
                else
                    mem.StartedSkating = null;
                if (member.YearStoppedSkating != null && member.YearStoppedSkating != new DateTime())
                    mem.StoppedSkating = member.YearStoppedSkating.Value;
                else
                    mem.StoppedSkating = null;

                mem.CurrentLeagueId = member.CurrentLeagueId;
                mem.IsRetired = member.Retired;
                mem.Firstname = member.Firstname;
                mem.DerbyName = member.DerbyName;
                mem.DerbyNameUrl = ServerConfig.WEBSITE_DEFAULT_LOCATION + "/roller-derby-skater/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(member.DerbyName) + "/" + member.MemberId.ToString().Replace("-", "");
                mem.MemberId = memberId;
                mem.UserId = member.AspNetUserId;
                mem.DayJob = member.DayJob;
                var user = Membership.GetUser((object)member.AspNetUserId);
                if (user != null)
                    mem.UserName = user.UserName;
                mem.IsNotConnectedToDerby = member.IsNotConnectedToDerby;

                mem.Email = ExtractEmailFromContactCard(member);
                if (member.ContactCard.Addresses.Count > 0)
                {
                    foreach (var add in member.ContactCard.Addresses)
                    {
                        var address = new RDN.Portable.Classes.ContactCard.Address();
                        address.AddressId = add.AddressId;
                        address.Address1 = add.Address1;
                        address.Address2 = add.Address2;
                        address.CityRaw = add.CityRaw;
                        if (add.Country != null)
                            address.Country = add.Country.Code;
                        address.StateRaw = add.StateRaw;
                        address.Zip = add.Zip;
                        address.Type = (AddressTypeEnum)add.AddressType;

                        mem.ContactCard.Addresses.Add(address);
                    }
                }
                GenderEnum gen;
                if (Enum.TryParse<GenderEnum>(member.Gender.ToString(), out gen))
                    mem.Gender = gen;
                mem.LastName = member.Lastname;
                mem.Bio = member.Bio;
                mem.DefaultPositionType = (DefaultPositionEnum)Enum.Parse(typeof(DefaultPositionEnum), member.PositionType.ToString());
                mem.BioHtml = member.Bio;

                if (member.DateOfBirth.HasValue)
                    mem.DOB = member.DateOfBirth.Value;

                mem.WeightLbs = member.WeightInLbs;

                if (member.HeightInches != 0)
                {
                    mem.HeightFeet = (int)(member.HeightInches / 12);
                    mem.HeightInches = (int)(member.HeightInches % 12);
                }

                DisplayInsuranceNumbers(member.InsuranceNumbers, mem);
                DisplayMemberNotifications(member.Notifications, mem);

                mem.Settings = MemberSettingsFactory.DisplayMemberSettings(member.Settings);

                foreach (var memberContact in member.MemberContacts)
                {
                    try
                    {
                        RDN.Portable.Classes.Account.Classes.MemberContact contact = new RDN.Portable.Classes.Account.Classes.MemberContact();
                        contact.ContactId = memberContact.ContactId;
                        contact.Firstname = memberContact.Firstname;
                        contact.Lastname = memberContact.Lastname;
                        contact.ContactType = (MemberContactTypeEnum)Enum.Parse(typeof(MemberContactTypeEnum), memberContact.ContactTypeEnum.ToString());
                        if (memberContact.ContactCard != null)
                        {
                            if (memberContact.ContactCard.Emails.Count > 0)
                                contact.Email = memberContact.ContactCard.Emails.Where(x => x.IsDefault == true).FirstOrDefault().EmailAddress;
                            if (memberContact.ContactCard.Communications.Count > 0)
                            {
                                contact.PhoneNumber = memberContact.ContactCard.Communications.FirstOrDefault().Data;
                                contact.SMSVerificationNum = memberContact.ContactCard.Communications.FirstOrDefault().SMSVerificationCode;
                                contact.Carrier = (MobileServiceProvider)memberContact.ContactCard.Communications.FirstOrDefault().CarrierType;
                            }
                            if (memberContact.ContactCard.Addresses.Count > 0)
                            {
                                contact.Addresses = new List<Portable.Classes.ContactCard.Address>();

                                foreach (var add in memberContact.ContactCard.Addresses)
                                {
                                    var address = new RDN.Portable.Classes.ContactCard.Address();
                                    address.Address1 = add.Address1;
                                    address.Address2 = add.Address2;
                                    address.CityRaw = add.CityRaw;
                                    if (add.Country != null)
                                        address.Country = add.Country.Code;
                                    address.StateRaw = add.StateRaw;
                                    address.Zip = add.Zip;
                                    address.Type = (AddressTypeEnum)add.AddressType;
                                    contact.Addresses.Add(address);
                                }
                            }
                        }
                        mem.MemberContacts.Add(contact);
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                if (member.ContactCard.Communications.Count > 0)
                {
                    var com = member.ContactCard.Communications.Where(x => x.IsDefault == true).Where(x => x.CommunicationTypeEnum == (byte)CommunicationTypeEnum.PhoneNumber).FirstOrDefault();
                    if (com != null)
                    {
                        mem.PhoneNumber = com.Data;
                        mem.SMSVerificationNum = com.SMSVerificationCode;
                        mem.Carrier = (MobileServiceProvider)com.CarrierType;
                        mem.IsCarrierVerified = com.IsCarrierVerified;
                    }
                }
                mem.PlayerNumber = member.PlayerNumber;
                if (member.Leagues.Count > 0)
                {
                    foreach (var league in member.Leagues)
                    {
                        RDN.Portable.Classes.League.Classes.League l = new Portable.Classes.League.Classes.League();
                        l.LeagueId = league.League.LeagueId;
                        l.Name = league.League.Name;
                        l.IsInactiveInLeague = league.IsInactiveForLeague;
                        l.DepartureDate = league.DepartureDate;
                        l.MembershipDate = league.MembershipDate;
                        l.SkillsTestDate = league.SkillsTestDate;
                        l.HasLeftLeague = league.HasLeftLeague;
                        l.NotesAboutMember = league.Notes;
                        l.NameUrl = ServerConfig.WEBSITE_DEFAULT_LOCATION_FOR_LEAGUES + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(l.Name) + "/" + l.LeagueId.ToString().Replace("-", "");
                        l.LeagueOwnersEnum = (LeagueOwnersEnum)league.LeagueOwnersEnums;
                        if (l.LeagueId == mem.CurrentLeagueId)
                        {
                            mem.LeagueOwnersEnum = l.LeagueOwnersEnum;
                            mem.DoesReceiveLeagueNotifications = !league.TurnOffEmailNotifications;
                        }
                        if (league.SkaterClass != null)
                            l.SkaterClass = league.SkaterClass.ClassId;
                        else
                            l.SkaterClass = 0;

                        mem.Leagues.Add(l);
                    }
                }

                MedicalInformationFactory.AttachMemberMedicalInformation(member, mem);

                foreach (var fed in member.Federations)
                {
                    FederationDisplay fedDisplay = new FederationDisplay();
                    fedDisplay.FederationId = fed.Federation.FederationId;
                    fedDisplay.FederationName = fed.Federation.Name;
                    fedDisplay.MADEClassRank = ((MADEClassRankEnum)Enum.ToObject(typeof(MADEClassRankEnum), fed.MADEClassRankForMember)).ToString();
                    fedDisplay.MemberType = ((MemberTypeFederationEnum)Enum.ToObject(typeof(MemberTypeFederationEnum), fed.MemberType)).ToString();
                    var ownersOfFed = fed.Federation.Owners.Where(x => x.Member == member).FirstOrDefault();
                    if (ownersOfFed == null)
                        fedDisplay.OwnerType = FederationOwnerEnum.None.ToString();
                    else
                        fedDisplay.OwnerType = ((FederationOwnerEnum)Enum.ToObject(typeof(FederationOwnerEnum), ownersOfFed.OwnerType)).ToString();

                    if (fed.MembershipDate != null && fed.MembershipDate != new DateTime())
                        fedDisplay.MembershipDate = fed.MembershipDate.Value;
                    else
                        fedDisplay.MembershipDate = DateTime.UtcNow;
                    fedDisplay.MembershipId = fed.FederationIdForMember;
                    mem.FederationsApartOf.Add(fedDisplay);
                }
                if (pullGameData)
                    GetGameStats(memberId, dc, mem);
                return mem;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }
        public ActionResult ManagePost(Game game)
        {
            try
            {
                var gameDb = GameManager.GetGameForManagement(game.GameId, game.PrivateKeyForGame, RDN.Library.Classes.Account.User.GetMemberId());
                if (game == null)
                    return Redirect(Url.Content("~/"));

                gameDb.GameName = game.GameName;
                gameDb.GameDate = game.GameDate;

                for (int i = 0; i < gameDb.MembersOfGame.Count; i++)
                {
                    string linkId = HttpContext.Request.Form[gameDb.MembersOfGame[i].MemberId.ToString().Replace("-", "") + "hidden"];
                    if (String.IsNullOrEmpty(linkId))
                        gameDb.MembersOfGame[i].MemberLinkId = new Guid();
                    else
                    {
                        if (new Guid(linkId) != gameDb.MembersOfGame[i].MemberLinkId)
                        {
                            gameDb.MembersOfGame[i].MemberLinkId = new Guid(linkId);
                        }
                    }
                }
                gameDb.SelectedShop = game.SelectedShop;
                gameDb.SelectedTournament = game.SelectedTournament;
                gameDb.PassCodeEnteredForTournament = game.PassCodeEnteredForTournament;

                for (int i = 0; i < gameDb.MemberOwners.Count + 5; i++)
                {
                    if (HttpContext.Request.Form["MemberOwner" + i + "hidden"] != null && !String.IsNullOrEmpty(HttpContext.Request.Form["MemberOwner" + i + "hidden"].ToString()))
                    {
                        MemberDisplayBasic mem = new MemberDisplayBasic();
                        mem.MemberId = new Guid(HttpContext.Request.Form["MemberOwner" + i + "hidden"].ToString());
                        gameDb.MemberOwners.Add(mem);
                    }
                    if (HttpContext.Request.Form["LeagueOwner" + i + "hidden"] != null && !String.IsNullOrEmpty(HttpContext.Request.Form["LeagueOwner" + i + "hidden"].ToString()))
                    {
                        RDN.Portable.Classes.League.Classes.League mem = new Portable.Classes.League.Classes.League();
                        mem.LeagueId = new Guid(HttpContext.Request.Form["LeagueOwner" + i + "hidden"].ToString());
                        gameDb.LeagueOwners.Add(mem);
                    }
                    if (HttpContext.Request.Form["FederationOwner" + i + "hidden"] != null && !String.IsNullOrEmpty(HttpContext.Request.Form["FederationOwner" + i + "hidden"].ToString()))
                    {
                        FederationDisplay mem = new FederationDisplay();
                        mem.FederationId = new Guid(HttpContext.Request.Form["FederationOwner" + i + "hidden"].ToString());
                        gameDb.FederationOwners.Add(mem);
                    }
                }
                if (!String.IsNullOrEmpty(game.EmbededVideoString))
                    gameDb.IsThereVideoOfGame = GameVideoTypeEnum.EmbededVideo;
                else if (!String.IsNullOrEmpty(game.StreamingUrlSilverlight))
                    gameDb.IsThereVideoOfGame = GameVideoTypeEnum.SilverLightLive;

                gameDb.StreamingMobileUrlSilverlight = game.StreamingMobileUrlSilverlight;
                gameDb.StreamingUrlSilverlight = game.StreamingUrlSilverlight;
                gameDb.EmbededVideoString = game.EmbededVideoString;
                gameDb.SelectedPaywall = game.SelectedPaywall;

                GameManager.UpdateGameFromManagement(gameDb);
                try
                {
                    //clears the live game once we complete the update.
                    WebClient client = new WebClient();
                    client.DownloadString(ServerConfig.URL_TO_CLEAR_LIVE_GAME_CACHE + game.GameId.ToString());
                }
                catch { }
                try
                {
                    //clears the live game once we complete the update.
                    WebClient client = new WebClient();
                    client.DownloadString(ServerConfig.WEBSITE_CLEAR_TOURNAMENT_CACHE_API);
                }
                catch { }
                return Redirect(Url.Content("~/game/manage/" + game.PrivateKeyForGame.ToString().Replace("-", "") + "/" + game.GameId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.s));
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.na));
        }
        public static Game DisplayGame(DataModels.Game.Game game)
        {
            ManagementContext dc = new ManagementContext();
            Game tempGame = new Game();
            tempGame.IsThereVideoOfGame = (GameVideoTypeEnum)Enum.Parse(typeof(GameVideoTypeEnum), game.IsThereVideoOfGame.ToString());
            tempGame.StreamingUrlSilverlight = game.StreamingUrlOfVideo;
            tempGame.StreamingMobileUrlSilverlight = game.StreamingUrlOfVideoMobile;
            tempGame.EmbededVideoString = game.EmbededVideoHtml;
            if (game.Paywall != null)
                tempGame.SelectedPaywall = game.Paywall.PaywallId;
            tempGame.GameDate = game.GameDate;
            tempGame.GameId = game.GameId;
            tempGame.PrivateKeyForGame = game.IdForOnlineManagementUse;
            tempGame.GameName = game.GameName;
            if (game.SelectedShop != null)
                tempGame.SelectedShop = game.SelectedShop.MerchantId.ToString();
            var games = game.GameTeams.OrderByDescending(x => x.Created).Take(2);
            var team2 = games.OrderBy(x => x.TeamName).FirstOrDefault();
            var team1 = games.OrderByDescending(x => x.TeamName).FirstOrDefault();

            if (team1 != null)
                tempGame.Team1Name = team1.TeamName;
            else
                tempGame.Team1Name = "Home";
            if (team2 != null)
                tempGame.Team2Name = team2.TeamName;
            else
                tempGame.Team2Name = "Away";
            tempGame.HasGameStarted = game.HasGameStarted;
            tempGame.IsGameLive = game.IsGameLive;
            tempGame.IsGameOver = game.IsGameOver;
            tempGame.IsGamePublishedOnline = game.IsGamePublishedOnline;
            tempGame.IsGameScrimmage = game.IsGameScrimmage;
            tempGame.VersionNumber = game.VersionNumber;

            foreach (var team in game.GameTeams)
            {
                foreach (var mem in team.GameMembers)
                {
                    MemberDisplayGame member = new MemberDisplayGame();
                    member.DerbyName = mem.MemberName;
                    member.MemberId = mem.GameMemberId;
                    if (mem.MemberLinkId != new Guid())
                    {
                        var memDb = (from xx in dc.Members
                                     where xx.MemberId == mem.MemberLinkId
                                     select xx.DerbyName).FirstOrDefault();
                        if (!String.IsNullOrEmpty(memDb))
                        {
                            member.MemberLinkId = mem.MemberLinkId;
                            member.DerbyLinkName = memDb;
                        }
                    }
                    tempGame.MembersOfGame.Add(member);
                }
            }
            var endDate = DateTime.UtcNow.AddDays(5);
            var tournys = dc.GameTournaments.Where(x => x.StartDate < DateTime.UtcNow && x.EndDate < endDate).ToList();
            if (game.GameTournament != null)
            {
                tempGame.SelectedTournament = game.GameTournament.TournamentId.ToString();
                tempGame.PassCodeEnteredForTournament = game.GameTournament.TournamentPasscode;
                Tournament t = new Tournament();
                t.Name = game.GameTournament.TournamentName;
                t.EndDate = game.GameTournament.EndDate;
                t.Id = game.GameTournament.TournamentId;
                t.StartDate = game.GameTournament.StartDate;
                tempGame.AvailableTournaments.Add(t);
            }

            foreach (var owner in game.MemberOwners)
            {
                MemberDisplayBasic mem = new MemberDisplayBasic();
                mem.MemberId = owner.Member.MemberId;
                mem.DerbyName = owner.Member.DerbyName;
                tempGame.MemberOwners.Add(mem);
            }
            if (tempGame.MemberOwners.Count < 5)
            {
                MemberDisplayBasic mem = new MemberDisplayBasic();
                tempGame.MemberOwners.Add(mem);
                MemberDisplayBasic mem1 = new MemberDisplayBasic();
                tempGame.MemberOwners.Add(mem1);
                MemberDisplayBasic mem2 = new MemberDisplayBasic();
                tempGame.MemberOwners.Add(mem2);
                MemberDisplayBasic mem3 = new MemberDisplayBasic();
                tempGame.MemberOwners.Add(mem3);
            }

            foreach (var owner in game.LeagueOwners)
            {
                RDN.Portable.Classes.League.Classes.League mem = new RDN.Portable.Classes.League.Classes.League();
                mem.LeagueId = owner.League.LeagueId;
                mem.Name = owner.League.Name;
                tempGame.LeagueOwners.Add(mem);
            }
            if (tempGame.LeagueOwners.Count < 2)
            {
                RDN.Portable.Classes.League.Classes.League mem = new RDN.Portable.Classes.League.Classes.League();
                tempGame.LeagueOwners.Add(mem);
                RDN.Portable.Classes.League.Classes.League mem1 = new RDN.Portable.Classes.League.Classes.League();
                tempGame.LeagueOwners.Add(mem1);
            }
            foreach (var owner in game.FederationOwners)
            {
                FederationDisplay mem = new FederationDisplay();
                mem.FederationId = owner.Federation.FederationId;
                mem.FederationName = owner.Federation.Name;
                tempGame.FederationOwners.Add(mem);
            }
            if (tempGame.FederationOwners.Count == 0)
            {
                FederationDisplay mem = new FederationDisplay();
                tempGame.FederationOwners.Add(mem);
            }

            foreach (var tourn in tournys)
            {
                var gameT = tourn.Games.Where(x => x.GameId == tempGame.GameId).FirstOrDefault();
                if (gameT != null)
                {
                    tempGame.SelectedTournament = tourn.TournamentId.ToString();
                    tempGame.PassCodeEnteredForTournament = tourn.TournamentPasscode;
                }
                Tournament t = new Tournament();
                t.Name = tourn.TournamentName;
                t.EndDate = tourn.EndDate;
                t.Id = tourn.TournamentId;
                t.StartDate = tourn.StartDate;
                if (tempGame.AvailableTournaments.Where(x => x.Id == t.Id).FirstOrDefault() == null)
                    tempGame.AvailableTournaments.Add(t);
            }
            return tempGame;
        }