//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using CommunityServer;
using CommunityServer.Components;
using System.ComponentModel;
using System.IO;
using CommunityServer.Configuration;


namespace CommunityServer.Controls 
{
	public class EditProfile : SecureTemplatedWebControl
    {
        #region Child Controls

        Literal username;
        TimezoneDropDownList timezone;
        TextBox commonName;
        TextBox location;
        TextBox occupation;
        TextBox interests;
        TextBox webAddress;
        TextBox webLog;
		TextBox webGallery;
        TextBox signature;
        TextBox bio;
        TextBox privateEmail;
        TextBox publicEmail;
        TextBox msnIM;
        TextBox aolIM;
        TextBox yahooIM;
        TextBox icq;
        TextBox avatarUrl;
        TextBox usernameEdit;
        RadioButtonList enableAvatar;
        RadioButtonList  hideReadPosts;
        RadioButtonList enableEmailTracking;
        RadioButtonList displayInMemberList;
        RadioButtonList enableHtmlEmail;
        RadioButtonList enableEmail;
		YesNoRadioButtonList enableInk;
        YesNoRadioButtonList enableDisplayNames;
        YesNoRadioButtonList enableUserSignatures;
        YesNoRadioButtonList enableUserAvtars;
        GenderRadioButtonList gender;
        LanguageDropDownList language;
        DateFormatDropDownList dateFormat;
		DatePickerToggle birthday;
        Button updateButtonBottom;
        Button avatarUpdateButton;
        DateFilter defaultThreadView;
        CustomValidator signatureMaxLengthValidator;
        HtmlInputFile uploadedAvatar;
        HtmlAnchor changePassword;
        HtmlAnchor changePasswordAnswer;
        ThemeDropDownList theme;
        YesNoRadioButtonList enablePostPreviewPopup;
        YesNoRadioButtonList EnableEmoticons;
        Label avatarMsg;
        Label enableAvatarMsg;
        YesNoRadioButtonList enableCollapsingPanels;
        FontSizeDropDownList fontsizeList;
        SortOrderDropDownList sortOrder;
        StatusMessage formStatus;
        DropDownList editorList;
		DropDownList postViewType;
        Literal DateCreated;
        Literal LastLogin;
        Literal LastActivity;
        Control avatarSection;
        UserAvatar avatar;
        Control EnableSignature;
        Control EnableGender;
        Control EnablePasswordQuestionAnswer; 
        Control EmoticonRow;
		CheckBox ShareFavoriteUsers;
		Repeater FavoriteUsers;
		IButton DeleteFavoriteUsers;
		Repeater Watchers;
		CheckBox ShareFavoritePosts;
		Repeater FavoritePosts;
		IButton DeleteFavoritePosts;
		CheckBox ShareFavoriteSections;
		Repeater FavoriteSections;
		IButton DeleteFavoriteSections;
		ResourceControl EnablePostPreviewPopupLabel;
		ResourceControl ReceiveEmailsLabel;
		ResourceControl EnableHtmlEmailLabel;
		ResourceControl EnableEmailTrackingLabel;
		ResourceControl ThemeLabel;
		ResourceControl AvatarUrlLabel;
		ResourceControl EmailTitleLabel;
		YesNoRadioButtonList ynEnableHelp;
		DropDownList PageSize;
		DropDownList ControlPanelManageView;
		Control ControlPanelManageViewArea;
		PlaceHolder SectionLocalizationArea;
		CheckBoxList FilterLanguageList;
		Control contactCheckboxes;
		YesNoRadioButtonList allowSiteToContact;
		YesNoRadioButtonList allowSitePartnersToContact;

        CSContext csContext = CSContext.Current;
        User userToEdit;

        #endregion

        protected override void OnInit(EventArgs e) 
        {
            if (SkinName == null)                
                ExternalSkinFileName = "Skin-EditProfile.ascx";
            else 
                ExternalSkinFileName = SkinName;
			
            // Get the user we are editing
            //
            userToEdit = Users.GetUserWithWriteableProfile();

            base.OnInit(e);
        }
		
        protected override void OnLoad(EventArgs e) 
        {
			if (!Page.IsPostBack)
				DataBind();

            base.OnLoad(e);

            UsersOnline.SetLocation("Editing Profile",null);
        }

        #region DataBind

