protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {
                androidButton = (global::Android.Widget.Button)Control;
                formsElement = (CustomImageButton)this.Element;
                androidButton.SetPadding(20, 20, 20, 20);
                androidButton.SetAllCaps(false);
                if (formsElement.ImageName != null)
                    androidButton.SetBackgroundDrawable(Context.Resources.GetDrawable(formsElement.ImageName));


                if (formsElement.TextOrientation != null)
                {
                    if (Convert.ToString(formsElement.TextOrientation) == "Left")
                    {

                        androidButton.Gravity = Android.Views.GravityFlags.Left;
                    }
                    else if (Convert.ToString(formsElement.TextOrientation) == "Right")
                    {
                        androidButton.Gravity = Android.Views.GravityFlags.Right;
                    }
                    else
                    {
                        androidButton.Gravity = Android.Views.GravityFlags.Center;
                    }
                }
            }
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {

                winButton = Control;
                formsElement = (CustomImageButton)this.Element;
             

                if( formsElement.TextOrientation == TextOrientation.Left )
                {
                    winButton.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left;
                }
                else if (formsElement.TextOrientation == TextOrientation.Middle)
                {
                   winButton.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                }
                else
                {
                    winButton.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                }

                formsElement.BorderColor = Xamarin.Forms.Color.Transparent;
                formsElement.BorderWidth = 0;
                if (formsElement.ImageName != null )
                winButton.Background = new ImageBrush { Stretch = System.Windows.Media.Stretch.Fill, ImageSource = new BitmapImage(new Uri(formsElement.ImageName, UriKind.Relative)) };

      
               
            }
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement == null)
            {
                iosButton = (UIButton) Control;
                formsElement = (CustomImageButton)this.Element;

                if (formsElement.ImageName != null)
                {
                    iosButton.SetBackgroundImage(UIImage.FromBundle(formsElement.ImageName), UIControlState.Normal);
                }

            
              
                 /*   if (Convert.ToString(callingElement.TextOrientation) == CustomLocalization.GetString(LEFT,string.Empty))
                    {

                        nativeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left;
                    }
                    else if (Convert.ToString(callingElement.TextOrientation) == CustomLocalization.GetString(RIGHT, string.Empty))
                    {

                        nativeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right;
                    }
                    else
                    {

                        nativeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
                    }*/
                
                
            }
        }
        public void Dispose()
        {
            this.masterLayout = null;
            this.name = null;
            this.divider = null;
            this.deleteButton = null;

            GC.Collect();
        }
        public ActionPreviewCellItem()
        {
            masterLayout = new CustomLayout();
            masterLayout.BackgroundColor = Constants.MENU_BG_COLOR;
            // IDeviceSpec deviceSpec = DependencyService.Get<IDeviceSpec>();
            name = new Label();
            name.SetBinding(Label.TextProperty, "Name");
            name.TextColor = Color.Gray;
            name.FontSize = Device.OnPlatform(12, 15, 18);
            name.WidthRequest = App.screenWidth * 50 / 100;

            divider = new StackLayout();
            divider.WidthRequest = App.screenWidth;
            divider.HeightRequest = .75;
            divider.BackgroundColor = Color.FromRgb(255, 255, 255);

            deleteButton = new CustomImageButton();
            deleteButton.ImageName = Device.OnPlatform("delete_button.png", "delete_button.png", @"/Assets/delete_button.png");
            deleteButton.WidthRequest = Device.OnPlatform( 20, 20, 60 );
            deleteButton.HeightRequest = Device.OnPlatform(20, 20, 60);
            deleteButton.SetBinding(CustomImageButton.ClassIdProperty, "Name");

            deleteButton.Clicked += (sender, e) =>
            {
                Device.BeginInvokeOnMainThread(() =>
               {
                   try
                   {
                       CustomImageButton button = sender as CustomImageButton;
                       PreviewItem itemToDel = FeelingsSecondPage.actionPreviewListSource.FirstOrDefault(item => item.Name == button.ClassId);
                       if (itemToDel != null)
                       {
                           mainPage.ShowAlert("Are you sure you want to delete this item ?.", itemToDel);
                       }
                   }
                   catch (Exception ex)
                   {
                       
                   }
               });

            };

            masterLayout.WidthRequest = App.screenWidth;
            masterLayout.HeightRequest = App.screenHeight * Device.OnPlatform(30, 50, 6) / 100;
            masterLayout.AddChildToLayout(name, (float)Device.OnPlatform(5, 5, 5), (float)Device.OnPlatform(5, 5, 25), (int)masterLayout.WidthRequest, (int)masterLayout.HeightRequest);
            masterLayout.AddChildToLayout(deleteButton, (float)Device.OnPlatform( 80, 80, 75 ), (float)Device.OnPlatform(5, 3.5, 5), (int)masterLayout.WidthRequest, (int)masterLayout.HeightRequest);
            // masterLayout.AddChildToLayout(divider, (float)1, (float)20, (int)masterLayout.WidthRequest, (int)masterLayout.HeightRequest);
            this.View = masterLayout;

        }
        public void Dispose()
        {
            this.mainTitleBar.imageAreaTapGestureRecognizer.Tapped -= imageAreaTapGestureRecognizer_Tapped;
            this.mainTitleBar = null;
            this.subTitleBar.BackButtonTapRecognizer.Tapped -= OnBackButtonTapRecognizerTapped;
            this.subTitleBar.NextButtonTapRecognizer.Tapped -= NextButtonTapRecognizer_Tapped;
            this.Appearing -= FeelingNowPage_Appearing;
            this.goalsAndDreamsPickerButton.Clicked -= OnGoalsPickerButtonClicked;
            this.goalsAndDreamsPickerButton = null;
            this.actionPickerButton.Clicked -= OnActionPickerButtonClicked;
            this.actionPickerButton = null;
            this.subTitleBar = null;
            this.masterLayout = null;
            // this.deviceSpec = null;
            actionPreviewListSource.Clear();
            actionPreviewListSource = null;
            this.actionPreviewListView = null;
            this.listContainer = null;
            this.slider = null;
            this.selectedGoal = null;
            this.selectedActions = null;

            GC.Collect();
        }
        public FeelingsSecondPage()
        {
            progressBar = DependencyService.Get<IProgressBar>();
            NavigationPage.SetHasNavigationBar(this, false);
            masterLayout = new CustomLayout();
            masterLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
            //deviceSpec = DependencyService.Get<IDeviceSpec>();
			AddEventsSituationsOrThoughts.feelingSecondPage = this;
            this.Appearing += FeelingsSecondPage_Appearing;
            actionPreviewListSource = new ObservableCollection<PreviewItem>();

            mainTitleBar = new PurposeColorTitleBar(Color.FromRgb(8, 135, 224), "Purpose Color", Color.Black, "back", true);
            mainTitleBar.imageAreaTapGestureRecognizer.Tapped += imageAreaTapGestureRecognizer_Tapped;

            subTitleBar = new PurposeColorSubTitleBar(Constants.SUB_TITLE_BG_COLOR, "Emotional Awareness");
            subTitleBar.BackButtonTapRecognizer.Tapped += OnBackButtonTapRecognizerTapped;
            subTitleBar.NextButtonTapRecognizer.Tapped += NextButtonTapRecognizer_Tapped;
            screenHeight = App.screenHeight;
            screenWidth = App.screenWidth;
			aePicker = null;
			actionlist = null;

            Label firstLine = new Label();
            firstLine.Text = "Does being";
            firstLine.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            firstLine.TextColor = Color.FromRgb(40, 47, 50);
            firstLine.HeightRequest = screenHeight * 15 / 100;
            firstLine.HorizontalOptions = LayoutOptions.Center;
            firstLine.WidthRequest = screenWidth;
            firstLine.XAlign = TextAlignment.Center;

            Label secondLine = new Label();
            secondLine.Text = App.SelectedEmotion;
            secondLine.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            secondLine.FontAttributes = FontAttributes.Italic;
            secondLine.TextColor = Constants.BLUE_BG_COLOR;//Color.FromRgb(40, 47, 50);
            secondLine.HeightRequest = screenHeight * 15 / 100;
            secondLine.HorizontalOptions = LayoutOptions.Center;
            secondLine.WidthRequest = screenWidth;
            secondLine.XAlign = TextAlignment.Center;

            Label thirdLine = new Label();
            thirdLine.Text = "support your goals and dreams?";
            thirdLine.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            thirdLine.TextColor = Color.FromRgb(40, 50, 50);
            thirdLine.HeightRequest = screenHeight * 11 / 100;
            thirdLine.HorizontalOptions = LayoutOptions.Center;
            thirdLine.WidthRequest = screenWidth;
            thirdLine.XAlign = TextAlignment.Center;


            goalsAndDreamsPickerButton = new PurposeColor.interfaces.CustomImageButton();
            goalsAndDreamsPickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", @"/Assets/select_box_whitebg.png");
            goalsAndDreamsPickerButton.Text = "Goals & Dreams";
            goalsAndDreamsPickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            goalsAndDreamsPickerButton.TextOrientation = interfaces.TextOrientation.Left;
            goalsAndDreamsPickerButton.FontSize = 17;
            goalsAndDreamsPickerButton.TextColor = Color.Gray;
            goalsAndDreamsPickerButton.WidthRequest = screenWidth * 90 / 100;

            goalsAndDreamsPickerButton.Clicked += OnGoalsPickerButtonClicked;


            actionPickerButton = new CustomImageButton();
            actionPickerButton.IsVisible = false;
            actionPickerButton.BackgroundColor = Color.FromRgb(30, 126, 210);
            actionPickerButton.Text = "Add Supporting Actions";
            actionPickerButton.TextColor = Color.White;

            actionPickerButton.TextOrientation = TextOrientation.Middle;
            actionPickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            // actionPickerButton.TextOrientation = interfaces.TextOrientation.Left;
            actionPickerButton.WidthRequest = screenWidth * 90 / 100;

            actionPickerButton.Clicked += OnActionPickerButtonClicked;


            if (App.screenDensity > 1.5)
            {
                firstLine.FontSize = Device.OnPlatform(20, 20, 30);
                secondLine.FontSize = Device.OnPlatform(20, 22, 30);
                thirdLine.FontSize = Device.OnPlatform(20, 20, 30);
                actionPickerButton.FontSize = 17;
                actionPickerButton.HeightRequest = screenHeight * 6 / 100;
                goalsAndDreamsPickerButton.HeightRequest = screenHeight * 6 / 100;
            }
            else
            {
                firstLine.FontSize = Device.OnPlatform(16, 18, 26);
                secondLine.FontSize = Device.OnPlatform(16, 20, 26);
                thirdLine.FontSize = Device.OnPlatform(16, 18, 26);
                actionPickerButton.FontSize = 15;
                actionPickerButton.HeightRequest = screenHeight * 9 / 100;
                goalsAndDreamsPickerButton.HeightRequest = screenHeight * 9 / 100;
            }

            slider = new CustomSlider
            {
                Minimum = -2,
                Maximum = 2,
                WidthRequest = screenWidth * 90 / 100
            };
            slider.StopGesture = GetstopGetsture;


            //Image sliderDivider1 = new Image();
            //sliderDivider1.Source = "drag_sepeate.png";


            //Image sliderDivider2 = new Image();
            //sliderDivider2.Source = "drag_sepeate.png";


            //Image sliderDivider3 = new Image();
            //sliderDivider3.Source = "drag_sepeate.png";

            //Image sliderBG = new Image();
            //sliderBG.Source = "drag_bg.png";

            this.Appearing += FeelingNowPage_Appearing;

            masterLayout.AddChildToLayout(mainTitleBar, 0, 0);
            masterLayout.AddChildToLayout(subTitleBar, 0, Device.OnPlatform(9, 10, 9));
            masterLayout.AddChildToLayout(firstLine, 0, 20);
            masterLayout.AddChildToLayout(secondLine, 0, 25);
            masterLayout.AddChildToLayout(thirdLine, 0, 30);
            //masterLayout.AddChildToLayout(sliderBG, 7, 45);
            masterLayout.AddChildToLayout(slider, 5, Device.OnPlatform(37, 35, 34));
            /*  masterLayout.AddChildToLayout(sliderDivider1, 30, 45.5f);
              masterLayout.AddChildToLayout(sliderDivider2, 50, 45.5f);
              masterLayout.AddChildToLayout(sliderDivider3, 70, 45.5f);*/
            masterLayout.AddChildToLayout(goalsAndDreamsPickerButton, 5, Device.OnPlatform(50, 50, 45));
            masterLayout.AddChildToLayout(actionPickerButton, 5, Device.OnPlatform(65, 65, 55));


            listContainer = new StackLayout();
            listContainer.BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY;
            listContainer.WidthRequest = screenWidth * 90 / 100;
            listContainer.HeightRequest = screenHeight * 20 / 100;
            listContainer.ClassId = "preview";

            actionPreviewListView = new ListView();
            actionPreviewListView.BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY;
            actionPreviewListView.ItemTemplate = new DataTemplate(typeof(ActionPreviewCellItem));
            ActionPreviewCellItem.mainPage = this;
            actionPreviewListView.SeparatorVisibility = SeparatorVisibility.None;
            actionPreviewListView.Opacity = 1;
            actionPreviewListView.ItemsSource = actionPreviewListSource;
            listContainer.Children.Add(actionPreviewListView);
            masterLayout.AddChildToLayout(listContainer, 5, Device.OnPlatform(73, 73, 64));

            Content = masterLayout;

        }
		void RenderGems( CommunityGemsObject gemsObject, bool prevButtonNeeded )
		{
			try
			{
				/*Button loadPreviousGems = new Button();
				loadPreviousGems.BackgroundColor = Color.Transparent;
				loadPreviousGems.TextColor = Constants.BLUE_BG_COLOR;
				loadPreviousGems.Text = "Load previous gems";
				loadPreviousGems.FontSize = 12;
				loadPreviousGems.BorderWidth = 0;
				loadPreviousGems.BorderColor = Color.Transparent;
				loadPreviousGems.Clicked += OnLoadPreviousGemsClicked;
				masterStackLayout.Children.Add( loadPreviousGems );*/

				foreach (var item in gemsObject.resultarray )
				{
					CustomLayout masterStack = new CustomLayout();
					masterStack.WidthRequest = App.screenWidth * 102 / 100;
					masterStack.ClassId = "masterstack" + item.gem_id;
					masterStack.BackgroundColor = Color.White;// Color.FromRgb(244, 244, 244);

					#region TOOLS LAYOUT

					StackLayout toolsLayout = new StackLayout();
					toolsLayout.BackgroundColor = Color.White;
					toolsLayout.Spacing = App.screenWidth*.10;
					toolsLayout.Orientation = StackOrientation.Horizontal;
					//toolsLayout.WidthRequest = App.screenWidth * 95 / 100;
					toolsLayout.HeightRequest = App.screenHeight * .05;
					toolsLayout.HorizontalOptions = LayoutOptions.Center;
					toolsLayout.Padding = new Thickness(10, 0, 10, 0);

					likeButtonTap = new TapGestureRecognizer();
					Image likeButton = new Image();
					string likeSource = ( item.like_status == 1 ) ? "icn_liked.png" : "icn_like.png";
					likeButton.Source = likeSource;
					likeButton.WidthRequest = Device.OnPlatform(15, 15, 15);
					likeButton.HeightRequest = Device.OnPlatform(15, 15, 15);
					likeButton.VerticalOptions = LayoutOptions.Center;
					likeButton.ClassId = item.gem_id + "&&"  + item.gem_type;
					likeButton.GestureRecognizers.Add(likeButtonTap);

					Label likeLabel = new Label
					{
						Text = "Like",
						FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
						TextColor = Color.Gray,
						VerticalOptions = LayoutOptions.Center,
						FontSize = Device.OnPlatform(12, 12, 15),
						ClassId = item.gem_id + "&&" + item.gem_type
					};
					likeLabel.GestureRecognizers.Add(likeButtonTap);

					Label likeCount = new Label
					{
						Text = ( item.likecount > 0 ) ? item.likecount.ToString() : "",
						FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
						TextColor = Color.Blue,
						VerticalOptions = LayoutOptions.Center,
						FontSize = Device.OnPlatform(12, 12, 15)
					};
					StackLayout likeLayout = new StackLayout{Children = {likeCount, likeButton, likeLabel}, Orientation = StackOrientation.Horizontal, Spacing = 5};


					toolsLayout.Children.Add( likeLayout  );

//					toolsLayout.Children.Add(likeCount);
//					toolsLayout.Children.Add(likeButton);
//					toolsLayout.Children.Add(likeLabel);

					likeButtonTap.Tapped += async (object tapSender, EventArgs eTap) => 
					{
						try
						{
							string gemID = "";
							Image likeImg = tapSender as Image;
							Label like = tapSender as Label;
							Label likeCountLabel = new Label();
							if (likeImg != null)
							{
								int likeImgIndex = likeLayout.Children.IndexOf( likeImg );
								if( likeImgIndex > 0 )
								{
									likeCountLabel =(Label) likeLayout.Children[ likeImgIndex - 1 ];
								}
								if (likeImg.ClassId != null)
									gemID = likeImg.ClassId;
							}

							if (like != null)
							{
								int labelIndex = likeLayout.Children.IndexOf( like );
								if( labelIndex > 0 )
								{
									likeImg =(Image) likeLayout.Children[ labelIndex - 1 ];
									likeCountLabel =(Label) likeLayout.Children[ labelIndex - 2 ];
								}
								if (like.ClassId != null)
									gemID = like.ClassId;
							}

							//likeButtonTap.Tapped -= OnLikeButtonTapped;
							progressBar.ShowProgressbar("Requesting...   ");
							/////////////// for testing /////////////

							string[] delimiters = { "&&" };
							string[] clasIDArray = gemID.Split(delimiters, StringSplitOptions.None);
							string selectedGemID = clasIDArray [0];
							string selectedGemType = clasIDArray [1];

							LikeResponse likeRes = await ServiceHelper.LikeGem( selectedGemID, selectedGemType );
							if( likeRes != null )
							{
								string source = ( likeRes.like_status == 1 ) ? "icn_liked.png" : "icn_like.png";
								likeImg.Source = source;
								if( likeCountLabel != null )
									likeCountLabel.Text =  ( likeRes.likecount > 0 ) ? likeRes.likecount.ToString() : "";
							}
							progressBar.HideProgressbar();

						}
						catch (Exception ex)
						{
							progressBar.HideProgressbar();
							DisplayAlert(Constants.ALERT_TITLE, "Could not process the request now.", Constants.ALERT_OK);
						}

						progressBar.HideProgressbar();
					};


					Image shareButton = new Image();
					shareButton.Source = Device.OnPlatform("share.png", "share.png", "//Assets//share.png");
					shareButton.WidthRequest = Device.OnPlatform(15, 15, 15);
					shareButton.HeightRequest = Device.OnPlatform(15, 15, 15);
					shareButton.VerticalOptions = LayoutOptions.Center;
					shareButton.ClassId = item.gem_id;
					shareLabel = new Label
					{
						Text = "Share",
						FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
						TextColor = Color.Gray,
						VerticalOptions = LayoutOptions.Center,
						FontSize = Device.OnPlatform(12, 12, 15),
						ClassId = item.gem_id
					};
					shareButtonTap = new TapGestureRecognizer();
					shareButtonTap.Tapped += OnShareButtonTapped;
					shareButton.GestureRecognizers.Add(shareButtonTap);
					shareLabel.GestureRecognizers.Add(shareButtonTap);
					toolsLayout.Children.Add( new StackLayout{Children = {shareButton, shareLabel}, Orientation = StackOrientation.Horizontal, Spacing = 5});

//					toolsLayout.Children.Add(shareButton);
//					toolsLayout.Children.Add(shareLabel);



					Image commentButton = new Image();
					commentButton.Source = Device.OnPlatform("icon_cmnt.png", "icon_cmnt.png", "//Assets//icon_cmnt.png");
					commentButton.WidthRequest = Device.OnPlatform(15, 15, 15);
					commentButton.HeightRequest = Device.OnPlatform(15, 15, 15);
					commentButton.VerticalOptions = LayoutOptions.Center;
					commentButton.ClassId = item.gem_id + "&&"  + item.gem_type;
					Label commentsLabel = new Label
					{
						VerticalOptions = LayoutOptions.Center,
						FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
						TextColor = Color.Gray,
						FontSize = Device.OnPlatform(12, 12, 15),
						ClassId = item.gem_id + "&&"  + item.gem_type
					};
					if( item.comment_count > 0 )
					{
						commentsLabel.Text = "Comments (" + item.comment_count.ToString() + ")";
					}
					else
					{
						commentsLabel.Text = "Comments";
					}

					commentButtonTap = new TapGestureRecognizer();
					commentButtonTap.Tapped += OnCommentButtonTapped;
					//commentButton.GestureRecognizers.Add(commentButtonTap);
					commentsLabel.GestureRecognizers.Add(commentButtonTap);


					toolsLayout.Children.Add( new StackLayout{Children = {commentButton, commentsLabel}, Orientation = StackOrientation.Horizontal, Spacing = 5});
//
//					toolsLayout.Children.Add(commentButton);
//					toolsLayout.Children.Add(commentsLabel);


					#endregion


					#region  title, description
					Image profileImage = new Image();
					profileImage.Source = (item.profileimg != null) ? Constants.SERVICE_BASE_URL + item.profileimg : "avatar.jpg";
					profileImage.WidthRequest = 60;
					profileImage.HeightRequest = 60;
					profileImage.Aspect = Aspect.Fill;
					profileImage.ClassId = item.user_id;
					TapGestureRecognizer profileImageTag = new TapGestureRecognizer();
					profileImageTag.Tapped += ProfileImageTag_Tapped;
					profileImage.GestureRecognizers.Add(profileImageTag);

					Label userName = new Label();
					userName.Text = item.firstname;
					userName.TextColor = Color.Black;
					userName.WidthRequest = App.screenWidth * 90 / 100;
					userName.FontAttributes = FontAttributes.Bold;
					userName.FontSize = Device.OnPlatform(14, 15, 12);
					userName.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;

					title = new Label();
					title.Text = item.gem_datetime;
					title.TextColor = Color.Black;
					title.WidthRequest = App.screenWidth * 90 / 100;
					title.FontSize = Device.OnPlatform(12, 12, 12);
					title.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;

					description = new Label();
					description.WidthRequest = App.screenWidth * .80;
					description.Text = item.gem_details;
					description.TextColor = Color.Black;
					description.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
					description.FontSize = Device.OnPlatform(12, 15, 15);

					CustomImageButton menuButton = new CustomImageButton
					{
						ImageName = Device.OnPlatform("downarrow.png", "downarrow.png", "//Assets//downarrow.png"),
						Text = string.Empty,
						HorizontalOptions = LayoutOptions.End,
						BackgroundColor = Color.Transparent,
						WidthRequest = 30,
						HeightRequest = 20,
						ClassId = item.gem_id
					};

		
					menuButton.Clicked += GemMenuButton_Clicked;

					CustomImageButton followButton = new CustomImageButton();
					//followButton.Text = "Follow";
					followButton.ImageName = "follow.png";
					followButton.TextColor = Color.White;
					followButton.HeightRequest = 20;
					followButton.BackgroundColor =  Color.FromRgb(8, 135, 224);
					followButton.WidthRequest = 60;
					followButton.ClassId = item.user_id;
					followButton.IsEnabled = true;
					if( item.follow_status > 0 )
					{
						followButton.ImageName = "follow_disable.png";	
						followButton.IsEnabled = false;
					}
					followButton.Clicked += async (object fsender, EventArgs fe) => 
					{
						CustomImageButton btn = fsender as CustomImageButton;
						btn.ImageName = "follow_disable.png";	
						btn.IsEnabled = false;
						if( btn != null && btn.ClassId != null )
						{
							if( currentUser != null )
							{
								progressBar.ShowProgressbar( "Loading...." );
								FollowResponse resp = await ServiceHelper.SendFollowRequest( currentUser.UserId.ToString(), btn.ClassId.ToString() );
								if( resp != null && resp.code == "400" )
								{
									progressBar.ShowToast( "Already sent reqeust." );
								}
								progressBar.HideProgressbar();
							}

						}
					};

					// masterStack.AddChildToLayout(pageTitle, 1, 1);
					//masterStack.AddChildToLayout(menuButton, 79, 1);
					masterStack.AddChildToLayout(profileImage, 4, 1);
					masterStack.AddChildToLayout(userName, 25, 3);
					masterStack.AddChildToLayout(title, 25, 7);

					if( (item.user_id != currentUser.UserId.ToString() ) && item.can_follow == "1")
					{
						masterStack.AddChildToLayout(followButton, 80, 3 );
					}

					TapGestureRecognizer moreTap = new TapGestureRecognizer();
					moreTap.Tapped += async (object senderr, EventArgs ee) =>
					{
						Image more = senderr as Image;
						if (more != null)
						{
							IProgressBar progress = DependencyService.Get<IProgressBar>();
							progress.ShowProgressbar("Loading more medias..");
							App.masterPage.IsPresented = false;
							CommunityGemsDetails gemInfo = communityGems.resultarray.FirstOrDefault(itm => itm.gem_id == more.ClassId);
							if (gemInfo != null)
							{
								List<PurposeColor.Constants.MediaDetails> mediaPlayerList = new List<PurposeColor.Constants.MediaDetails>();

								List<string> listToDownload = new List<string>();

								foreach (var mediaItem in  gemInfo.gem_media )
								{
									if(string.IsNullOrEmpty(mediaItem.gem_media))
									{
										continue;
									}

									if (mediaItem.media_type == "png" || mediaItem.media_type == "jpg" || mediaItem.media_type == "jpeg") 
									{

										listToDownload.Add(Constants.SERVICE_BASE_URL+ mediaItem.gem_media);
										string fileName = System.IO.Path.GetFileName(mediaItem.gem_media);
										mediaItem.gem_media = App.DownloadsPath + fileName;
										mediaPlayerList.Add(new PurposeColor.Constants.MediaDetails() { ImageName = mediaItem.gem_media, ID = item.gem_id, MediaType = mediaItem.media_type, Url = mediaItem.gem_media });
									}
									else if( mediaItem.media_type == "mp4" || mediaItem.media_type == "3gpp" )
									{
										mediaItem.gem_media = Constants.SERVICE_BASE_URL + mediaItem.gem_media ;
										mediaPlayerList.Add(new PurposeColor.Constants.MediaDetails() { ImageName = mediaItem.video_thumb, ID = item.gem_id, MediaType = mediaItem.media_type, Url = mediaItem.gem_media });
									}
									else
									{
										mediaItem.gem_media = Constants.SERVICE_BASE_URL + mediaItem.gem_media ;
										mediaPlayerList.Add(new PurposeColor.Constants.MediaDetails() { ImageName = mediaItem.gem_media, ID = item.gem_id, MediaType = mediaItem.media_type, Url = mediaItem.gem_media });
									}



								}

								// down load files //
								if (listToDownload != null && listToDownload.Count > 0) {
									IDownload downloader = DependencyService.Get<IDownload>();
									await downloader.DownloadFiles(listToDownload);
								}

								await Navigation.PushAsync(new CommunityMediaViewer(mediaPlayerList));
							}

							progress.HideProgressbar();
						}

					};
					Image moreImg = new Image();
					moreImg.Source = "more.png";
					moreImg.HorizontalOptions = LayoutOptions.End;
					moreImg.VerticalOptions = LayoutOptions.End;
					moreImg.GestureRecognizers.Add(moreTap);
					moreImg.ClassId = item.gem_id;

					#endregion

					StackLayout bottomAndLowerControllStack = new StackLayout
					{
						Orientation = StackOrientation.Vertical,
						BackgroundColor = Color.Transparent,
						Spacing = 1,
						Padding = new Thickness(0, 5, 0, 5),
						WidthRequest = App.screenWidth * 102 / 100
					};

					BoxView paddingBoxView = new BoxView();
					paddingBoxView.WidthRequest = App.screenWidth * 3 / 100;
					paddingBoxView.BackgroundColor = Color.Transparent;

					bottomAndLowerControllStack.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal , WidthRequest = App.screenWidth * 102 / 100, Children = { paddingBoxView, description } });

					#region MEDIA LIST

					if ( item.gem_media != null )
					{
						GemMedia gemMedia = (item.gem_media.Count > 0) ? item.gem_media[0] : null;
						if( gemMedia != null )
						{
							TapGestureRecognizer videoTap = new TapGestureRecognizer();
							videoTap.Tapped += OnGemTapped;

							IDownload downloader = DependencyService.Get<IDownload>();

							string fileName = Path.GetFileName( Constants.SERVICE_BASE_URL + gemMedia.gem_media ); 
							string localFilePath = Device.OnPlatform( downloader.GetLocalFileName( fileName ), App.DownloadsPath + fileName, "" );


							Image img = new Image();
							bool isValidUrl = (gemMedia.gem_media != null && !string.IsNullOrEmpty(gemMedia.gem_media)) ? true : false;
							string source = (isValidUrl) ?  localFilePath : null;
							string fileExtenstion = Path.GetExtension(source);
							bool isImage = (fileExtenstion == ".png" || fileExtenstion == ".jpg" || fileExtenstion == ".jpeg") ? true : false;
							img.WidthRequest = App.screenWidth * 102 / 100;// * 90 / 100;
							img.HeightRequest = App.screenWidth * 80 / 100;
							img.Aspect = Aspect.Fill;

							img.ClassId = null;
							if ( gemMedia.gem_media != null && gemMedia.media_type == "mp4")
							{
								img.ClassId = Constants.SERVICE_BASE_URL + gemMedia.gem_media ;
								source = Constants.SERVICE_BASE_URL + gemMedia.video_thumb;
							}
							else if ( gemMedia.gem_media != null && (gemMedia.media_type == "3gpp" || gemMedia.media_type == "aac" ))
							{
								img.ClassId = Constants.SERVICE_BASE_URL + gemMedia.gem_media;
								source = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
							}
							else if (gemMedia.gem_media != null && gemMedia.media_type == "wav")
							{
								img.ClassId = source;
								source = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
							}

							if( source != null )
							{
								img.Source = source;
								img.GestureRecognizers.Add(videoTap);
								var indicator = new ActivityIndicator { Color = new Color(.5), };
								indicator.SetBinding(ActivityIndicator.IsRunningProperty, "IsLoading");
								masterStack.AddChildToLayout(indicator, 45, 30);

							/*	CustomLayout imgContainer = new CustomLayout();
								imgContainer.WidthRequest = App.screenWidth * 90 / 100;
								imgContainer.HeightRequest = App.screenWidth * 90 / 100;
								imgContainer.Children.Add(img);
								if( item.gem_media != null && item.gem_media.Count > 1 )
									imgContainer.AddChildToLayout(moreImg, 75, 75, (int)imgContainer.WidthRequest, (int)imgContainer.HeightRequest);*/

								Grid grid = new Grid
								{
									WidthRequest = App.screenWidth * 102 / 100,
								//	HeightRequest = App.screenWidth * 80 / 100,
									VerticalOptions = LayoutOptions.FillAndExpand,
									HorizontalOptions = LayoutOptions.FillAndExpand,
									RowDefinitions = 
									{
										new RowDefinition { Height = new GridLength( img.HeightRequest / 3 ) },
										new RowDefinition { Height = new GridLength( img.HeightRequest / 3 ) },
										new RowDefinition { Height = new GridLength( img.HeightRequest / 3 ) },

									},
									ColumnDefinitions = 
									{
										new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },
										new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },
										new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },

									}
								};
								
								if ( gemMedia != null && gemMedia.media_type == "mp4")
								{

									Image play = new Image();
									play.Source = "video_play.png";
									play.Aspect = Aspect.AspectFit;
									play.WidthRequest = 75;
									play.HeightRequest = 75;
									play.HorizontalOptions = LayoutOptions.Center;
									play.VerticalOptions = LayoutOptions.Center;
									play.ClassId =  img.ClassId;
									play.GestureRecognizers.Add(videoTap);

									BoxView box = new BoxView();
									box.BackgroundColor = Color.Red;
									box.WidthRequest = 100;
									box.HeightRequest = 100;

									grid.Children.Add( img, 0, 0 );
									Grid.SetColumnSpan(img, 3);
									Grid.SetRowSpan( img, 3 );
									grid.Children.Add(play, 1, 1);
									if( item.gem_media.Count > 1 )
									grid.Children.Add(moreImg, 2, 2);
									bottomAndLowerControllStack.Children.Add(grid);
								}
								else
								{	
									grid.Children.Add( img, 0, 0 );
									Grid.SetColumnSpan(img, 3);
									Grid.SetRowSpan( img, 3 );
									if( item.gem_media.Count > 1 )
										grid.Children.Add(moreImg, 2, 2);
									bottomAndLowerControllStack.Children.Add(grid);
								}
							}

						}

					}

					#endregion


					bottomAndLowerControllStack.Children.Add(toolsLayout);
					masterStack.AddChildToLayout(bottomAndLowerControllStack, 0, 12);
					//  masterStack.AddChildToLayout( moreImg, 65, Device.OnPlatform( 30, 20, 20 ) );

					//masterStack.AddChildToLayout(spaceOffsetlayout, 1, 85);
					/// bottomAndLowerControllStack.Children.Add(spaceOffsetlayout);

	

					masterScroll.HeightRequest = App.screenHeight - 20;
					masterScroll.WidthRequest = App.screenWidth * 102 / 100;// * 90 / 100;


					masterStackLayout.Children.Add(masterStack);


				}


				if( prevButtonNeeded )
				{
					Button backToTop = new Button();
					backToTop.BackgroundColor = Color.Transparent;
					backToTop.TextColor = Constants.BLUE_BG_COLOR;
					backToTop.Text = "Go back to previous page";
					backToTop.FontSize = 12;
					backToTop.BorderWidth = 0;
					backToTop.BorderColor = Color.Transparent;
					backToTop.ClassId = "prev page";
					backToTop.Clicked += (object sender, EventArgs e) => 
					{
						OnLoadPreviousGemsClicked(  masterScroll, EventArgs.Empty );
					};
					masterStackLayout.Children.Add ( backToTop );
				}
				/*	Button loadMoreGems = new Button();
				loadMoreGems.BackgroundColor = Color.Transparent;
				loadMoreGems.TextColor = Constants.BLUE_BG_COLOR;
				loadMoreGems.Text = "Load more gems";
				loadMoreGems.FontSize = 12;
				loadMoreGems.BorderWidth = 0;
				loadMoreGems.BorderColor = Color.Transparent;
				loadMoreGems.Clicked += OnLoadMoreGemsClicked;*/

				BoxView transBox = new BoxView();
				transBox.HeightRequest = 125;
				transBox.WidthRequest = App.screenWidth * 80 / 100;
				transBox.BackgroundColor = Color.Transparent;
				//masterStackLayout.Children.Add(loadMoreGems);
				masterStackLayout.Children.Add(transBox);
				masterScroll.Content = masterStackLayout;
			}
			catch (Exception ex) 
			{
				
			}
		}
		public void Dispose()
		{
			this.eventPickerButton = null;
			this.eventPickerButton.Clicked -= OnEventPickerButtonClicked;
			this.emotionalPickerButton = null;
			this.emotionalPickerButton.Clicked -= OnEmotionalPickerButtonClicked;
			this.slider = null;
			this.masterLayout = null;
			this.progressBar = null;
			this.selectedEmotionItem = null;
			this.selectedEventItem = null;
			this.about = null;
			this.subTitleBar.NextButtonTapRecognizer.Tapped -= OnNextButtonTapRecognizerTapped;
			this.subTitleBar.BackButtonTapRecognizer.Tapped -= OnBackButtonTapRecognizerTapped;
			this.subTitleBar = null;
			this.Appearing -= OnFeelingNowPageAppearing;
			this.mainTitleBar = null;
			sliderValLabel = null;
			emotionTextLabel = null;
			eventTextLabel = null;
			imagesContainer = null;
			feedbackLabelStack = null;
			sliderFeedbackStack = null;
			feelingFeedbackStack = null;
			eventFeedbackStack = null;
			hLine = null;
			emotionTextTap = null;

			GC.Collect();
		}
		public SourceChooser(CustomLayout pageContainer, string type, ProfileSettingsPage parentObject)
		{
			CustomLayout masterLayout = new CustomLayout();
			masterLayout.BackgroundColor = Color.Transparent;
			//IDeviceSpec deviceSpec = DependencyService.Get<IDeviceSpec>();
			double screenWidth = App.screenWidth;
			double screenHeight = App.screenHeight;
			PageContainer = pageContainer;

			callerObject = parentObject;

			StackLayout layout = new StackLayout();
			layout.BackgroundColor = Color.Black;
			layout.Opacity = .6;
			layout.WidthRequest = screenWidth;
			layout.HeightRequest = screenHeight;

			TapGestureRecognizer emptyAreaTapGestureRecognizer = new TapGestureRecognizer();
			emptyAreaTapGestureRecognizer.Tapped += (s, e) =>
			{

				View pickView = PageContainer.Children.FirstOrDefault(pick => pick.ClassId == "mediachooser");
				PageContainer.Children.Remove(pickView);
				pickView = null;

			};
			layout.GestureRecognizers.Add(emptyAreaTapGestureRecognizer);

			CustomImageButton imageButton = new CustomImageButton();
			imageButton.ImageName = Device.OnPlatform("photoCamera_icon.png", "photoCamera_icon.png", @"/Assets/photoCamera_icon.png");
			imageButton.WidthRequest = screenWidth * 20 / 100;
			imageButton.HeightRequest = screenHeight * 10 / 100;
			imageButton.ClassId = type;
			imageButton.Clicked += OnImageButtonClicked;

			CustomImageButton selectFromGalleryButton = new CustomImageButton();
			selectFromGalleryButton.ImageName = Device.OnPlatform("image.png", "image.png", @"/Assets/image.png");
			selectFromGalleryButton.WidthRequest = screenWidth * 20 / 100;
			selectFromGalleryButton.HeightRequest = screenHeight * 10 / 100;
			selectFromGalleryButton.ClassId = type;
			selectFromGalleryButton.Clicked += SelectFromGalleryButtonClicked;

			masterLayout.AddChildToLayout(layout, 0, 0);
			masterLayout.AddChildToLayout(imageButton, 40, 40);
			masterLayout.AddChildToLayout(selectFromGalleryButton, 40, 60);

			this.BackgroundColor = Color.Transparent;



			Content = masterLayout;
		}
        public void Dispose()
        {
            subTitleBar.BackButtonTapRecognizer.Tapped -= OnBackButtonTapRecognizerTapped;
            subTitleBar.NextButtonTapRecognizer.Tapped -= NextButtonTapRecognizer_Tapped;
            masterLayout = null;
            this.TopTitleBar = null;
            this.subTitleBar = null;
            eventDescription = null;
            this.textInputContainer = null;
            this.audioInputStack = null;
            this.cameraInput = null;
            this.audioInput = null;
            this.cameraInputStack = null;
            this.galleryInput = null;
            this.galleryInputStack = null;
            this.locationInput = null;
            this.locationInputStack = null;
            this.contactInput = null;
            this.contactInputStack = null;
            this.textinputAndIconsHolder = null;
            this.audioRecorder = null;
            eventTitle = null;
            this.iconContainerGrid = null;
			this.locAndContactsEntry = null;
			this.editLocationAndContactsStack = null;
			this.editLocationDoneButton = null;
            GC.Collect();
        }
        public CustomEventView(CustomLayout containerLayout, int topY, string title, bool titelBarRequired, bool addButtonRequired)
        {
            pageContainedLayout = containerLayout;
            masterLayout = new CustomLayout();
            masterLayout.BackgroundColor = Color.Transparent;
            screenHeight = App.screenHeight;
            screenWidth = App.screenWidth;

            pageTitle = title;
            topYPos = topY;

            StackLayout layout = new StackLayout();
            layout.BackgroundColor = Color.Black;
            layout.Opacity = .4;
            layout.WidthRequest = screenWidth;
            layout.HeightRequest = screenHeight;

            TapGestureRecognizer emptyAreaTapGestureRecognizer = new TapGestureRecognizer();
            emptyAreaTapGestureRecognizer.Tapped += (s, e) =>
            {
                View pickView = pageContainedLayout.Children.FirstOrDefault(pick => pick.ClassId == "ePicker");
                pageContainedLayout.Children.Remove(pickView);
                pickView = null;

            };
            layout.GestureRecognizers.Add(emptyAreaTapGestureRecognizer);


            StackLayout listContainer = new StackLayout();
            listContainer.WidthRequest = screenWidth * 96 / 100;
            listContainer.HeightRequest = screenHeight * topY / 100;
            listContainer.Orientation = StackOrientation.Vertical;


            StackLayout listHeader = new StackLayout();
            listHeader.WidthRequest = screenWidth * 96 / 100;
            listHeader.HeightRequest = screenHeight * 10 / 100;
            listHeader.BackgroundColor = Color.FromRgb(30, 126, 210);

            listTitle = new Label();
            listTitle.Text = title;
            listTitle.TextColor = Color.White;
            listTitle.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            listTitle.FontSize = 17;


            startDatePickerButton = new PurposeColor.interfaces.CustomImageButton();
            startDatePickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", "//Assets//select_box_whitebg.png");
            if (App.SelectedActionStartDate != null && App.SelectedActionStartDate.Trim().Length > 0)
            {
                startDatePickerButton.Text = App.SelectedActionStartDate;
            }
            else
            {
                startDatePickerButton.Text = "Start Date";
            }
           
            startDatePickerButton.FontSize = 18;
            startDatePickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            startDatePickerButton.TextOrientation = interfaces.TextOrientation.Left;
            startDatePickerButton.TextColor = Color.Gray;
            startDatePickerButton.WidthRequest = screenWidth * 90 / 100;
            startDatePickerButton.HeightRequest = screenHeight * 8 / 100;
            startDatePickerButton.Clicked += startDatePickerButton_Clicked;

            endDatePickerButton = new PurposeColor.interfaces.CustomImageButton();
            endDatePickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", "//Assets//select_box_whitebg.png");
            if (App.SelectedActionStartDate != null && App.SelectedActionStartDate.Trim().Length > 0)
            {
                endDatePickerButton.Text = App.SelectedActionEndDate;
            }
            else
            {
                endDatePickerButton.Text = "End Date";
            }

            endDatePickerButton.FontSize = 18;
            endDatePickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            endDatePickerButton.TextOrientation = interfaces.TextOrientation.Left;
            endDatePickerButton.TextColor = Color.Gray;
            endDatePickerButton.WidthRequest = screenWidth * 90 / 100;
            endDatePickerButton.HeightRequest = screenHeight * 8 / 100;
            endDatePickerButton.Clicked += endDatePickerButton_Clicked;




            this.WidthRequest = screenWidth;
            this.HeightRequest = screenHeight;

            masterLayout.AddChildToLayout(layout, 0, 0);
          /*  if (titelBarRequired)
            {
                masterLayout.AddChildToLayout(listHeader, 2, (100 - topY - 1) - 10);
                masterLayout.AddChildToLayout(listTitle, 5, (100 - topY - 1) - 7);

            }*/

            listContainer.Children.Add(startDatePickerButton);
            listContainer.Children.Add(endDatePickerButton);
            masterLayout.AddChildToLayout(listContainer, 2, 100 - topY - 1);
            this.BackgroundColor = Color.Transparent;

            Content = masterLayout;
        }
        async void OnAppearing(object sender, EventArgs e)
        {

			if (!isFirstTime)
				return;

            // this.Animate("", (s) => Layout(new Rectangle(X, (1 - s) * Height, Width, Height)), 0, 1000, Easing.SpringIn, null, null); // slide up
        

			if (emotionsMasterList != null)
			{
				for (int index = 0; index < emotionsMasterList.event_details.Count; index++)
				{
					TapGestureRecognizer tap = new TapGestureRecognizer ();
					tap.Tapped += OnEmotionTapped;
					StackLayout cellMasterLayout = new StackLayout ();
					cellMasterLayout.Orientation = StackOrientation.Vertical;
					cellMasterLayout.BackgroundColor = Color.White;

					StackLayout headerLayout = new StackLayout ();
					headerLayout.Orientation = StackOrientation.Vertical;
					headerLayout.BackgroundColor = Color.FromRgb (244, 244, 244);

					CustomLayout customLayout = new CustomLayout ();
					customLayout.BackgroundColor = Color.FromRgb (244, 244, 244);
					double screenWidth = App.screenWidth;
					double screenHeight = App.screenHeight;
					customLayout.ClassId = emotionsMasterList.event_details [index].event_id;
					customLayout.GestureRecognizers.Add (  tap);

					CustomImageButton mainTitle = new CustomImageButton ();
					//  mainTitle.IsEnabled = false;
					mainTitle.BackgroundColor = Color.FromRgb (30, 126, 210);
					mainTitle.ImageName = Device.OnPlatform ("blue_bg.png", "blue_bg.png", @"/Assets/blue_bg.png");
					mainTitle.Text = "My Supporting Emotions";
					mainTitle.TextColor = Color.White;
					mainTitle.FontSize = Device.OnPlatform (12, 12, 18);
					mainTitle.WidthRequest = App.screenWidth;
					mainTitle.TextOrientation = TextOrientation.Middle;
					headerLayout.VerticalOptions = LayoutOptions.CenterAndExpand;
					mainTitle.HeightRequest = 80;


					Label subTitle = new Label ();
					subTitle.Text = (emotionsMasterList.event_title != null && emotionsMasterList.event_title.Count > 0) ? emotionsMasterList.event_title [index].event_title : "empty";
					subTitle.TextColor = Color.Gray;
					subTitle.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
					subTitle.XAlign = TextAlignment.Center;
					int subTitleFontSize = (App.screenDensity > 1.5) ? 18 : 16;
					subTitle.VerticalOptions = LayoutOptions.Center;
					subTitle.FontSize = Device.OnPlatform (subTitleFontSize, subTitleFontSize, 22);
					subTitle.WidthRequest = App.screenWidth * 90 / 100;
					headerLayout.HorizontalOptions = LayoutOptions.Center;
					subTitle.HeightRequest = Device.OnPlatform (40, 40, 30);
					subTitle.ClassId = emotionsMasterList.event_details [index].event_id;
					subTitle.GestureRecognizers.Add (  tap);


					Label firstDetailsInfo = new Label ();
					string trimmedFirstDetails = (emotionsMasterList.event_details != null && emotionsMasterList.event_details.Count > 0) ? emotionsMasterList.event_details [index].event_details : "empty";
					if (trimmedFirstDetails != null && trimmedFirstDetails.Length > 50) {
						trimmedFirstDetails = trimmedFirstDetails.Substring (0, 50);
						trimmedFirstDetails = trimmedFirstDetails + "....";
						trimmedFirstDetails = trimmedFirstDetails.Replace ("\\n", string.Empty);
						trimmedFirstDetails = trimmedFirstDetails.Replace ("\\r", string.Empty);
					}

  
					firstDetailsInfo.Text = trimmedFirstDetails;
					firstDetailsInfo.TextColor = Color.Gray;
					firstDetailsInfo.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
					firstDetailsInfo.WidthRequest = App.screenWidth * 60 / 100;
					firstDetailsInfo.HeightRequest = 40;
					firstDetailsInfo.ClassId = emotionsMasterList.event_details [index].event_id;
					firstDetailsInfo.GestureRecognizers.Add (  tap);
					int firstDetailsInfoFontSize = (App.screenDensity > 1.5) ? Device.OnPlatform (17, 16, 13) : 15;
					firstDetailsInfo.FontSize = Device.OnPlatform (firstDetailsInfoFontSize, firstDetailsInfoFontSize, firstDetailsInfoFontSize);


					Label firstDateInfo = new Label ();
					firstDateInfo.Text = (emotionsMasterList.event_datetime != null && emotionsMasterList.event_datetime.Count > 0) ? emotionsMasterList.event_datetime [index].event_datetime : "empty";
					//firstDateInfo.Text = "2015 Januvary 30";
					firstDateInfo.TextColor = Color.Black;
					firstDateInfo.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
					int dateFontSize = (App.screenDensity > 1.5) ? Device.OnPlatform (13, 15, 13) : 12;
					firstDateInfo.FontSize = Device.OnPlatform (dateFontSize, dateFontSize, dateFontSize);
					firstDateInfo.ClassId = emotionsMasterList.event_details [index].event_id;
					firstDateInfo.GestureRecognizers.Add (  tap);


					Image firstEmotionsImage = new Image ();
					firstEmotionsImage.WidthRequest = App.screenWidth * Device.OnPlatform (30, 28, 25) / 100;
					firstEmotionsImage.HeightRequest = App.screenWidth * Device.OnPlatform (25, 22, 18) / 100;

                    string eventID = emotionsMasterList.event_details[index].event_id;
                    List<EventMedia> firstThumbMedia = emotionsMasterList.event_media.FindAll(itm => itm.event_id == eventID).ToList();
                    bool firstImageValidity = (firstThumbMedia != null && firstThumbMedia.Count > 0 && !string.IsNullOrEmpty(firstThumbMedia[0].event_media)) ? true : false;
                    string firstImageSource = (firstImageValidity) ? Constants.SERVICE_BASE_URL + eventsMediaThumbPath + firstThumbMedia[0].event_media : Constants.SERVICE_BASE_URL + eventsNoMediaPath;
                    if (firstThumbMedia != null && firstThumbMedia[0].media_type == "mp4" )
                    {
                        firstImageSource = Device.OnPlatform("video.png", "video.png", "//Assets//video.png");
                    }
					else if (firstThumbMedia[0] != null && (firstThumbMedia[0].media_type == "3gpp" || firstThumbMedia[0].media_type == "aac" ) )
                    {
                        firstImageSource = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
                    }
                    else if (firstThumbMedia[0] != null && firstThumbMedia[0].media_type == "wav")
                    {
                        firstImageSource = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
                    }
                    firstEmotionsImage.Source = firstImageSource;
					firstEmotionsImage.ClassId = emotionsMasterList.event_details [index].event_id;
					firstEmotionsImage.GestureRecognizers.Add (  tap);
					firstEmotionsImage.Aspect = Aspect.Fill;
					//firstEmotionsImage.SetBinding(Image.SourceProperty, "FirstImage");


					customLayout.WidthRequest = screenWidth;
					customLayout.HeightRequest = 125;//screenHeight * Device.OnPlatform(30, 31, 7) / 100;


					StackLayout viewContainer = new StackLayout ();
					viewContainer.WidthRequest = App.screenWidth;
					viewContainer.HeightRequest = 100;//screenHeight * Device.OnPlatform(30, 27, 7) / 100;
					viewContainer.BackgroundColor = Color.White;

					Image divider = new Image ();
					divider.Source = "line_seperate.png";
					divider.BackgroundColor = Color.Transparent;
					divider.WidthRequest = App.screenWidth * 85 / 100;

					customLayout.AddChildToLayout (viewContainer, 0, Device.OnPlatform (-5, 0, 0));
					customLayout.AddChildToLayout (firstDetailsInfo, 5, Device.OnPlatform (-3, 2, 2));
					customLayout.AddChildToLayout (firstDateInfo, 5, Device.OnPlatform (4, 9, 6));
					customLayout.AddChildToLayout (firstEmotionsImage, Device.OnPlatform( 67, 65, 67 ), Device.OnPlatform (-3, 2, 1));

					masterStack.Children.Add (customLayout);
				}
				isFirstTime = false;
			} 
			else if (goalsMasterList != null) 
			{
				for (int index = 0; index < goalsMasterList.action_details.Count; index++)
				{
					TapGestureRecognizer tap = new TapGestureRecognizer ();
					tap.Tapped += OnGoalsTapped;;
					StackLayout cellMasterLayout = new StackLayout();
					cellMasterLayout.Orientation = StackOrientation.Vertical;
					cellMasterLayout.BackgroundColor = Color.White;

					StackLayout headerLayout = new StackLayout();
					headerLayout.Orientation = StackOrientation.Vertical;
					headerLayout.BackgroundColor = Color.FromRgb(244, 244, 244);

					CustomLayout customLayout = new CustomLayout();
					customLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
					double screenWidth = App.screenWidth;
					double screenHeight = App.screenHeight;
					customLayout.ClassId = goalsMasterList.action_details [index].goalaction_id;
					customLayout.GestureRecognizers.Add ( tap );


					CustomImageButton mainTitle = new CustomImageButton();
					//  mainTitle.IsEnabled = false;
					mainTitle.BackgroundColor = Color.FromRgb(30, 126, 210);
					mainTitle.ImageName = Device.OnPlatform("blue_bg.png", "blue_bg.png", @"/Assets/blue_bg.png");
					mainTitle.Text = "My Goals and Dreams";
					mainTitle.TextColor = Color.White;
					mainTitle.FontSize = Device.OnPlatform(12, 12, 18);
					mainTitle.WidthRequest = App.screenWidth;
					mainTitle.TextOrientation = TextOrientation.Middle;
					headerLayout.VerticalOptions = LayoutOptions.CenterAndExpand;
					mainTitle.HeightRequest = 80;


					Label subTitle = new Label();
					subTitle.Text = (goalsMasterList.action_title != null && goalsMasterList.action_title.Count > 0) ? goalsMasterList.action_title[index].action_title : "empty";
					subTitle.TextColor = Color.Gray;
					subTitle.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
					subTitle.XAlign = TextAlignment.Center;
					int subTitleFontSize = (App.screenDensity > 1.5) ? 18 : 16;
					subTitle.VerticalOptions = LayoutOptions.Center;
					subTitle.FontSize = Device.OnPlatform(subTitleFontSize, subTitleFontSize, 22);
					subTitle.WidthRequest = App.screenWidth * 90 / 100;
					headerLayout.HorizontalOptions = LayoutOptions.Center;
					subTitle.HeightRequest = Device.OnPlatform(40, 40, 30);

					Label firstDetailsInfo = new Label();
					string trimmedFirstDetails = (goalsMasterList.action_details != null &&goalsMasterList.action_details.Count > 0) ? goalsMasterList.action_details[index].action_details : "empty";
					if (trimmedFirstDetails != null && trimmedFirstDetails.Length > 50)
					{
						trimmedFirstDetails = trimmedFirstDetails.Substring(0, 50);
						trimmedFirstDetails = trimmedFirstDetails + "....";
						trimmedFirstDetails = trimmedFirstDetails.Replace("\\n", string.Empty);
						trimmedFirstDetails = trimmedFirstDetails.Replace("\\r", string.Empty);
					}
					firstDetailsInfo.Text = trimmedFirstDetails;
					firstDetailsInfo.TextColor = Color.Gray;
					firstDetailsInfo.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
					firstDetailsInfo.WidthRequest = App.screenWidth * 60 / 100;
					firstDetailsInfo.HeightRequest = 40;
					firstDetailsInfo.ClassId = goalsMasterList.action_details [index].goalaction_id;
					firstDetailsInfo.GestureRecognizers.Add ( tap );
					int firstDetailsInfoFontSize = (App.screenDensity > 1.5) ? Device.OnPlatform(17, 16, 13) : 15;
					firstDetailsInfo.FontSize = Device.OnPlatform(firstDetailsInfoFontSize, firstDetailsInfoFontSize, firstDetailsInfoFontSize);


					Label firstDateInfo = new Label();
					firstDateInfo.Text = (goalsMasterList.action_datetime != null && goalsMasterList.action_datetime.Count > 0) ? goalsMasterList.action_datetime[index].action_datetime : "empty";
					//firstDateInfo.Text = "2015 Januvary 30";
					firstDateInfo.TextColor = Color.Black;
					firstDateInfo.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
					firstDateInfo.ClassId = goalsMasterList.action_details [index].goalaction_id;
					firstDateInfo.GestureRecognizers.Add ( tap );
					int dateFontSize = (App.screenDensity > 1.5) ? Device.OnPlatform(13, 15, 13) : 12;
					firstDateInfo.FontSize = Device.OnPlatform(dateFontSize, dateFontSize, dateFontSize);


					Image firstEmotionsImage = new Image();
					firstEmotionsImage.WidthRequest = App.screenWidth * Device.OnPlatform (30, 28, 25) / 100;
					firstEmotionsImage.HeightRequest = App.screenWidth * Device.OnPlatform (25, 22, 18) / 100;
					firstEmotionsImage.ClassId = goalsMasterList.action_details [index].goalaction_id;
                    string actionID = goalsMasterList.action_details[index].goalaction_id;
                    List<ActionMedia> FirstThumbMedia = goalsMasterList.action_media.FindAll(itm => itm.goalaction_id == actionID).ToList();
					firstEmotionsImage.GestureRecognizers.Add ( tap );
                    bool firstImageValidity = (FirstThumbMedia != null && FirstThumbMedia.Count > 0 && !string.IsNullOrEmpty(FirstThumbMedia[0].action_media)) ? true : false;
                    string firstImageSource = (firstImageValidity) ? Constants.SERVICE_BASE_URL + goalsMediaThumbPath + FirstThumbMedia[0].action_media : Constants.SERVICE_BASE_URL + goalsNoMediaPath;
                    if ( FirstThumbMedia!= null && FirstThumbMedia[0].media_type == "mp4")
                    {
                        firstImageSource = Device.OnPlatform("video.png", "video.png", "//Assets//video.png");
                    }
					else if (FirstThumbMedia[0].media_type == "3gpp" || FirstThumbMedia[0].media_type == "aac")
                    {
                        firstImageSource = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
                    }
                    else if (FirstThumbMedia[0].media_type == "wav")
                    {
                        firstImageSource = Device.OnPlatform("audio.png", "audio.png", "//Assets//audio.png");
                    }
					firstEmotionsImage.Source = Device.OnPlatform(firstImageSource, firstImageSource, firstImageSource);
					//firstEmotionsImage.SetBinding(Image.SourceProperty, "FirstImage");


					customLayout.WidthRequest = screenWidth;
					customLayout.HeightRequest = 125;//screenHeight * Device.OnPlatform(30, 31, 7) / 100;


					StackLayout viewContainer = new StackLayout();
					viewContainer.WidthRequest = App.screenWidth;
					viewContainer.HeightRequest = 100;//screenHeight * Device.OnPlatform(30, 27, 7) / 100;
					viewContainer.BackgroundColor = Color.White;

					Image divider = new Image();
					divider.Source = "line_seperate.png";
					divider.BackgroundColor = Color.Transparent;
					divider.WidthRequest = App.screenWidth * 85 / 100;

					customLayout.AddChildToLayout(viewContainer, 0, Device.OnPlatform(-5, 0, 0));
					customLayout.AddChildToLayout(firstDetailsInfo, 5, Device.OnPlatform(-3, 2, 2));
					customLayout.AddChildToLayout(firstDateInfo, 5, Device.OnPlatform(4, 9, 6));
                    customLayout.AddChildToLayout(firstEmotionsImage, Device.OnPlatform(67, 65, 67), Device.OnPlatform(-3, 2, 1));

					masterStack.Children.Add(customLayout);
				}

				isFirstTime = false;
			}

            if (Device.OS == TargetPlatform.WinPhone)
            {
                StackLayout spaceOffsetlayout = new StackLayout();
                spaceOffsetlayout.WidthRequest = App.screenWidth * 50 / 100;
                spaceOffsetlayout.HeightRequest = Device.OnPlatform(0, 0, 100);
                spaceOffsetlayout.BackgroundColor = Color.Transparent;
                masterStack.Children.Add(spaceOffsetlayout);
            }
           
        }
 public void Dispose()
 {
     masterLayout = null;
     BackButtonTapRecognizer = null;
     NextButton = null;
     title = null;
     GC.Collect();
 }
        public CreateEventPage()
        {
            NavigationPage.SetHasNavigationBar(this, false);
            masterLayout = new CustomLayout();
            masterLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
            deviceSpec = DependencyService.Get<IDeviceSpec>();

			PurposeColorTitleBar mainTitleBar = new PurposeColorTitleBar(Color.FromRgb(8, 135, 224), "Purpose Color", Color.Black, "back", true);
            mainTitleBar.imageAreaTapGestureRecognizer.Tapped += imageAreaTapGestureRecognizer_Tapped;
            PurposeColorSubTitleBar subTitleBar = new PurposeColorSubTitleBar(Constants.SUB_TITLE_BG_COLOR, "Create Reminder", false, true);
            subTitleBar.BackButtonTapRecognizer.Tapped += BackButtonTapRecognizer_Tapped;

			CustomImageButton startDatePickerButton = new CustomImageButton();
			CustomImageButton startTimePickerButton = new CustomImageButton();
			CustomImageButton endDatePickerButton = new CustomImageButton();
			CustomImageButton endTimePickerButton = new CustomImageButton();


            CustomEntry title = new CustomEntry();
			title.WidthRequest = deviceSpec.ScreenWidth * 90 / 100;
			title.Placeholder = " Title";
			title.TextColor = Color.Black;
			title.BackgroundColor = Color.White;


            CustomEntry messege = new CustomEntry();
			messege.WidthRequest = deviceSpec.ScreenWidth * 90 / 100;
			messege.Placeholder = " Description";
			messege.TextColor = Color.Black;
			messege.BackgroundColor = Color.White;


			DatePicker startDatePicker = new DatePicker();
			startDatePicker.WidthRequest = 0;
			startDatePicker.HeightRequest = 0;
			startDatePicker.IsVisible = false;
			startDatePicker.DateSelected += (object sender, DateChangedEventArgs e) => 
			{
				
				startDatePickerButton.Text = startDatePicker.Date.ToString("dd/MM/yyyy");
			};

			DatePicker endDatePicker = new DatePicker();
			endDatePicker.WidthRequest = 0;
			endDatePicker.HeightRequest = 0;
			endDatePicker.IsVisible = false;
			endDatePicker.DateSelected += (object sender, DateChangedEventArgs e) => 
			{
				endDatePickerButton.Text = endDatePicker.Date.ToString("dd/MM/yyyy");
			};

			TimePicker startTimePicker = new TimePicker();
			startTimePicker.WidthRequest = 0;
			startTimePicker.HeightRequest = 0;
			startTimePicker.IsVisible = false;
			startTimePicker.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) => 
			{
                try
                {

                    if ("Time" == e.PropertyName)
                    {
                        //	string tie = startTimePicker.Time.ToString("hh:mm tt");
                        string amPM = (startTimePicker.Time.Hours > 12) ? "PM" : "AM";
                        startTimePickerButton.Text = startTimePicker.Time.ToString(); //startTimePicker.Time.Hours.ToString () + " : " + startTimePicker.Time.Minutes.ToString() + "  " + amPM;

                    }

                }
                catch (Exception ex)
                {
                    var test = ex.Message;
                }
			};


			TimePicker endTimePicker = new TimePicker();
			endTimePicker.WidthRequest = 0;
			endTimePicker.HeightRequest = 0;
			endTimePicker.IsVisible = false;
			endTimePicker.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) => 
			{
                try
                {
                    if ("Time" == e.PropertyName)
                    {
                        string amPM = (endTimePicker.Time.Hours > 12) ? "PM" : "AM";
                        endTimePickerButton.Text = endTimePicker.Time.ToString();// endTimePicker.Time.Hours.ToString () + " : " + endTimePicker.Time.Minutes.ToString() + "  " + amPM;
                    }
                }
                catch (Exception ex)
                {
                    var test = ex.Message;
                }
			};

            //startDatePickerButton = new CustomImageButton();
            startDatePickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", "//Assets//select_box_whitebg.png");
            startDatePickerButton.Text = "Start Date";
            startDatePickerButton.FontSize = 17;
            startDatePickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            startDatePickerButton.TextOrientation = interfaces.TextOrientation.Left;
            startDatePickerButton.TextColor = Color.Gray;
            startDatePickerButton.WidthRequest = deviceSpec.ScreenWidth * 40 / 100;
			startDatePickerButton.Clicked += (object sender, EventArgs e) => 
			{
                try
                {
					startDatePicker.Date = DateTime.Now.AddDays(1);
                    startDatePicker.Focus();
                }
                catch (Exception ex)
                {
                    var test = ex.Message;
                }
			};



           // startTimePickerButton = new CustomImageButton();
            startTimePickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", "//Assets//select_box_whitebg.png");
            startTimePickerButton.Text = " Start Time";
            startTimePickerButton.TextOrientation = TextOrientation.Middle;         
            startTimePickerButton.FontSize = 17;
            startTimePickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
            startTimePickerButton.TextOrientation = interfaces.TextOrientation.Left;
            startTimePickerButton.TextColor = Color.Gray;
            startTimePickerButton.WidthRequest = deviceSpec.ScreenWidth * 40 / 100;
			startTimePickerButton.Clicked += (object sender, EventArgs e) => 
			{
                try
                {
                    startTimePicker.Time = new TimeSpan(12, 00, 00);
                    startTimePicker.Focus();
                }
                catch (Exception ex)
                {
                    var test = ex.Message;
                }
			};
		
		
		   // endDatePickerButton = new CustomImageButton();
            endDatePickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", "//Assets//select_box_whitebg.png");
			endDatePickerButton.Text = "End Date";
			endDatePickerButton.FontSize = 17;
			endDatePickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			endDatePickerButton.TextOrientation = interfaces.TextOrientation.Left;
			endDatePickerButton.TextColor = Color.Gray;
			endDatePickerButton.WidthRequest = deviceSpec.ScreenWidth * 40 / 100;
			endDatePickerButton.Clicked += (object sender, EventArgs e) => 	
			{
                try
                {
					endDatePicker.Date = DateTime.Now.AddDays(1);
                    endDatePicker.Focus();
                }
                catch (Exception ex)
                {
                    var test = ex.Message;
                }
			};


		   // endTimePickerButton = new CustomImageButton();
            endTimePickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", "//Assets//select_box_whitebg.png");
			endTimePickerButton.Text = " End Time";
			endTimePickerButton.FontSize = 17;
			endTimePickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			endTimePickerButton.TextOrientation = interfaces.TextOrientation.Left;
			endTimePickerButton.TextColor = Color.Gray;
			endTimePickerButton.WidthRequest = deviceSpec.ScreenWidth * 40 / 100;
			endTimePickerButton.Clicked += (object sender, EventArgs e) => 	
			{
                try
                {
                    endTimePicker.Time = new TimeSpan(12, 00, 00);
                    endTimePicker.Focus();
                }
                catch (Exception ex)
                {
                    var test = ex.Message;
                }
			};

			CustomImageButton reminderPickerButton = new CustomImageButton ();
			Picker reminderPicker = new Picker ();
			reminderPicker.Items.Add ("15");
			reminderPicker.Items.Add ("30");
			reminderPicker.Items.Add ("45");
			reminderPicker.Items.Add ("60");
			reminderPicker.WidthRequest = 0;
			reminderPicker.HeightRequest = 0;
			reminderPicker.SelectedIndexChanged += (object sender, EventArgs e) => 
			{
				reminderPickerButton.Text = reminderPicker.Items[reminderPicker.SelectedIndex];
			};


            reminderPickerButton.ImageName = Device.OnPlatform("select_box_whitebg.png", "select_box_whitebg.png", "//Assets//select_box_whitebg.png");
			reminderPickerButton.Text = " Reminder";
			reminderPickerButton.TextOrientation = TextOrientation.Middle;         
			reminderPickerButton.FontSize = 17;
			reminderPickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			reminderPickerButton.TextOrientation = interfaces.TextOrientation.Left;
			reminderPickerButton.TextColor = Color.Gray;
			reminderPickerButton.WidthRequest = deviceSpec.ScreenWidth * 90 / 100;
			reminderPickerButton.Clicked += (object sender, EventArgs e) => 
			{
				reminderPicker.Focus();
			};

			Button createReminderButton = new Button ();
			createReminderButton.Text = "Create Reminder";
			createReminderButton.TextColor = Color.White;
			createReminderButton.BackgroundColor = Color.FromRgb( 30, 126, 210 );
			createReminderButton.WidthRequest = deviceSpec.ScreenWidth * 90 / 100;
			createReminderButton.Clicked += async (object sender, EventArgs e) =>
			{
                try
                {

                    App.CalPage = this;
                    if (startDatePickerButton.Text == "Start Date" || endDatePickerButton.Text == "End Date")
                    {
                        await DisplayAlert(Constants.ALERT_TITLE, "Please select start date and end date to proceed", Constants.ALERT_OK);
                        return;
                    }
                    IReminderService reminder = DependencyService.Get<IReminderService>();

                    if (Device.OS == TargetPlatform.iOS)
                    {
                        var access = await reminder.RequestAccessAsync();
                        if (!access)
                            return;
                    }

                    int reminderValue = 0;
                    if (reminderPickerButton.Text != null && reminderPickerButton.Text.Length > 0 && reminderPicker.SelectedIndex >= 0)
                    {
                        reminderValue = Convert.ToInt32(reminderPickerButton.Text);
                    }

                    DateTime startDateAndTime = new DateTime(startDatePicker.Date.Year, startDatePicker.Date.Month, startDatePicker.Date.Day, startTimePicker.Time.Hours, startTimePicker.Time.Minutes, 0);
                    DateTime endDateAndTime = new DateTime(endDatePicker.Date.Year, endDatePicker.Date.Month, endDatePicker.Date.Day, endTimePicker.Time.Hours, endTimePicker.Time.Minutes, 0);

                    // add this to app datetime fields to serve to api.
                    App.SelectedActionStartDate = startDateAndTime.ToString(); //to be converted into UTC
                    App.SelectedActionEndDate = endDateAndTime.ToString(); //to be converted into UTC
                    App.SelectedActionReminderValue = reminderValue;
                    if (!reminder.Remind(startDateAndTime, endDateAndTime, title.Text, messege.Text, reminderValue))
                    {
                        await DisplayAlert("Purpose Color", "Error in creating calendar event", Constants.ALERT_OK);
                    }
                    else
                    {
                        IProgressBar progress = DependencyService.Get<IProgressBar>();
                        progress.ShowToast("Calander event created");
                        if (Device.OS != TargetPlatform.iOS)
                        { //Navigation.PopAsync(); 
                            await Navigation.PopModalAsync();
                        }

                    }

                }
                catch (Exception ex)
                {
                    var test = ex.Message;
                }
			};

            masterLayout.AddChildToLayout(mainTitleBar, 0, 0);
            masterLayout.AddChildToLayout(subTitleBar, 0, Device.OnPlatform(9, 10, 10));

			masterLayout.AddChildToLayout(startDatePicker, 0, 0);
            masterLayout.AddChildToLayout(startTimePicker, 0, 0);
			masterLayout.AddChildToLayout(endDatePicker, 0, 0);
			masterLayout.AddChildToLayout(endTimePicker, 0, 0);
			masterLayout.AddChildToLayout(reminderPicker, 0, 0);

			masterLayout.AddChildToLayout (title, 5, 20);
			masterLayout.AddChildToLayout(messege, 5, 30);
			masterLayout.AddChildToLayout(startDatePickerButton, 5, 40);
			masterLayout.AddChildToLayout(startTimePickerButton, 55, 40);
			masterLayout.AddChildToLayout(endDatePickerButton, 5, 50);
			masterLayout.AddChildToLayout(endTimePickerButton, 55, 50);
			masterLayout.AddChildToLayout(reminderPickerButton, 5, 70);
			masterLayout.AddChildToLayout(createReminderButton, 5, 80);
            Content = masterLayout;
        }
        public MediaSourceChooser(AddEventsSituationsOrThoughts masterObject, CustomLayout pageContainer, string type)
        {

            MasterObject = masterObject;
            CustomLayout masterLayout = new CustomLayout();
            masterLayout.BackgroundColor = Color.Transparent;
            //IDeviceSpec deviceSpec = DependencyService.Get<IDeviceSpec>();
            double screenWidth = App.screenWidth;
            double screenHeight = App.screenHeight;
            PageContainer = pageContainer;

            StackLayout layout = new StackLayout();
            layout.BackgroundColor = Color.Black;
            layout.Opacity = .6;
            layout.WidthRequest = screenWidth;
            layout.HeightRequest = screenHeight;

            TapGestureRecognizer emptyAreaTapGestureRecognizer = new TapGestureRecognizer();
            emptyAreaTapGestureRecognizer.Tapped += (s, e) =>
            {

                View pickView = PageContainer.Children.FirstOrDefault(pick => pick.ClassId == "mediachooser");
                PageContainer.Children.Remove(pickView);
                pickView = null;

            };
            layout.GestureRecognizers.Add(emptyAreaTapGestureRecognizer);

            CustomImageButton imageButton = new CustomImageButton();
            imageButton.ImageName = Device.OnPlatform("image.png", "image.png", @"/Assets/image.png");
            imageButton.WidthRequest = screenWidth * 20 / 100;
            imageButton.HeightRequest = screenHeight * 10 / 100;
            imageButton.ClassId = type;
            imageButton.Clicked += OnImageButtonClicked;

            CustomImageButton videoButton = new CustomImageButton();
            videoButton.ImageName = Device.OnPlatform("video.png", "video.png", @"/Assets/video.png");
            videoButton.WidthRequest = screenWidth * 20 / 100;
            videoButton.HeightRequest = screenHeight * 10 / 100;
            videoButton.ClassId = type;
            videoButton.Clicked += OnVideoButtonClicked;

            masterLayout.AddChildToLayout(layout, 0, 0);
            masterLayout.AddChildToLayout(imageButton, 40, 40);
            masterLayout.AddChildToLayout(videoButton, 40, 60);

            this.BackgroundColor = Color.Transparent;



            Content = masterLayout;
        }
        public AddEventsSituationsOrThoughts(string title, DetailsPageModel detailsPageModel = null)
        {
            NavigationPage.SetHasNavigationBar(this, false);
            masterLayout = new CustomLayout();
            audioRecorder = DependencyService.Get<PurposeColor.interfaces.IAudioRecorder>();
            //deviceSpec = DependencyService.Get<IDeviceSpec>();
            screenHeight = App.screenHeight;
            screenWidth = App.screenWidth;

            masterLayout.BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY;
            pageTitle = title;
            lattitude = string.Empty;
            longitude = string.Empty;
            currentAddress = string.Empty;
            int devWidth = (int)screenWidth;
            App.MediaArray = new List<MediaItem>();
            App.ContactsArray = new List<string>();
            App.PreviewListSource.Clear();
            int textInputWidth = (int)(devWidth * .80);
			contactSelectAction = OnContactSelected;

            #region TITLE BARS
            TopTitleBar = new StackLayout
            {
                BackgroundColor = Constants.BLUE_BG_COLOR,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                VerticalOptions = LayoutOptions.StartAndExpand,
                Padding = 0,
                Spacing = 0,
                Children = { new BoxView { WidthRequest = screenWidth } }
            };
            masterLayout.AddChildToLayout(TopTitleBar, 0, 0);
            
            string trimmedPageTitle = string.Empty;

            int titleMaxLength = 24;
            if (App.screenDensity > 1.5)
            {
                titleMaxLength = 24;
            }
            else
            {
                titleMaxLength = 22;
            }

            if (title.Length > titleMaxLength)
            {
                trimmedPageTitle = title.Substring(0, titleMaxLength);
                trimmedPageTitle += "..";
            }
            else
            {
                trimmedPageTitle = pageTitle;
            }

            subTitleBar = new PurposeColorBlueSubTitleBar(Constants.SUB_TITLE_BG_COLOR, trimmedPageTitle, true, true);
            masterLayout.AddChildToLayout(subTitleBar, 0, 1);
            subTitleBar.BackButtonTapRecognizer.Tapped += OnBackButtonTapRecognizerTapped;
            subTitleBar.NextButtonTapRecognizer.Tapped += NextButtonTapRecognizer_Tapped;
            #endregion

            #region EVENT TITLE - CUSTOM ENTRY

            eventTitle = new CustomEntry
            {
                VerticalOptions = LayoutOptions.StartAndExpand,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                BackgroundColor = Color.White,
                Placeholder = "Title",
                TextColor = Color.FromHex("#424646"),
                HeightRequest = Device.OnPlatform(50,50,73),
                WidthRequest = (int)(devWidth * .90) // 90% of screen,
            };
			eventTitle.TextChanged += EventTitle_TextChanged;

            
            //if (App.screenDensity > 1.5)
            //{
            //    eventTitle.HeightRequest = screenHeight * 6 / 100;
            //}
            //else
            //{
            //    eventTitle.HeightRequest = screenHeight * 9 / 100;
            //}
            masterLayout.AddChildToLayout(eventTitle, 5, 11);

            #endregion

            #region EVENT DESCRIPTION

            eventDescription = new CustomEditor
            {
                VerticalOptions = LayoutOptions.StartAndExpand,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                HeightRequest = 100,
                Placeholder = pageTitle,
                BackgroundColor = Color.White
            };
			eventDescription.TextChanged += EventDescription_TextChanged;
				

            eventDescription.WidthRequest = textInputWidth;

            if (detailsPageModel != null)
            {
				if (detailsPageModel.IsCopyingGem) {
					isUpdatePage = false;
				}
				else
				{
					isUpdatePage = true;
				}

                currentGemId = detailsPageModel.gemId;
                if (detailsPageModel.gemType != null)
                {
                    currentGemType = detailsPageModel.gemType;
                    switch (currentGemType)
                    {
                        case GemType.Goal:
                            pageTitle = Constants.EDIT_GOALS;
                            break;
                        case GemType.Event:
                            pageTitle = Constants.EDIT_EVENTS;
                            break;
                        case GemType.Action:
                            pageTitle = Constants.EDIT_ACTIONS;
                            break;
                        default:
                            break;
                    }
                }
                
                if (detailsPageModel.titleVal != null)
                {
                    eventTitle.Text = detailsPageModel.titleVal;
                }
                if ( detailsPageModel.description != null)
	            {
		             eventDescription.Text = detailsPageModel.description;
	            }
            }

            #endregion

            #region MEDIA INPUTS

            Image pinButton = new Image
            {
                BackgroundColor = Color.Transparent,
                VerticalOptions = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.Center,
                Source = Device.OnPlatform("icn_attach.png", "icn_attach.png", "//Assets//icn_attach.png"),

            };
            StackLayout pinButtonHolder = new StackLayout
            {
                Padding = 10,
                VerticalOptions = LayoutOptions.Start,
                Children = { pinButton }
            };
            TapGestureRecognizer pinButtonTapRecognizer = new TapGestureRecognizer();
            pinButtonHolder.GestureRecognizers.Add(pinButtonTapRecognizer);
            pinButtonTapRecognizer.Tapped += (s, e) =>
            {
                iconContainerGrid.IsVisible = !iconContainerGrid.IsVisible;
            };

            Image audioRecodeOnButton = new Image
            {
                BackgroundColor = Color.Transparent,
                VerticalOptions = LayoutOptions.Center,
                Source = Device.OnPlatform("mic.png", "mic.png", "//Assets//mic.png"),
            };
            audioRecodeOnHolder = new StackLayout
            {
                Padding = 10,
                VerticalOptions = LayoutOptions.End,
                Children = { audioRecodeOnButton }
            };
            TapGestureRecognizer RecodeOnTapRecognizer = new TapGestureRecognizer();
            audioRecodeOnHolder.GestureRecognizers.Add(RecodeOnTapRecognizer);

            audioRecodeOffButton = new Image
            {
                BackgroundColor = Color.Transparent,
                VerticalOptions = LayoutOptions.Center,
                Source = Device.OnPlatform("turn_off_mic.png", "turn_off_mic.png", "//Assets//turn_off_mic.png"),
            };
            audioRecodeOffHolder = new StackLayout
            {
                BackgroundColor = Color.Transparent,
                Padding = 10,
                VerticalOptions = LayoutOptions.End,
                IsVisible = false,
                Children = { audioRecodeOffButton }
            };
            TapGestureRecognizer RecodeOffTapRecognizer = new TapGestureRecognizer();
            audioRecodeOffHolder.GestureRecognizers.Add(RecodeOffTapRecognizer);

            audioRecodeOffHolder.TranslateTo(0, Device.OnPlatform(audioRecodeOffButton.Y + 60, audioRecodeOffButton.Y + 60, audioRecodeOffButton.Y + 50), 5, null);
            audioRecodeOnHolder.TranslateTo(0, Device.OnPlatform(audioRecodeOffButton.Y + 60, audioRecodeOffButton.Y + 60, audioRecodeOffButton.Y + 50), 5, null);

            RecodeOnTapRecognizer.Tapped += RecodeOnTapRecognizer_Tapped;
            RecodeOffTapRecognizer.Tapped += RecodeOffTapRecognizer_Tapped;

            StackLayout menuPinContainer = new StackLayout
            {
                BackgroundColor = Color.White,
                Orientation = StackOrientation.Vertical,
                HeightRequest = 140,
                WidthRequest = (int)(devWidth * .10),
                Children = {
                    pinButtonHolder, 
                    audioRecodeOnHolder, 
                    audioRecodeOffHolder
                }
            };


            TapGestureRecognizer locationlabelTap = new TapGestureRecognizer();

            locationInfo = new Label();
            locationInfo.TextColor = Constants.BLUE_BG_COLOR;
            locationInfo.BackgroundColor = Color.Transparent;
            locationInfo.FontSize = 12;
            locationInfo.HeightRequest = Device.OnPlatform(15, 25, 25);
            locationInfo.GestureRecognizers.Add(locationlabelTap);
            locationlabelTap.Tapped += OnEditLocationInfo;

            editLocationAndContactsStack = new StackLayout();
            editLocationAndContactsStack.Padding = new Thickness(1, 1, 1, 1);
            editLocationAndContactsStack.BackgroundColor = Color.FromRgb(30, 126, 210);
            editLocationAndContactsStack.WidthRequest = App.screenWidth * 90 / 100;
            editLocationAndContactsStack.IsVisible = false;
            editLocationAndContactsStack.Orientation = StackOrientation.Horizontal;


            locAndContactsEntry = new Entry();
            locAndContactsEntry.TextColor = Color.Black;
            locAndContactsEntry.BackgroundColor = Color.White;
            locAndContactsEntry.VerticalOptions = LayoutOptions.Center;
            locAndContactsEntry.WidthRequest = App.screenWidth * 80 / 100;
            locAndContactsEntry.HeightRequest = 50;

            editLocationDoneButton = new CustomImageButton();
            editLocationDoneButton.VerticalOptions = LayoutOptions.Center;
            editLocationDoneButton.ImageName = "icn_done.png";
            editLocationDoneButton.HeightRequest = 25;
            editLocationDoneButton.WidthRequest = 25;
            editLocationDoneButton.Clicked += OnLocationEditCompleted;


            editLocationAndContactsStack.Children.Add(locAndContactsEntry);
            editLocationAndContactsStack.Children.Add(editLocationDoneButton);

            if (Device.OS == TargetPlatform.iOS)
            {
                editLocationAndContactsStack.TranslationY = -30;
            }

            locLayout = new StackLayout();
            locLayout.Orientation = StackOrientation.Vertical;
            locLayout.BackgroundColor = Color.Transparent;



            locLayout.Children.Add(locationInfo);

            TapGestureRecognizer contactsLabelTap = new TapGestureRecognizer();
            contactInfo = new Label();
            contactInfo.TextColor = Constants.BLUE_BG_COLOR;
            contactInfo.BackgroundColor = Color.Transparent;
            contactInfo.FontSize = 12;
            contactInfo.HeightRequest = Device.OnPlatform(15, 25, 25);
            contactInfo.GestureRecognizers.Add(contactsLabelTap);
            contactsLabelTap.Tapped += async (object sender, EventArgs e) =>
            {
                editLocationAndContactsStack.ClassId = "contactedit";
                string spanContacts = "";
                if (contactInfo.FormattedText != null && contactInfo.FormattedText.Spans.Count > 1)
                    spanContacts = contactInfo.FormattedText.Spans[1].Text;
                locAndContactsEntry.Text = spanContacts;
                editLocationAndContactsStack.IsVisible = true;
                contactInfo.IsVisible = false;
                iconContainerGrid.IsVisible = false;
                locationInfo.IsVisible = true;

                await editLocationAndContactsStack.TranslateTo(100, 0, 300, Easing.SinInOut);
                await editLocationAndContactsStack.TranslateTo(0, 0, 300, Easing.SinIn);

            };

            locLayout.IsVisible = false;
            contactInfo.IsVisible = false;
            
            #endregion

            if(detailsPageModel != null)
            {
                if (detailsPageModel.eventMediaArray!= null && detailsPageModel.eventMediaArray.Count > 0)
                {
                    foreach (EventMedia eventObj in detailsPageModel.eventMediaArray)
                    {
						if (eventObj.event_media != null && !eventObj.event_media.Contains("default")) {
							AddFilenameToMediaList(eventObj.event_media);
						}
                    }
                }

                if (detailsPageModel.goal_media != null && detailsPageModel.goal_media.Count > 0)
                {
                    foreach (SelectedGoalMedia goalObj in detailsPageModel.goal_media)
                    {
						if (goalObj.goal_media != null && !goalObj.goal_media.Contains("default")) {
							AddFilenameToMediaList(goalObj.goal_media);
						}
                    }
                }

                if (detailsPageModel.actionMediaArray != null && detailsPageModel.actionMediaArray.Count > 0)
                {
                    foreach (ActionMedia actionObj in detailsPageModel.actionMediaArray)
                    {
						if (actionObj.action_media != null && !actionObj.action_media.Contains("default")) {
							AddFilenameToMediaList(actionObj.action_media);
						}
                    }
                }

            }



            StackLayout entryAndLocContainer = new StackLayout();
            entryAndLocContainer.Orientation = StackOrientation.Vertical;
            entryAndLocContainer.BackgroundColor = Color.White;
            entryAndLocContainer.Children.Add( eventDescription );
			entryAndLocContainer.Children.Add(contactInfo);
            entryAndLocContainer.Children.Add(locLayout);

            textInputContainer = new StackLayout
            {
                Orientation = StackOrientation.Horizontal,
                Spacing = 0,
                Padding = 0,
                Children = { entryAndLocContainer, menuPinContainer }
            };

            #region ICONS

            audioInput = new Image()
            {
                Source = Device.OnPlatform("ic_music.png", "ic_music.png", "//Assets//ic_music.png"),
                Aspect = Aspect.AspectFit
            };

            int ICON_SIZE = 8;

            if( Device.OS == TargetPlatform.WinPhone )
            {
                audioInput.WidthRequest = screenWidth * ICON_SIZE / 100;
                audioInput.HeightRequest = screenWidth * ICON_SIZE / 100;
            }
            audioInputStack = new StackLayout
            {
                Padding = new Thickness(5, 10, 5, 10),
                //BackgroundColor = Constants.STACK_BG_COLOR_GRAY,
                //HorizontalOptions = LayoutOptions.Center,
                Spacing = 0,
                Children = { audioInput 
                                /*, new Label { Text = "Audio", TextColor = Constants.TEXT_COLOR_GRAY, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) }*/ 
                           }
            };

            cameraInput = new Image()
            {
                Source = Device.OnPlatform("icn_camera.png", "icn_camera.png", "//Assets//icn_camera.png"),
                Aspect = Aspect.AspectFit
            };



            if (Device.OS == TargetPlatform.WinPhone)
            {
                cameraInput.WidthRequest = screenWidth * ICON_SIZE / 100;
                cameraInput.HeightRequest = screenWidth * ICON_SIZE / 100;
            }


            cameraInputStack = new StackLayout
            {
                Padding = new Thickness(5, 10, 5, 10),
                //BackgroundColor = Constants.STACK_BG_COLOR_GRAY,
                //HorizontalOptions = LayoutOptions.Center,
                Spacing = 0,
                Children = { cameraInput
                                /*, new Label { Text = "Camera", TextColor = Constants.TEXT_COLOR_GRAY, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) } 
                                 */
                            }
            };
            cameraInputStack.ClassId = "camera";

            #region CAMERA TAP RECOGNIZER
            CameraTapRecognizer = new TapGestureRecognizer();
            cameraInputStack.GestureRecognizers.Add(CameraTapRecognizer);
            CameraTapRecognizer.Tapped += async (s, e) =>
            {
                try
                {
					await ApplyAnimation( cameraInputStack );
                    StackLayout send = s as StackLayout;
                    MediaSourceChooser chooser = new MediaSourceChooser(this, masterLayout, send.ClassId);
                    chooser.ClassId = "mediachooser";
                    masterLayout.AddChildToLayout(chooser, 0, 0);
                   
                }
                catch (System.Exception ex)
                {
                    DisplayAlert("Camera", ex.Message + " Please try again later", "ok");
                }

                /*
                try
                {
                    StackLayout send = s as StackLayout;
                    MediaSourceChooser chooser = new MediaSourceChooser(this, masterLayout, send.ClassId);
                    chooser.ClassId = "mediachooser";
                    masterLayout.AddChildToLayout(chooser, 0, 0);
                }
                catch (System.Exception ex)
                {
                    DisplayAlert("Camera", ex.Message + " Please try again later", "ok");
                }
                */
            };

            #endregion

            galleryInput = new Image()
            {
                Source = Device.OnPlatform("icn_gallery.png", "icn_gallery.png", "//Assets//icn_gallery.png"),
                Aspect = Aspect.AspectFit
            };

            if (Device.OS == TargetPlatform.WinPhone)
            {
                galleryInput.WidthRequest = screenWidth * ICON_SIZE / 100;
                galleryInput.HeightRequest = screenWidth * ICON_SIZE / 100;
            }

            galleryInputStack = new StackLayout
            {
                Padding = new Thickness(5, 10, 5, 10),
                Spacing = 0,
                Children = { galleryInput 
                                //new Label { Text = "Gallery", TextColor = Constants.TEXT_COLOR_GRAY, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) } 
                            }
            };
            galleryInputStack.ClassId = "gallery";

            #region GALLERY  TAP RECOGNIZER

            TapGestureRecognizer galleryInputStackTapRecognizer = new TapGestureRecognizer();
            galleryInputStack.GestureRecognizers.Add(galleryInputStackTapRecognizer);
            galleryInputStackTapRecognizer.Tapped += async (s, e) =>
            {
				await ApplyAnimation( galleryInputStack );
                StackLayout send = s as StackLayout;
                MediaSourceChooser chooser = new MediaSourceChooser(this, masterLayout, send.ClassId);
                chooser.ClassId = "mediachooser";
                masterLayout.AddChildToLayout(chooser, 0, 0);

            };

            #endregion

            locationInput = new Image()
            {
                Source = Device.OnPlatform("icn_location.png", "icn_location.png", "//Assets//icn_location.png"),
                Aspect = Aspect.AspectFit
            };

            if (Device.OS == TargetPlatform.WinPhone)
            {
                locationInput.WidthRequest = screenWidth * ICON_SIZE / 100;
                locationInput.HeightRequest = screenWidth * ICON_SIZE / 100;
            }


            locationInputStack = new StackLayout
            {
                Padding = new Thickness(5, 10, 5, 10),
                //BackgroundColor = Constants.STACK_BG_COLOR_GRAY,
                //HorizontalOptions = LayoutOptions.Center,
                Spacing = 0,
                Children = { locationInput
                                //, new Label { Text = "Location", TextColor = Constants.TEXT_COLOR_GRAY, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) } 
                            }
            };

            #region LOCATION TAP RECOGNIZER

            TapGestureRecognizer locationInputTapRecognizer = new TapGestureRecognizer();
            locationInputStack.GestureRecognizers.Add(locationInputTapRecognizer);
            locationInputTapRecognizer.Tapped += LocationInputTapRecognizer_Tapped;

            #endregion

            contactInput = new Image()
            {
                Source = Device.OnPlatform("icn_contact.png", "icn_contact.png", "//Assets//icn_contact.png"),
                Aspect = Aspect.AspectFit
            };

            if (Device.OS == TargetPlatform.WinPhone)
            {
                contactInput.WidthRequest = screenWidth * ICON_SIZE / 100;
                contactInput.HeightRequest = screenWidth * ICON_SIZE / 100;
            }

            contactInputStack = new StackLayout
            {
                Padding = new Thickness(5, 10, 0, 10),
                Spacing = 0,
                Children = { contactInput
                    //new Label { Text = "Contact", TextColor = Constants.TEXT_COLOR_GRAY, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) }
                     }
            };

            #region CONTACTS TAP RECOGNIZER

            TapGestureRecognizer contactsInputTapRecognizer = new TapGestureRecognizer();
            contactInputStack.GestureRecognizers.Add(contactsInputTapRecognizer);

            contactsInputTapRecognizer.Tapped += async (s, e) =>
            {
				await ApplyAnimation( contactInputStack );

				try
				{
					if( Device.OS == TargetPlatform.Android  || Device.OS == TargetPlatform.iOS )
					{
						IContactPicker testicker = DependencyService.Get< IContactPicker >();
						testicker.ShowContactPicker();
					}	
				}
				catch (Exception ex)
                {
                    DisplayAlert("contactsInputTapRecognizer: ", ex.Message, "ok");
                }
                 
            };

            #endregion

            #endregion

            #region ICON CONTAINER GRID

            iconContainerGrid = new Grid
            {
                IsVisible = false,
                VerticalOptions = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions = 
            {
                    new RowDefinition { Height = GridLength.Auto }
                },
                ColumnDefinitions = 
            {
                    new ColumnDefinition { Width = new GridLength(((screenWidth * .80) )/4, GridUnitType.Absolute) }, // icon container x = 3 //new ColumnDefinition { Width = GridLength.Auto },
                  //  new ColumnDefinition { Width = new GridLength(((screenWidth * .80)) /5, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(((screenWidth * .80))/4, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(((screenWidth * .80))/4, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(((screenWidth * .80))/4, GridUnitType.Absolute) },
            }
            };

            iconContainerGrid.Children.Add(galleryInputStack, 0, 0);
            iconContainerGrid.Children.Add(cameraInputStack, 1, 0);
          //  iconContainerGrid.Children.Add(audioInputStack, 2, 0);
            iconContainerGrid.Children.Add(locationInputStack, 2, 0);
            iconContainerGrid.Children.Add(contactInputStack, 3, 0);

            textinputAndIconsHolder = new StackLayout
            {
                Orientation = StackOrientation.Vertical,
                HorizontalOptions = LayoutOptions.Center,
                Spacing = 0,
                Padding = 0,
				Children = { textInputContainer, iconContainerGrid, editLocationAndContactsStack }
            };

            Button createEvent = new Button();
            if (pageTitle == Constants.ADD_ACTIONS || pageTitle == Constants.ADD_GOALS || pageTitle == Constants.EDIT_ACTIONS || pageTitle == Constants.EDIT_GOALS)
            {
                createEvent.BackgroundColor = Color.Transparent;
                createEvent.TextColor = Constants.BLUE_BG_COLOR;
                createEvent.Text = "Create Reminder";
                createEvent.FontSize = 12;
                createEvent.BorderWidth = 0;
                createEvent.BorderColor = Color.Transparent;
                createEvent.Clicked += createEvent_Clicked;
				if( Device.OS == TargetPlatform.iOS )
				createEvent.TranslationY = -8;
                textinputAndIconsHolder.Children.Add(createEvent);

            }
            masterLayout.AddChildToLayout(textinputAndIconsHolder, 5, 21);


            #region PREVIEW LIST
            listContainer = new StackLayout();
            listContainer.BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY;
            listContainer.WidthRequest = screenWidth * 90 / 100;
            listContainer.HeightRequest = screenHeight * 25 / 100;
            listContainer.ClassId = "preview";

            previewListView = new ListView();
            previewListView.BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY;
            PreviewListViewCellItem.addEvntObject = this;
            previewListView.ItemTemplate = new DataTemplate(typeof(PreviewListViewCellItem));
            previewListView.SeparatorVisibility = SeparatorVisibility.None;
            previewListView.Opacity = 1;
            previewListView.ItemsSource = App.PreviewListSource;
			previewListView.ItemSelected += (object sender, SelectedItemChangedEventArgs e) => 
			{
              /*  PreviewItem items = previewListView.SelectedItem as PreviewItem;
                if( items != null )
                App.Navigator.PushModalAsync( new VideoPlayerView( items.Path ) );*/
				previewListView.SelectedItem = null;
			};
            listContainer.Children.Add(previewListView);
            masterLayout.AddChildToLayout(listContainer, 5, Device.OnPlatform( 63, 63, 50 ));
            #endregion

			//masterLayout.AddChildToLayout(locationEditStack, 5, 30 );
            #endregion

            Content = masterLayout;
        }
		public CommunityMediaViewer ( List<PurposeColor.Constants.MediaDetails> mediaList )
		{
			NavigationPage.SetHasNavigationBar (this, false);
			masterLayout = new CustomLayout ();
			masterLayout.BackgroundColor = Color.Black;// Color.FromRgb(244, 244, 244);
			masterScroll = new ScrollView ();
			masterScroll.BackgroundColor = Color.Black;//Color.FromRgb(244, 244, 244);
			progressBar = DependencyService.Get<IProgressBar> ();

			mainTitleBar = new PurposeColorTitleBar (Color.FromRgb (8, 135, 224), "Purpose Color", Color.Black, "back", true);
			subTitleBar = new PurposeColorSubTitleBar (Constants.SUB_TITLE_BG_COLOR, "Gem Media Viewer", false);
			subTitleBar.BackButtonTapRecognizer.Tapped += async (object sender, EventArgs e) => {
				try {
					await Navigation.PopAsync ();
				} catch (Exception) {
				}
			};

			mainTitleBar.imageAreaTapGestureRecognizer.Tapped += (object sender, EventArgs e) => 
			{
				App.masterPage.IsPresented = !App.masterPage.IsPresented;
			};
				

			masterStack = new CustomLayout ();
			masterStack.BackgroundColor = Color.Transparent;
			masterStack.HorizontalOptions = LayoutOptions.Center;

			StackLayout bottomAndLowerControllStack = new StackLayout {
				Orientation = StackOrientation.Vertical,
				BackgroundColor = Color.Transparent,
				Spacing = 1,
				Padding = new Thickness (0, 5, 0, 5),
				WidthRequest = App.screenWidth,
			};


			ScrollView imgScrollView = new ScrollView ();
			imgScrollView.Orientation = ScrollOrientation.Horizontal;

			StackLayout horizmgConatiner = new StackLayout ();
			horizmgConatiner.Orientation = StackOrientation.Horizontal;


			CustomImageButton nextImg = new CustomImageButton ();
			nextImg.ImageName = "next.png";
			nextImg.WidthRequest = 40;
			nextImg.HeightRequest = 65;
				
			nextImg.Clicked += async (object sender, EventArgs e) => 
			{

				double curX = imgScrollView.ScrollX;
				double imgWidth = App.screenWidth * 100 / 100;

				if( Device.OS == TargetPlatform.iOS )
				{
					if( curX + imgWidth + 15 < imgScrollView.ContentSize.Width )
						await imgScrollView.ScrollToAsync( curX + imgWidth , 0, true );
				}
				else
				{
					await imgScrollView.ScrollToAsync( curX + imgWidth , 0, true );
				}
					
			};


			CustomImageButton prevImg = new CustomImageButton ();
			prevImg.ImageName = "prev.png";
			prevImg.WidthRequest = 40;
			prevImg.HeightRequest = 65;
			prevImg.Clicked += async (object sender, EventArgs e) => 
			{
				double curX = imgScrollView.ScrollX;
				double imgWidth = App.screenWidth * 90 / 100;
				if( curX > 0 )
				await imgScrollView.ScrollToAsync( curX - App.screenWidth , 0, true );
			};


			#region MEDIA LIST

			if (mediaList != null) 
			{
				foreach (var item in mediaList) 
				{
					TapGestureRecognizer videoTap = new TapGestureRecognizer ();
					videoTap.Tapped += OnActionVideoTapped;

					Image img = new Image ();
					bool isValidUrl = ( item.Url != null && !string.IsNullOrEmpty ( item.Url )) ? true : false;
					string source = (isValidUrl) ? item.Url : Device.OnPlatform ("noimage.png", "noimage.png", "//Assets//noimage.png");
					string fileExtenstion = Path.GetExtension (source);
					bool isImage = (fileExtenstion == ".png" || fileExtenstion == ".jpg" || fileExtenstion == ".jpeg") ? true : false;
					img.WidthRequest = App.screenWidth;
					img.HeightRequest = App.screenWidth;
					img.Aspect = Aspect.AspectFill;
					img.ClassId = null;
					if (item != null && item.MediaType == "mp4") 
					{
						img.ClassId = source;
						source = Constants.SERVICE_BASE_URL + item.ImageName;
					}
					else if ( item != null &&  item.MediaType == "aac")
					{
						img.ClassId = source;
						source = Device.OnPlatform ("audio.png", "audio.png", "//Assets//audio.png");
					}
					else if ( item != null &&  item.MediaType == "3gpp")
					{
						img.ClassId = source;
						source = Constants.SERVICE_BASE_URL + item.ImageName;
					}
					else if ( item != null && item.MediaType == "wav")
					{
						img.ClassId = source;
						source = Device.OnPlatform ("audio.png", "audio.png", "//Assets//audio.png");
					}
					img.Source = source;
					img.GestureRecognizers.Add (videoTap);
					var indicator = new ActivityIndicator { Color = new Color (.5), };
					indicator.SetBinding (ActivityIndicator.IsRunningProperty, "IsLoading");
					indicator.BindingContext = img;
					masterStack.AddChildToLayout (indicator, 40, 30);

					if (item != null && ( item.MediaType == "mp4" || item.MediaType == "3gpp" ) )
					{
						Grid grid = new Grid
						{
							VerticalOptions = LayoutOptions.FillAndExpand,
							HorizontalOptions = LayoutOptions.FillAndExpand,
							RowDefinitions = 
							{
								new RowDefinition { Height = new GridLength( img.WidthRequest / 3 ) },
								new RowDefinition { Height = new GridLength( img.WidthRequest / 3 ) },
								new RowDefinition { Height = new GridLength( img.WidthRequest / 3 ) },

							},
							ColumnDefinitions = 
							{
								new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },
								new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },
								new ColumnDefinition { Width = new GridLength( img.WidthRequest / 3 ) },

							}
						};

						Image play = new Image();
						play.Source = "video_play.png";
						play.Aspect = Aspect.AspectFit;
						play.WidthRequest = 75;
						play.HeightRequest = 75;
						play.HorizontalOptions = LayoutOptions.Center;
						play.VerticalOptions = LayoutOptions.Center;
						play.ClassId =  img.ClassId;
						play.GestureRecognizers.Add(videoTap);

						grid.Children.Add( img, 0, 0 );
						Grid.SetColumnSpan(img, 3);
						Grid.SetRowSpan( img, 3 );
						grid.Children.Add(play, 1, 1);
						horizmgConatiner.Children.Add(grid);
					}
					else
					{
						horizmgConatiner.Children.Add(img);
					}
				}
				imgScrollView.Content = horizmgConatiner;
				bottomAndLowerControllStack.Children.Add (imgScrollView);

			}

			#endregion

			masterStack.AddChildToLayout (bottomAndLowerControllStack, 0, Device.OnPlatform (5, 9, 12));//12
			masterScroll.HeightRequest = App.screenHeight - 20;
			masterScroll.WidthRequest = App.screenWidth;// * 90 / 100;

			StackLayout masterStackLayout = new StackLayout ();
			masterStackLayout.HorizontalOptions = LayoutOptions.Center;
			masterStackLayout.BackgroundColor = Color.Black;
			masterStackLayout.Orientation = StackOrientation.Vertical;
			masterStackLayout.Children.Add (masterStack);
			masterScroll.Content = masterStackLayout;
			masterLayout.AddChildToLayout (mainTitleBar, 0, 0);
			masterLayout.AddChildToLayout (subTitleBar, 0, Device.OnPlatform (9, 10, 10));
			masterLayout.AddChildToLayout (masterScroll, 0, 18);
			masterLayout.AddChildToLayout (prevImg, Device.OnPlatform( -2, -2, 0 ), 50);
			masterLayout.AddChildToLayout (nextImg, 90, 50);
			Content = masterLayout;
		}
		public FeelingNowPage()
		{
			NavigationPage.SetHasNavigationBar(this, false);
			masterLayout = new CustomLayout();
			masterLayout.BackgroundColor = Color.FromRgb(244, 244, 244);
			screenHeight = App.screenHeight;
			screenWidth = App.screenWidth;
			progressBar = DependencyService.Get<IProgressBar>();
			currentUser = App.Settings.GetUser ();
			AddEventsSituationsOrThoughts.feelingsPage = this;

			mainTitleBar = new PurposeColorTitleBar(Color.FromRgb(8, 135, 224), "Purpose Color", Color.Black, "back", true);
			mainTitleBar.imageAreaTapGestureRecognizer.Tapped += imageAreaTapGestureRecognizer_Tapped;
			subTitleBar = new PurposeColorSubTitleBar(Constants.SUB_TITLE_BG_COLOR, "Emotional Awareness");
			subTitleBar.NextButtonTapRecognizer.Tapped += OnNextButtonTapRecognizerTapped;
			subTitleBar.BackButtonTapRecognizer.Tapped += OnBackButtonTapRecognizerTapped;

			slider = new CustomSlider
			{
				Minimum = -2,
				Maximum = 2,
				WidthRequest = screenWidth * 90 / 100
			};
			slider.StopGesture = GetstopGetsture;

			Label howYouAreFeeling = new Label();
			howYouAreFeeling.Text = Constants.HOW_YOU_ARE_FEELING;
			howYouAreFeeling.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			howYouAreFeeling.TextColor = Color.FromRgb(40, 47, 50);
			howYouAreFeeling.HorizontalOptions = LayoutOptions.Center;

			Label howYouAreFeeling2 = new Label();
			howYouAreFeeling2.Text = "feeling now ?";
			howYouAreFeeling2.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			howYouAreFeeling2.TextColor = Color.FromRgb(40, 47, 50);
			howYouAreFeeling2.HorizontalOptions = LayoutOptions.Center;

			#region  Emotion pic button
			emotionalPickerButton = new PurposeColor.interfaces.CustomImageButton ();
			emotionalPickerButton.ImageName = Device.OnPlatform ("select_box_whitebg.png", "select_box_whitebg.png", @"/Assets/select_box_whitebg.png");
			emotionalPickerButton.Text = "Select Emotion";

			emotionalPickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			emotionalPickerButton.TextOrientation = interfaces.TextOrientation.Left;
			emotionalPickerButton.TextColor = Color.Gray;
			emotionalPickerButton.WidthRequest = screenWidth * 90 / 100;
			emotionalPickerButton.Clicked += OnEmotionalPickerButtonClicked;

			eventPickerButton = new PurposeColor.interfaces.CustomImageButton ();
			eventPickerButton.IsVisible = false;
			eventPickerButton.ImageName = Device.OnPlatform ("select_box_whitebg.png", "select_box_whitebg.png", "/Assets/select_box_whitebg.png");
			eventPickerButton.Text = "Events, Situation & Thoughts";
			eventPickerButton.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			eventPickerButton.TextOrientation = interfaces.TextOrientation.Left;
			eventPickerButton.TextColor = Color.Gray;
			eventPickerButton.WidthRequest = screenWidth * 90 / 100;


			if (!eventsDisplaying)
			{
				eventPickerButton.Clicked += OnEventPickerButtonClicked;
			}
			#endregion

			#region About text
			about = new Label ();
			about.IsVisible = false;
			about.Text = "About";
			about.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			about.WidthRequest = screenWidth;
			about.HorizontalOptions = LayoutOptions.Center;
			about.XAlign = TextAlignment.Center;

			about.FontFamily = Constants.HELVERTICA_NEUE_LT_STD;
			about.TextColor = Color.FromRgb (40, 47, 50);

			int fontSize = 15;
			if (App.screenDensity > 1.5) {
				howYouAreFeeling.FontSize = Device.OnPlatform (20, 22, 30);
				howYouAreFeeling2.FontSize = Device.OnPlatform (20, 22, 30);
				about.FontSize = Device.OnPlatform (15, 18, 30);

				emotionalPickerButton.HeightRequest = screenHeight * 6 / 100;
				fontSize = 17;
				eventPickerButton.HeightRequest = screenHeight * 6 / 100;
			} else {
				howYouAreFeeling.FontSize = Device.OnPlatform (16, 18, 26);
				howYouAreFeeling2.FontSize = Device.OnPlatform (16, 18, 26);
				about.FontSize = Device.OnPlatform (16, 18, 26);

				emotionalPickerButton.HeightRequest = screenHeight * 9 / 100;
				fontSize = 15;
				eventPickerButton.HeightRequest = screenHeight * 9 / 100;
			}

			emotionalPickerButton.FontSize = Device.OnPlatform (fontSize, fontSize, 22);
			eventPickerButton.FontSize = Device.OnPlatform (fontSize, fontSize, 22);
			#endregion

			this.Appearing += OnFeelingNowPageAppearing;

			sliderValue = slider.CurrentValue;
			masterLayout.AddChildToLayout(mainTitleBar, 0, 0);
			masterLayout.AddChildToLayout(subTitleBar, 0, Device.OnPlatform(9, 10, 10));

			sliderValLabel = new Label
			{
				TextColor = Constants.BLUE_BG_COLOR,
				BackgroundColor = Color.Transparent,
				XAlign = TextAlignment.Start
			};

			sliderValueImage = new Image {
				Source = "Sliderfeedback0.png",
				HeightRequest = 30,
				Aspect = Aspect.Fill, 
				InputTransparent = true,
				BackgroundColor = Color.Transparent,

			};

			#region SLIDER LABEL TAP

			TapGestureRecognizer sliderLabelTapRecognizer = new TapGestureRecognizer();
			sliderLabelTapRecognizer.Tapped += (s, e) =>
			{
				/// show a slider as a popup and get its value,
				RemoveSliderPopup();
				popupSlider = new CustomSlider
				{
					Minimum = -2,
					Maximum = 2,
					WidthRequest = screenWidth * 90 / 100,
					HorizontalOptions = LayoutOptions.Center,
					VerticalOptions = LayoutOptions.Center,
					CurrentValue = sliderValue
				};

				StackLayout sliderBg = new StackLayout
				{
					BackgroundColor = Color.Black,
					Opacity = .95,
					HeightRequest = App.screenHeight,
					WidthRequest = App.screenWidth,
					HorizontalOptions = LayoutOptions.Center,
					VerticalOptions = LayoutOptions.Center,
					Children = {
						new StackLayout{HeightRequest = 250},
						new StackLayout{
							Children = { popupSlider },
							Padding = 10,
							BackgroundColor = Color.FromRgb(244, 244, 244),
							HorizontalOptions = LayoutOptions.Center,
							VerticalOptions = LayoutOptions.Center,
							Opacity = 1
						}
					},
					ClassId = "sliderBg"
				};

				TapGestureRecognizer sliderBgTapRecognizer = new TapGestureRecognizer();
				sliderBg.GestureRecognizers.Add(sliderBgTapRecognizer);
				sliderBgTapRecognizer.Tapped += (snd, eve) =>
				{
					RemoveSliderPopup();
				};

				popupSlider.CurrentValue = slider.CurrentValue;
				popupSlider.StopGesture = GetstopGetsture;

				masterLayout.AddChildToLayout(sliderBg, 0, 0);
			};

			#endregion

			emotionTextLabel = new Label
			{
				TextColor = Constants.BLUE_BG_COLOR,
				BackgroundColor = Color.Transparent,
				XAlign = TextAlignment.Start,
				FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
				FontSize = Device.OnPlatform(12, 14, 26)
			};
			emotionTextTap = new TapGestureRecognizer();
			emotionTextTap.Tapped += EmotionTextTap_Tapped;

			eventTextLabel = new Label
			{
				TextColor = Constants.BLUE_BG_COLOR,
				BackgroundColor = Color.Transparent,
				XAlign = TextAlignment.Start,
				FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
				FontSize = Device.OnPlatform(12, 14, 26)
			};

			eventTextTap = new TapGestureRecognizer();
			eventTextTap.Tapped += async (s, e) =>
			{
				if (!eventsDisplaying)
				{
					await Task.Delay(100);
					OnEventPickerButtonClicked(eventPickerButton, EventArgs.Empty);
				}
			};
			//eventTextLabel.GestureRecognizers.Add(eventTextTap);

			sliderFeedbackStack = new StackLayout {
				IsVisible = false,
				BackgroundColor = Color.Transparent,
				VerticalOptions = LayoutOptions.Center,
				Orientation = StackOrientation.Horizontal, 
				Spacing = 0, Padding = new Thickness (App.screenWidth * .10, 0, 10, 0), 
				Children = {
					new Label {
						FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
						FontSize = Device.OnPlatform(12, 14, 26),
						Text = "Happiness : ",
						TextColor = Color.Black,
						VerticalOptions = LayoutOptions.End,
					},
					sliderValueImage
				}
			};
			sliderFeedbackStack.GestureRecognizers.Add(sliderLabelTapRecognizer);


			feelingFeedbackStack = new StackLayout {
				IsVisible = false,
				Orientation = StackOrientation.Horizontal,
				Spacing = 0,
				Padding = new Thickness (App.screenWidth * .10, 0, 10, 0),
				Children = {
					new Label {
						Text = "Feeling : " ,
						TextColor = Color.Black,
						FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
						FontSize = Device.OnPlatform(12, 14, 26),
					},
					emotionTextLabel
				}
			};
			feelingFeedbackStack.GestureRecognizers.Add(emotionTextTap);

			eventFeedbackStack = new StackLayout {
				IsVisible = false,
				//BackgroundColor = Color.Red,
				Orientation = StackOrientation.Horizontal,
				Spacing = 0,
				Padding = new Thickness (App.screenWidth * .10, 0, 10, 0),
				Children = {
					new Label {
						Text = "Event : " ,
						TextColor = Color.Black,
						FontFamily = Constants.HELVERTICA_NEUE_LT_STD,
						FontSize = Device.OnPlatform(12, 14, 26),
					},
					eventTextLabel
				}
			};
			eventFeedbackStack.GestureRecognizers.Add(eventTextTap);

			// add this to a customLayout n a stack with bg transparent.
			topLabelsContainer = new CustomLayout {
				WidthRequest = screenWidth,
			};

			topLabelBg = new StackLayout {
				WidthRequest = screenWidth,
				BackgroundColor = Color.Gray,
				Opacity = .2
			};

			topBgandCloseBtn = new StackLayout {
				//BackgroundColor  = Color.Yellow, // for testing only
				Orientation = StackOrientation.Vertical,
				Spacing = 0,
				Children = {topLabelBg}
			};

			topCloseBtn = new Image {
				Source = "downarrow.png",
				IsVisible = false,
				HeightRequest = 25,
				WidthRequest = 35,
				HorizontalOptions = LayoutOptions.End
			};
			topBgandCloseBtn.Children.Add (topCloseBtn);

			TapGestureRecognizer topCloseBtnTapRecognizer = new TapGestureRecognizer();
			topCloseBtnTapRecognizer.Tapped += (s, e) =>
			{
				AnimateToplabels(0);
			};

			topCloseBtn.GestureRecognizers.Add (topCloseBtnTapRecognizer);

			feedbackLabelStack = new StackLayout
			{
				Orientation = StackOrientation.Vertical,
				//BackgroundColor = Constants.PAGE_BG_COLOR_LIGHT_GRAY,
				HorizontalOptions = LayoutOptions.Center,
				VerticalOptions = LayoutOptions.Center,
				Spacing = 2,
				WidthRequest = App.screenWidth,
				Children = {sliderFeedbackStack, feelingFeedbackStack, eventFeedbackStack}
			};
			topLabelsContainer.AddChildToLayout (topBgandCloseBtn, 0, 0);
			topLabelsContainer.AddChildToLayout (feedbackLabelStack, 0, 0);


			//masterLayout.AddChildToLayout(feedbackLabelStack, 0, Device.OnPlatform(16, 18, 10));
			masterLayout.AddChildToLayout(topLabelsContainer, 0, Device.OnPlatform(16, 18, 10));

			masterLayout.AddChildToLayout(howYouAreFeeling, 16, Device.OnPlatform(33, 33, 30));
			masterLayout.AddChildToLayout(howYouAreFeeling2, 29, Device.OnPlatform(38, 38, 27));
			masterLayout.AddChildToLayout(slider, 5, 43);

			masterLayout.AddChildToLayout(emotionalPickerButton, 5, Device.OnPlatform(50, 57, 47));
			masterLayout.AddChildToLayout(about, 0, Device.OnPlatform(62, 66, 59));
			masterLayout.AddChildToLayout(eventPickerButton, 5, Device.OnPlatform(70, 73, 67));




			//SetFeedBackLablText();
			Content = masterLayout;

		}