        public override void DataBind() 
        {
            base.DataBind();

			if (ShareFavoriteUsers != null)
			{
				ShareFavoriteUsers.Text = ResourceManager.GetString("EditProfile_FavoriteUsers_Share");
				ShareFavoriteUsers.Checked = ((csContext.User.FavoritesShared & FavoriteType.User) == FavoriteType.User);
			}

			if (FavoriteUsers != null)
				BindFavoriteUsers();

			if (Watchers != null)
				BindWatchers();

			if (ShareFavoritePosts != null)
			{
				ShareFavoritePosts.Text = ResourceManager.GetString("EditProfile_FavoritePosts_Share");
				ShareFavoritePosts.Checked = ((csContext.User.FavoritesShared & FavoriteType.Post) == FavoriteType.Post);
			}

			if (FavoritePosts != null)
				BindFavoritePosts();

			if (ShareFavoriteSections != null)
			{
				ShareFavoriteSections.Text = ResourceManager.GetString("EditProfile_FavoriteSections_Share");
				ShareFavoriteSections.Checked = ((csContext.User.FavoritesShared & FavoriteType.Section) == FavoriteType.Section);
			}

			if (FavoriteSections != null)
				BindFavoriteSections();

			if (EmailTitleLabel != null)
				EmailTitleLabel.Visible = csContext.SiteSettings.EnableEmail;

			if (ReceiveEmailsLabel != null)
				ReceiveEmailsLabel.Visible = csContext.SiteSettings.EnableEmail;

			if (enableEmail != null)
				enableEmail.Visible = csContext.SiteSettings.EnableEmail;

			if (EnableEmailTrackingLabel != null)
				EnableEmailTrackingLabel.Visible = csContext.SiteSettings.EnableEmail;
			
			if (enableEmailTracking != null)
                enableEmailTracking.Visible = csContext.SiteSettings.EnableEmail;

			if (EnableHtmlEmailLabel != null)
				EnableHtmlEmailLabel.Visible = csContext.SiteSettings.EnableEmail;
			
			if (enableHtmlEmail != null)
                enableHtmlEmail.Visible = csContext.SiteSettings.EnableEmail;

			if(enableInk != null)
				enableInk.SelectedValue = csContext.User.EnableInk;

            if(enableDisplayNames != null)
                enableDisplayNames.SelectedValue = csContext.User.EnableDisplayName;

            if(enableUserSignatures != null)
                enableUserSignatures.SelectedValue = csContext.User.EnableUserSignatures;

            if(enableUserAvtars != null)
                enableUserAvtars.SelectedValue = csContext.User.EnableUserAvtars;
			
			if (EnableEmoticons != null)
                EnableEmoticons.SelectedValue = csContext.User.Profile.EnableEmoticons;

            if (EmoticonRow != null)
                EmoticonRow.Visible = csContext.SiteSettings.EnableEmoticons;

            if (signatureMaxLengthValidator != null)
                signatureMaxLengthValidator.ErrorMessage = string.Format(ResourceManager.GetString("EditProfile_SigMaxLength"), csContext.SiteSettings.UserSignatureMaxLength.ToString());

            if (changePassword != null) 
            {
                changePassword.InnerText = ResourceManager.GetString("EditProfile_PasswordChange");
                changePassword.HRef = Globals.GetSiteUrls().UserChangePassword;
            }
            
            if (changePasswordAnswer != null)
            {
                changePasswordAnswer.InnerText = ResourceManager.GetString("EditProfile_PasswordAnswerChange");
                changePasswordAnswer.HRef = Globals.GetSiteUrls().UserChangePasswordAnswer;
            }

            if (EnablePasswordQuestionAnswer != null &&
                csContext.SiteSettings.PasswordRecovery == CommunityServer.Components.PasswordRecovery.QuestionAndAnswer)
            {
                EnablePasswordQuestionAnswer.Visible = true;
            }

            if (EnableSignature != null)
            {
                if (csContext.SiteSettings.AllowUserSignatures)
                    EnableSignature.Visible = true;
                else
                    EnableSignature.Visible = false;
            }
			
            // Do we allow the user to select theme?
            if (theme != null)
				theme.Visible = csContext.SiteSettings.EnableUserThemeSelection;
			if (ThemeLabel != null)
				ThemeLabel.Visible = csContext.SiteSettings.EnableUserThemeSelection;

            // Do we allow the user to specify gender?
            if (EnableGender != null && 
                csContext.SiteSettings.AllowGender)
            {
                EnableGender.Visible = true;
            }

            if (username != null)
            {
                // Set form to the current values of logged on user
                //
                username.Text = userToEdit.CommonNameOrUserName;

                // Do we allow the user to edit his/her username?
                if (csContext.SiteSettings.EnableUsernameChange) 
                {
                    username.Visible = false;

                    if (usernameEdit != null)
                    {
                        usernameEdit.Visible = true;
                        usernameEdit.Text = username.Text;
                    }
                }
            }

            if (timezone != null &&
                timezone.Items.FindByValue( userToEdit.Profile.Timezone.ToString() ) != null)
            {
                timezone.Items.FindByValue( userToEdit.Profile.Timezone.ToString() ).Selected = true;
            }

            // Find controls for Avatar/Post section
            //
            if (csContext.SiteSettings.EnableAvatars)  
            {
				if (avatar != null)
				{
					// Always force user (otherwise, user may be pulled from QueryString)
					avatar.User = userToEdit;

					if (userToEdit.HasAvatar && userToEdit.EnableAvatar)
						avatar.Visible = true;
					else
						avatar.Visible = false;
				}

                // Has the avatar been approved?
                if (enableAvatar != null)
                {
                    if (!userToEdit.IsAvatarApproved) 
                    {
                        enableAvatar.Enabled = false;
                        ((YesNoRadioButtonList) enableAvatar).SelectedValue = false;
                        enableAvatarMsg.Text = ResourceManager.GetString("EditProfile_AvatarsMustBeApprovedByModerator");
                    } 
                    else 
                    {
                        enableAvatar.Enabled = true;
                        enableAvatarMsg.Text = null;
                    }
                }

                if (avatarUrl != null)
                {
					avatarUrl.Visible = csContext.SiteSettings.EnableRemoteAvatars;
					
					if (csContext.SiteSettings.EnableRemoteAvatars) 
                        avatarMsg.Text = null;
                    else 
                        avatarMsg.Text = ResourceManager.GetString("EditProfile_RemoteAvatarsDisabled");
                }

//				if (AvatarUrlLabel != null)
//					AvatarUrlLabel.Visible = csContext.SiteSettings.EnableRemoteAvatars;



            }
            else 
            {
                if (avatarSection != null)
                    avatarSection.Visible = false;				
            }

            if (enablePostPreviewPopup != null)
            {
				// EnablePostPreviewPopupLabel.Visible = forumConfig.EnablePostPreviewPopup;
				// enablePostPreviewPopup.Visible = forumConfig.EnablePostPreviewPopup;

				//if (forumConfig.EnablePostPreviewPopup) 
					enablePostPreviewPopup.Items.FindByValue( userToEdit.Profile.EnablePostPreviewPopup.ToString() ).Selected = true;
            }

            if (commonName != null)
                commonName.Text = Globals.HtmlDecode(userToEdit.Profile.CommonName);

            if (location != null)
                location.Text = Globals.HtmlDecode(userToEdit.Profile.Location);

            if (occupation != null)
                occupation.Text = Globals.HtmlDecode(userToEdit.Profile.Occupation);

            if (interests != null)
                interests.Text = Globals.HtmlDecode(userToEdit.Profile.Interests);

            if (webAddress != null)
                webAddress.Text = Globals.HtmlDecode(userToEdit.Profile.WebAddress);

            if (webLog != null)
                webLog.Text = Globals.HtmlDecode(userToEdit.Profile.WebLog);

			if (webGallery != null)
				webGallery.Text = Globals.HtmlDecode(userToEdit.Profile.WebGallery);

            if (signature != null)
                signature.Text = userToEdit.Profile.Signature;

            if (privateEmail != null)
                privateEmail.Text = userToEdit.Email;

            if (publicEmail != null)
                publicEmail.Text = Globals.HtmlDecode(userToEdit.Profile.PublicEmail);

            if (msnIM != null)
                msnIM.Text = Globals.HtmlDecode(userToEdit.Profile.MsnIM);

            if (aolIM != null)
                aolIM.Text = Globals.HtmlDecode(userToEdit.Profile.AolIM);

            if (yahooIM != null)
                yahooIM.Text = Globals.HtmlDecode(userToEdit.Profile.YahooIM);

            if (icq != null)
                icq.Text = Globals.HtmlDecode(userToEdit.Profile.IcqIM);

            if (avatarUrl != null)
                avatarUrl.Text = Globals.HtmlDecode(userToEdit.AvatarUrl);

            if (bio != null)
                bio.Text = userToEdit.Profile.Bio;

            if (birthday != null)
                birthday.SelectedDate = userToEdit.Profile.BirthDate;

            if (theme != null)
                theme.SelectedValue = userToEdit.Theme;

            // Set the gender
            if (gender != null)
                gender.Items.FindByValue( ((int) userToEdit.Profile.Gender).ToString() ).Selected = true;

            // Language Drop Down List
            if (language != null &&
                language.Items.FindByValue( userToEdit.Profile.Language ) != null)
            {
                language.Items.FindByValue( userToEdit.Profile.Language ).Selected = true;
            }

            if (dateFormat != null && 
                dateFormat.Items.FindByValue( userToEdit.Profile.DateFormat ) != null)
            {
                dateFormat.Items.FindByValue( userToEdit.Profile.DateFormat ).Selected = true;
            }

            if (sortOrder != null &&
                sortOrder.Items.FindByValue( ((int)userToEdit.PostSortOrder).ToString() ) != null)
            {
                sortOrder.Items.FindByValue( ((int)userToEdit.PostSortOrder).ToString() ).Selected = true;
            }

            if (enableAvatar != null)
                enableAvatar.Items.FindByValue( userToEdit.EnableAvatar.ToString() ).Selected = true;

            if (enableEmailTracking != null)
                enableEmailTracking.Items.FindByValue ( userToEdit.EnableThreadTracking.ToString() ).Selected = true;

            if (enableHtmlEmail != null)
                enableHtmlEmail.Items.FindByValue ( userToEdit.EnableHtmlEmail.ToString() ).Selected = true;

            if (enableEmail != null)
                enableEmail.Items.FindByValue ( userToEdit.EnableEmail.ToString() ).Selected = true;

            if (displayInMemberList != null)
                displayInMemberList.Items.FindByValue( userToEdit.EnableDisplayInMemberList.ToString()).Selected = true;

			if (ControlPanelManageView != null && (userToEdit.IsBlogAdministrator || userToEdit.IsGalleryAdministrator || userToEdit.IsFileAdministrator || userToEdit.IsForumAdministrator))
			{
				if (ControlPanelManageViewArea != null)
					ControlPanelManageViewArea.Visible = true;

                ControlPanelManageView.Items.Add(new ListItem(ResourceManager.GetString("EditProfile_ControlPanelManageView_Grid"), ((int) CommunityServer.Components.ControlPanelManageView.Grid).ToString()));
				ControlPanelManageView.Items.Add(new ListItem(ResourceManager.GetString("EditProfile_ControlPanelManageView_Tree"), ((int) CommunityServer.Components.ControlPanelManageView.Tree).ToString()));

				ControlPanelManageView.SelectedValue = ((int) userToEdit.ControlPanelManageView).ToString();
			}
			else if (ControlPanelManageViewArea != null)
				ControlPanelManageViewArea.Visible = false;


            if (DateCreated != null)
                DateCreated.Text = userToEdit.GetTimezone( userToEdit.DateCreated, true ).ToString( userToEdit.Profile.DateFormat );

            if (LastLogin != null)
                LastLogin.Text = userToEdit.GetTimezone( userToEdit.LastLogin, true ).ToString( userToEdit.Profile.DateFormat );

            if(LastActivity != null)
                LastActivity.Text = userToEdit.GetTimezone( userToEdit.LastActivity ).ToString( userToEdit.Profile.DateFormat );

            if (enableCollapsingPanels != null)
                enableCollapsingPanels.Items.FindByValue( userToEdit.EnableCollapsingPanels.ToString() ).Selected = true;

            if (editorList != null)
            {
                foreach (SelectableEditor e in csContext.Config.Editors)
                {
                    editorList.Items.Add( new ListItem(e.Name,e.Name) );
                }
            
                ListItem li = editorList.Items.FindByValue(userToEdit.EditorType);
                if (li != null)
                    li.Selected = true;
            }

			if (postViewType != null)
			{
				postViewType.Items.Add(new ListItem(ResourceManager.GetString("EditProfile_PostViewType_Flat"), ((int) PostViewType.Flat).ToString()));
				postViewType.Items.Add(new ListItem(ResourceManager.GetString("EditProfile_PostViewType_Threaded"), ((int) PostViewType.Threaded).ToString()));

				ListItem li = postViewType.Items.FindByValue(((int) userToEdit.PostViewType).ToString());
				if (li != null)
					li.Selected = true;
			}

			BindExtendedUserControls();

            // Give the update button some text
            //
            if (updateButtonBottom != null)
                updateButtonBottom.Text = CommunityServer.Components.ResourceManager.GetString("EditProfile_Update");

            // Set the avatar update button
            if (avatarUpdateButton != null)
                avatarUpdateButton.Text = CommunityServer.Components.ResourceManager.GetString("Update");

			// Set the delete favorite users button
			if (DeleteFavoriteUsers != null)
				DeleteFavoriteUsers.Text = ResourceManager.GetString("Delete");

			// Set the delete favorite posts button
			if (DeleteFavoritePosts != null)
				DeleteFavoritePosts.Text = ResourceManager.GetString("Delete");

			// Set the delete favorite sections button
			if (DeleteFavoriteSections != null)
				DeleteFavoriteSections.Text = ResourceManager.GetString("Delete");

            // Set font size list
            if (fontsizeList != null)
                fontsizeList.SelectedValue = userToEdit.Profile.FontSize.ToString();

			// Set font size list
			if (ynEnableHelp != null)
				ynEnableHelp.Items.FindByValue(Globals.SafeBool(userToEdit.GetExtendedAttribute("CPShowHelpIcons"),true).ToString()).Selected = true;	

            // Set font size list
			if (PageSize != null)
			{
				int ps = Globals.SafeInt(userToEdit.GetExtendedAttribute("CPPageSize"),10);
				ListItem li = PageSize.Items.FindByValue(ps.ToString());
				if(li != null)
					li.Selected = true;
			}

			if (csContext.SiteSettings.EnableSectionLocalization)
			{
				if (FilterLanguageList != null)
				{
					PopulateFilterLanguages();

					foreach (string flKey in userToEdit.FilterLanguageKeysToExclude)
					{
						ListItem li = FilterLanguageList.Items.FindByValue(flKey);
						if (li != null)
							li.Selected = true;
					}
				}
			}
			else if (SectionLocalizationArea != null)
				SectionLocalizationArea.Visible = false;
        	
        	// Site Contact Options
			if (contactCheckboxes != null)
				contactCheckboxes.Visible = csContext.SiteSettings.ShowContactCheckboxes;
			if (csContext.SiteSettings.ShowContactCheckboxes)
			{
				if (allowSiteToContact != null)
					allowSiteToContact.SelectedValue = userToEdit.AllowSiteToContact;
				if (allowSitePartnersToContact != null)
					allowSitePartnersToContact.SelectedValue = userToEdit.AllowSitePartnersToContact;
			}
        }

		private void PopulateFilterLanguages()
		{
			foreach (FilterLanguage fl in CSConfiguration.GetConfig().FilterLanguages)
			{
				this.FilterLanguageList.Items.Add(new ListItem(fl.Name, fl.Key));
			}
		}
		
        #endregion		
		
        #region Skin
                
        protected override void AttachChildControls() 
        {
            commonName = FindControl("CommonName") as TextBox;
            username = (Literal) FindControl("Username");
            usernameEdit = (TextBox) FindControl("UsernameEdit");
            timezone = (TimezoneDropDownList) FindControl("Timezone");
            location = (TextBox) FindControl("Location");
            occupation = (TextBox) FindControl("Occupation");
            interests = (TextBox) FindControl("Interests");
            webAddress = (TextBox) FindControl("WebAddress");
            webLog = (TextBox) FindControl("WebLog");
			webGallery = (TextBox) FindControl("WebGallery");
            privateEmail = (TextBox) FindControl("PrivateEmail");
            publicEmail = (TextBox) FindControl("PublicEmail");
            msnIM = (TextBox) FindControl("MsnIM");
            aolIM = (TextBox) FindControl("AolIM");
            yahooIM = (TextBox) FindControl("YahooIM");
            icq = (TextBox) FindControl("ICQ");
            avatarUrl = (TextBox) FindControl("avatarUrl");
            enableAvatar = (RadioButtonList) FindControl("EnableAvatar");
            hideReadPosts = (RadioButtonList) FindControl("HideReadPosts");
            signature = (TextBox) FindControl("Signature");
            displayInMemberList = (RadioButtonList) FindControl("DisplayInMemberList");
            updateButtonBottom = (Button) FindControl("UpdateButtonBottom");
            language = (LanguageDropDownList) FindControl("Language");
            dateFormat = (DateFormatDropDownList) FindControl("DateFormat");
            defaultThreadView = (DateFilter) FindControl("DefaultThreadView");
            signatureMaxLengthValidator = (CustomValidator) FindControl("SignatureMaxLengthValidator");
            uploadedAvatar = (HtmlInputFile) FindControl("AvatarUpload");
            avatarUpdateButton = (Button) FindControl("SubmitAvatar");
            gender = (GenderRadioButtonList) FindControl("Gender");
            changePassword = (HtmlAnchor) FindControl("ChangePassword");
            changePasswordAnswer = (HtmlAnchor) FindControl("ChangePasswordAnswer");
            birthday = (DatePickerToggle) FindControl("Birthday");
            theme = (ThemeDropDownList) FindControl("Theme");
            enableEmailTracking = (RadioButtonList) FindControl("EnableEmailTracking");
            enableHtmlEmail = (RadioButtonList) FindControl("EnableHtmlEmail");
            fontsizeList = (FontSizeDropDownList) FindControl("FontSize");
            avatarMsg = (Label) FindControl("AvatarMsg");
            enableAvatarMsg = (Label) FindControl("EnableAvatarMsg");
            editorList = FindControl("EditorList") as DropDownList;
			postViewType = FindControl("PostViewType") as DropDownList;
            enableEmail = (RadioButtonList) FindControl("ReceiveEmails");
            sortOrder = (SortOrderDropDownList) FindControl("SortOrder");
            enableCollapsingPanels = (YesNoRadioButtonList) FindControl("EnableCollapsingPanels");
            EnableEmoticons = (YesNoRadioButtonList) FindControl("EnableEmoticons");
            formStatus = FindControl("formStatus") as StatusMessage;
            bio = FindControl("bio") as TextBox;
            enablePostPreviewPopup = (YesNoRadioButtonList) FindControl("EnablePostPreviewPopup");
            DateCreated = (Literal) FindControl("DateCreated");
            LastLogin = (Literal) FindControl("LastLogin");
            LastActivity = (Literal) FindControl("LastActivity");
            avatarSection = FindControl("AvatarSection");
            avatar = (UserAvatar) FindControl("Avatar");
            EnableSignature = FindControl("EnableSignature");
            EnableGender = FindControl("EnableGender");
            EnablePasswordQuestionAnswer = FindControl("EnablePasswordQuestionAnswer");
            EmoticonRow = FindControl("EmoticonRow");
			ShareFavoriteUsers = (CheckBox)FindControl("ShareFavoriteUsers");
			FavoriteUsers = (Repeater)FindControl("FavoriteUsers");
			DeleteFavoriteUsers = FindButton("DeleteFavoriteUsers");
			Watchers = (Repeater)FindControl("Watchers");
			ShareFavoritePosts = (CheckBox)FindControl("ShareFavoritePosts");
			FavoritePosts = (Repeater)FindControl("FavoritePosts");
			DeleteFavoritePosts = FindButton("DeleteFavoritePosts");
			ShareFavoriteSections = (CheckBox)FindControl("ShareFavoriteSections");
			FavoriteSections = (Repeater)FindControl("FavoriteSections");
			DeleteFavoriteSections = FindButton("DeleteFavoriteSections");
			enableInk = FindControl("enableInk") as YesNoRadioButtonList;
            enableDisplayNames = FindControl("enableDisplayNames") as YesNoRadioButtonList;
			EnablePostPreviewPopupLabel = FindControl("EnablePostPreviewPopupLabel") as ResourceControl;
			ReceiveEmailsLabel = FindControl("ReceiveEmailsLabel") as ResourceControl;
			EnableHtmlEmailLabel = FindControl("EnableHtmlEmailLabel") as ResourceControl;
			EnableEmailTrackingLabel = FindControl("EnableEmailTrackingLabel") as ResourceControl;
			ThemeLabel = FindControl("ThemeLabel") as ResourceControl;
			AvatarUrlLabel = FindControl("AvatarUrlLabel") as ResourceControl;
			EmailTitleLabel = FindControl("EmailTitleLabel") as ResourceControl;
			ynEnableHelp = FindControl("ynEnableHelp") as YesNoRadioButtonList;
			PageSize = FindControl("PageSize") as DropDownList;
			ControlPanelManageView = FindControl("ControlPanelManageView") as DropDownList;
			ControlPanelManageViewArea = FindControl("ControlPanelManageViewArea");
			SectionLocalizationArea = FindControl("SectionLocalizationArea") as PlaceHolder;
			FilterLanguageList = FindControl("FilterLanguageList") as CheckBoxList;

			contactCheckboxes = FindControl("ContactCheckboxes");
			allowSiteToContact = FindControl("AllowSiteToContact") as YesNoRadioButtonList;
			allowSitePartnersToContact = FindControl("AllowSitePartnersToContact") as YesNoRadioButtonList;

            enableUserAvtars = FindControl("enableUserAvtars") as YesNoRadioButtonList;
            enableUserSignatures = FindControl("enableUserSignatures") as YesNoRadioButtonList;

			InitializeChildControls();
        }

        private void InitializeChildControls() 
        {
            if (updateButtonBottom != null)
                updateButtonBottom.Click += new EventHandler(Update_Click);

            if (avatarUpdateButton != null)
                avatarUpdateButton.Click += new EventHandler(UpdateAvatar_Click);

			if (DeleteFavoriteUsers != null)
				DeleteFavoriteUsers.Click += new EventHandler(DeleteFavoriteUsers_Click);

			if (DeleteFavoritePosts != null)
				DeleteFavoritePosts.Click += new EventHandler(DeleteFavoritePosts_Click);

			if (DeleteFavoriteSections != null)
				DeleteFavoriteSections.Click += new EventHandler(DeleteFavoriteSections_Click);
        }
		        
        #endregion

        #region Event Handlers

		public void DeleteFavoriteUsers_Click(object sender, EventArgs e)
		{
			foreach (RepeaterItem item in FavoriteUsers.Items)
			{
				if (((CheckBox)item.FindControl("Select")).Checked)
				{
					int itemID = int.Parse(((HtmlInputHidden)item.FindControl("ItemID")).Value);
					Favorites.DeleteFavorite(FavoriteType.User, csContext.User.UserID, itemID);
				}
			}

			BindFavoriteUsers();

			Update_Click(sender, e);
		}

		public void DeleteFavoritePosts_Click(object sender, EventArgs e)
		{
			foreach (RepeaterItem item in FavoritePosts.Items)
			{
				if (((CheckBox)item.FindControl("Select")).Checked)
				{
					int itemID = int.Parse(((HtmlInputHidden)item.FindControl("ItemID")).Value);
					Favorites.DeleteFavorite(FavoriteType.Post, csContext.User.UserID, itemID);
				}
			}

			BindFavoritePosts();

			Update_Click(sender, e);
		}

		public void DeleteFavoriteSections_Click(object sender, EventArgs e)
		{
			foreach (RepeaterItem item in FavoriteSections.Items)
			{
				if (((CheckBox)item.FindControl("Select")).Checked)
				{
					int itemID = int.Parse(((HtmlInputHidden)item.FindControl("ItemID")).Value);
					Favorites.DeleteFavorite(FavoriteType.Section, csContext.User.UserID, itemID);
				}
			}

			BindFavoriteSections();

			Update_Click(sender, e);
		}

        /// <summary>
        /// Save user image/avtar to the datastore
        /// </summary>
        public void UpdateAvatar_Click(Object sender, EventArgs e) 
        {
            try 
            {
                Resources.UpdateAvatar( csContext.User.UserID, uploadedAvatar.PostedFile.InputStream );

                if (avatarUrl != null)
                    avatarUrl.Text = "users/avatar.aspx?userid=" + csContext.User.UserID.ToString();
            } 
            catch 
            {
                throw new CSException(CSExceptionType.UnknownError);
            }

            Update_Click( sender, e );
        }

        /// <summary>
        /// Update the current user.
        /// </summary>
        public void Update_Click(Object sender, EventArgs e) 
        {
            if (!Page.IsValid)
                return;

            // Check the max length on the signature
            if (signature != null)
            {
                if (signature.Text.Length > csContext.SiteSettings.UserSignatureMaxLength) 
                {
                    if (signatureMaxLengthValidator != null)
                        signatureMaxLengthValidator.IsValid = false;

                    return;
                }
            }

			// Check if User account is locked before editing
			if (userToEdit.Member != null && userToEdit.Member.IsLockedOut == true)
			{
				if (formStatus != null)
				{
					formStatus.Success = false;
					formStatus.Visible = true;
					formStatus.ResourceName = "EditProfile_AccountLocked";
				}
				return;
			}


            // Get the updated values from the form
            //
			if (ShareFavoriteUsers != null)
			{
				if (ShareFavoriteUsers.Checked)
					userToEdit.FavoritesShared |= FavoriteType.User;
				else
					userToEdit.FavoritesShared &= ~(FavoriteType.User);
			}

			if (ShareFavoritePosts != null)
			{
				if (ShareFavoritePosts.Checked)
					userToEdit.FavoritesShared |= FavoriteType.Post;
				else
					userToEdit.FavoritesShared &= ~(FavoriteType.Post);
			}

			if (ShareFavoriteSections != null)
			{
				if (ShareFavoriteSections.Checked)
					userToEdit.FavoritesShared |= FavoriteType.Section;
				else
					userToEdit.FavoritesShared &= ~(FavoriteType.Section);
			}

            if (usernameEdit != null && 
                csContext.SiteSettings.EnableUsernameChange)
            {
                userToEdit.Username = usernameEdit.Text;
            }

            // Update gender?
            if (gender != null && 
                csContext.SiteSettings.AllowGender)
            {
                userToEdit.Profile.Gender = (Gender) int.Parse(gender.SelectedItem.Value);
            }

            if (commonName != null)
                userToEdit.Profile.CommonName = commonName.Text;

            if (timezone != null)
                userToEdit.Profile.Timezone = double.Parse(timezone.SelectedItem.Value);

            if (location != null)
                userToEdit.Profile.Location = location.Text;

            if (occupation != null)
                userToEdit.Profile.Occupation = occupation.Text;

            if (interests != null)
                userToEdit.Profile.Interests = interests.Text;

            if (signature != null)
                userToEdit.Profile.Signature = signature.Text;

            if (bio != null)
                userToEdit.Profile.Bio = bio.Text;

            if (fontsizeList != null)
                userToEdit.Profile.FontSize = int.Parse(fontsizeList.SelectedValue);

            if (webAddress != null)
                userToEdit.Profile.WebAddress = webAddress.Text;

            if (webLog != null)
                userToEdit.Profile.WebLog = webLog.Text;

			if (webGallery != null)
				userToEdit.Profile.WebGallery = webGallery.Text;

            if (signature != null)
                userToEdit.Profile.SignatureFormatted = signature.Text;

            if (privateEmail != null)
                userToEdit.Email = privateEmail.Text;

            if (publicEmail != null)
                userToEdit.Profile.PublicEmail = publicEmail.Text;

            if (msnIM != null)
                userToEdit.Profile.MsnIM = msnIM.Text;

            if (aolIM != null)
                userToEdit.Profile.AolIM = aolIM.Text;

            if (yahooIM != null)
                userToEdit.Profile.YahooIM = yahooIM.Text;

            if (icq != null)
                userToEdit.Profile.IcqIM = icq.Text;

            if (avatarUrl != null)
                userToEdit.AvatarUrl = avatarUrl.Text;

            if (dateFormat != null)
                userToEdit.Profile.DateFormat = dateFormat.SelectedItem.Value;

            if (enableAvatar != null)
                userToEdit.EnableAvatar = bool.Parse(enableAvatar.SelectedItem.Value);

            if (enableEmailTracking != null)
                userToEdit.EnableThreadTracking = bool.Parse(enableEmailTracking.SelectedItem.Value);

            if (displayInMemberList != null)
                userToEdit.EnableDisplayInMemberList = bool.Parse(displayInMemberList.SelectedItem.Value);

            if (enableHtmlEmail != null)
                userToEdit.EnableHtmlEmail = bool.Parse(enableHtmlEmail.SelectedItem.Value);

            if (EnableEmoticons != null)
                userToEdit.Profile.EnableEmoticons = EnableEmoticons.SelectedValue;

            if (editorList != null)
                userToEdit.EditorType = editorList.SelectedValue;
            
			if (postViewType != null)
				userToEdit.PostViewType = (PostViewType) int.Parse(postViewType.SelectedValue);
            
			if (ControlPanelManageView != null && (userToEdit.IsBlogAdministrator || userToEdit.IsGalleryAdministrator || userToEdit.IsFileAdministrator || userToEdit.IsForumAdministrator))
				userToEdit.ControlPanelManageView = (CommunityServer.Components.ControlPanelManageView) int.Parse(ControlPanelManageView.SelectedValue);
            
            if (sortOrder != null)
            {
                if (int.Parse(sortOrder.SelectedItem.Value) == 1)
                    userToEdit.PostSortOrder = SortOrder.Descending;
                else
                    userToEdit.PostSortOrder = SortOrder.Ascending;
            }

			if(enableInk != null)
				userToEdit.EnableInk = enableInk.SelectedValue;

            if(enableDisplayNames != null)
                userToEdit.EnableDisplayName = enableDisplayNames.SelectedValue;

            if (enableEmail != null)
            {
                userToEdit.EnableEmail = bool.Parse(enableEmail.SelectedItem.Value);
                if (!csContext.SiteSettings.EnableEmail)
                    userToEdit.EnableEmail = false;
            }

            if (language != null)
                userToEdit.Profile.Language = language.SelectedItem.Value;

			// if (enablePostPreviewPopup != null && forumConfig.EnablePostPreviewPopup)  
			if (enablePostPreviewPopup != null )  
            {  				
                userToEdit.Profile.EnablePostPreviewPopup = bool.Parse( enablePostPreviewPopup.SelectedItem.Value );
            }	
       
            if (birthday != null)
                userToEdit.Profile.BirthDate = birthday.SelectedDate;

            if (theme != null)
                userToEdit.Theme = theme.SelectedValue;

            if (enableCollapsingPanels != null)
                userToEdit.EnableCollapsingPanels = bool.Parse( enableCollapsingPanels.SelectedItem.Value );

            if(enableUserAvtars != null)
                userToEdit.EnableUserAvtars = enableUserAvtars.SelectedValue;

            if(enableUserSignatures != null)
                userToEdit.EnableUserSignatures = enableUserSignatures.SelectedValue;

			if (ynEnableHelp != null)
				userToEdit.SetExtendedAttribute("CPShowHelpIcons", ynEnableHelp.SelectedValue.ToString());
			if (PageSize != null)
				userToEdit.SetExtendedAttribute("CPPageSize", PageSize.SelectedValue);


			if (csContext.SiteSettings.EnableSectionLocalization && FilterLanguageList != null)
			{
				userToEdit.ClearFilterLanguagesToExclude();

				foreach (ListItem li in FilterLanguageList.Items)
				{
					if (li.Selected)
						userToEdit.AddFilterLanguageToExclude(li.Value);
				}
			}
        	
        	// Update site contact settings
			if (csContext.SiteSettings.ShowContactCheckboxes)
			{
				if (allowSiteToContact != null)
					userToEdit.AllowSiteToContact = allowSiteToContact.SelectedValue;
				if (allowSitePartnersToContact != null)
					userToEdit.AllowSitePartnersToContact = allowSitePartnersToContact.SelectedValue;
			}

            SetExtendedUserData();

            // Update the user
            //
            try 
            {
                Users.UpdateUser(userToEdit);

            }
            catch (CSException ex) 
            {
                // Check to see if the MemberRole component threw a duplicate email exception. If so we want to handle it gracefully.
                if (ex.CreateUserStatus == CreateUserStatus.DuplicateEmailAddress)
                {
                    // Notify that update was not successful because of duplicate email
                    if (formStatus != null)
                    {
                        formStatus.Success = false;
                        formStatus.Visible = true;
                        formStatus.ResourceName = "EditProfile_DuplicateEmail";
                    }

                    return;
                }

                throw;
            }
         
            // Notify the End of Update
            //
            if (formStatus != null)
            {
                formStatus.Success = true;
                formStatus.Visible = true;
                formStatus.ResourceName = "EditProfile_UpdateSuccess";
            }
        }

        #endregion

        #region Helpers
		private void BindFavoriteUsers()
		{
			FavoriteUsers.DataSource = Favorites.GetUsers(userToEdit.UserID);
			FavoriteUsers.DataBind();
		}

		private void BindWatchers()
		{
			Watchers.DataSource = Favorites.GetUsersWatching(userToEdit.UserID);
			Watchers.DataBind();
		}

		private void BindFavoritePosts()
		{
			FavoritePosts.DataSource = Favorites.GetPosts(userToEdit.UserID);
			FavoritePosts.DataBind();
		}

		private void BindFavoriteSections()
		{
			FavoriteSections.DataSource = Favorites.GetSections(userToEdit.UserID);
			FavoriteSections.DataBind();
		}

		private void BindExtendedUserControls()
		{
			foreach (string controlName in ExtendedUserData.Fields)
			{
				Control c  = FindControl(controlName);
				if (c != null)
				{
					string value = userToEdit.GetExtendedAttribute(c.ID);

					if (c is TextBox)
						((TextBox)c).Text = value;
					else if ((c is CheckBox) && (value != string.Empty))
						((CheckBox)c).Checked = bool.Parse(value);
					else if ((c is ListControl) && (((ListControl)c).Items.FindByValue(value) != null))
						((ListControl)c).Items.FindByValue(value).Selected = true;
				}
			}
		}

		private void SetExtendedUserData()
		{
			foreach (string controlName in ExtendedUserData.Fields)
			{
				Control c  = FindControl(controlName);
				if (c != null)
				{
					string value = null;

					if (c is TextBox)
						value = ((TextBox)c).Text;
					else if (c is ListControl)
						value = ((ListControl)c).SelectedValue;
					else if (c is CheckBox)
						value = ((CheckBox)c).Checked.ToString();

					if (value != null)
						userToEdit.SetExtendedAttribute(c.ID, value);
				}
			}
		}
		#endregion
	}
}
