public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            var cell = tableView.CellAt(indexPath);


            if (Reachability.IsHostReachable(Settings._baseDomain))
            {
                var ad = Owner.FavoritesAdList[indexPath.Row];
                var statusBarHeight = UIApplication.SharedApplication.StatusBarFrame.Height;
                var tabBarHeight    = Owner.TabBarController.TabBar.Bounds.Height;

                var frame   = new CGRect(0, statusBarHeight, Owner.View.Bounds.Width, Owner.View.Bounds.Height - (statusBarHeight + tabBarHeight));
                var webView = new UIWebView(frame);

                LoadingOverlay loadingOverlay = new LoadingOverlay(Owner.View.Frame);

                webView.LoadFinished += (sender, e) =>
                {
                    loadingOverlay.Hide();
                };


                var url = ad.AircraftForSaleURL;
                webView.LoadRequest(new NSUrlRequest(new NSUrl(url)));

                UIView.BeginAnimations("fadeflag");
                UIView.Animate(1, () =>
                {
                    cell.Alpha = .5f;
                }, () =>
                {
                    Owner.View.AddSubview(webView);
                    Owner.View.AddSubview(loadingOverlay);

                    UIButton closeButton = new UIButton(new CGRect(Owner.View.Bounds.Width - 50, 0, 50, 50));
                    closeButton.SetImage(UIImage.FromBundle("close"), UIControlState.Normal);
                    closeButton.BackgroundColor = UIColor.Black;
                    closeButton.TouchUpInside  += (sender, e) =>
                    {
                        try
                        {
                            webView.RemoveFromSuperview();
                            closeButton.RemoveFromSuperview();
                        }
                        finally
                        {
                            webView.Dispose();
                        }
                    };
                    //Owner.View.AddSubview(closeButton);
                    webView.AddSubview(closeButton);

                    cell.Alpha = 1f;
                });

                UIView.CommitAnimations();
                //}
            }
            else
            {
                HelperMethods.SendBasicAlert("Connect to a Network", "Please connect to a network to view this ad");
            }



            tableView.DeselectRow(indexPath, true);
        }
        async void SubmitButton_TouchUpInside(object sender, EventArgs e)
        {
            UsernameTextField.Enabled = false;
            PasswordTextField.Enabled = false;

            string username = UsernameTextField.Text;
            string password = PasswordTextField.Text;



            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                if (!HelperMethods.IsValidPassword(password))
                {
                    HelperMethods.SendBasicAlert("Validation", "Passwords should contain letters and numbers and be at least 6 characters.");
                    PasswordTextField.Layer.BorderColor = UIColor.Red.CGColor;
                    PasswordTextField.Layer.BorderWidth = 1f;
                    UsernameTextField.Enabled           = true;
                    PasswordTextField.Enabled           = true;
                    return;
                }
                //Save username/password to settings

                Settings.Username = username;
                Settings.Password = password;



                LoadingOverlay loadingIndicator = new LoadingOverlay(this.View.Frame, "Loading ...");
                this.View.AddSubview(loadingIndicator);

                //AuthResponse

                BlobCache.LocalMachine.InvalidateObject <AuthResponse>(AuthResponse.getAuthResponse);

                AuthResponse response = await AuthResponse.GetAuthResponseAsync(0, Settings.Username, Settings.Password);

                Settings.AppID     = response.AppId;
                Settings.AuthToken = response.AuthToken;

                APIManager manager = new APIManager();

                {
                    //LoginResponse authResponse = await manager.loginUser(Settings.AppID, Settings.Username, Settings.Password, Settings.AuthToken);
                    LoginResponse authResponse = await manager.loginUser(Settings.AppID, Settings.Username, Settings.Password, Settings.AuthToken);

                    if (authResponse.AuthToken != null)
                    {
                        Settings.AppID     = authResponse.AppId;
                        Settings.UserID    = authResponse.MagAppUserId;
                        Settings.AuthToken = authResponse.AuthToken;
                    }
                    else
                    {
                        loadingIndicator.Hide();
                        String responseMessage = "";
                        if (authResponse.ResponseMsg != null && authResponse.ResponseMsg != string.Empty)
                        {
                            responseMessage = authResponse.ResponseMsg;
                        }
                        else
                        {
                            responseMessage = "Unable to authenticate user.";
                        }

                        if (responseMessage == "Incorrect Password")
                        {
                            MessageViewController messageViewController = (MessageViewController)Storyboard.InstantiateViewController("MessageViewController");
                            this.PresentViewController(messageViewController, true, null);
                        }
                        else
                        {
                            HelperMethods.SendBasicAlert("Login", responseMessage);
                        }
                        UsernameTextField.Enabled = true;
                        PasswordTextField.Enabled = true;
                        return;
                    }


                    try
                    {
                        var responseProfile = await manager.getUserProfile(Settings.AppID, Settings.Username, Settings.AuthToken, Settings.Password);

                        Settings.IsAmphibian    = responseProfile.C1 == 1;
                        Settings.IsCommercial   = responseProfile.C2 == 1;
                        Settings.IsExperimental = responseProfile.C3 == 1;
                        Settings.IsHelicopter   = responseProfile.C4 == 1;
                        Settings.IsJets         = responseProfile.C5 == 1;
                        Settings.IsSingles      = responseProfile.C7 == 1;
                        Settings.IsSingleEngine = responseProfile.C6 == 1;
                        Settings.IsTwinPistons  = responseProfile.C8 == 1;
                        Settings.IsTwinTurbines = responseProfile.C9 == 1;
                        Settings.IsVintage      = responseProfile.C10 == 1;
                        Settings.IsWarbirds     = responseProfile.C11 == 1;
                        Settings.IsLightSport   = responseProfile.C12 == 1;

                        Settings.Email = Settings.Username;

                        Settings.FirstName = responseProfile.FirstName;
                        Settings.LastName  = responseProfile.LastName;
                        Settings.Phone     = responseProfile.CellPhone;

                        Settings.Company                  = responseProfile.Company;
                        Settings.Hours                    = responseProfile.HourPerMonth;
                        Settings.ManufacturerId           = responseProfile.DesignationId;
                        Settings.LocationPickerSelectedId = responseProfile.CountryId;
                        Settings.Phone                    = responseProfile.CellPhone;
                        Settings.DesignationId            = responseProfile.DesignationId;
                        Settings.PurposeId                = responseProfile.FlyingPurposeId;
                        Settings.HomeAirport              = responseProfile.HomeAirport;
                        Settings.Password                 = responseProfile.Password;
                        Settings.PilotStatusId            = responseProfile.PilotStatusId;
                        Settings.PilotTypeId              = responseProfile.PilotTypeId;
                        Settings.PurchaseTimeFrame        = responseProfile.PurchaseTimeFrame;

                        loadingIndicator.Hide();
                        this.PerformSegue("LoadTabBarControllerSeque", this);
                    }
                    catch (Exception exe)
                    {
                        loadingIndicator.Hide();
                        HelperMethods.SendBasicAlert("Login", "Login Failed");
                    }
                }



                PasswordTextField.Layer.BorderColor = UIColor.Clear.CGColor;
                PasswordTextField.Layer.BorderWidth = 0f;

                UsernameTextField.Layer.BorderColor = UIColor.Clear.CGColor;
                UsernameTextField.Layer.BorderWidth = 0f;
            }
            else
            {
                //Update UI to reflect invalid username or password

                if (string.IsNullOrEmpty(username))
                {
                    UsernameTextField.Layer.BorderColor = UIColor.Red.CGColor;
                    UsernameTextField.Layer.BorderWidth = 1f;
                }
                else
                {
                    UsernameTextField.Layer.BorderColor = UIColor.Clear.CGColor;
                    UsernameTextField.Layer.BorderWidth = 0f;
                }

                if (string.IsNullOrEmpty(password))
                {
                    PasswordTextField.Layer.BorderColor = UIColor.Red.CGColor;
                    PasswordTextField.Layer.BorderWidth = 1f;
                }
                else
                {
                    PasswordTextField.Layer.BorderColor = UIColor.Clear.CGColor;
                    PasswordTextField.Layer.BorderWidth = 0f;
                }
            }

            UsernameTextField.Enabled = true;
            PasswordTextField.Enabled = true;
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();



            this.NavigationItem.SetLeftBarButtonItem(new UIBarButtonItem(
                                                         UIImage.FromFile("new_home.png"), UIBarButtonItemStyle.Plain, (sender, args) =>
            {
                NavigationController.PopViewController(true);
            }), true);

            //Hide text button if broker doesn't have a cell phone
            if (string.IsNullOrEmpty(DataObject.Ads[0].BrokerCellPhone))
            {
                AdMessages1.Alpha = 0f;
            }
            ;

            var ad1 = DataObject.Ads[0];

            try
            {
                FeaturedLabel.Hidden = !ad1.IsFeatured;

                AdImage1.SetImage(
                    url: new NSUrl(ad1.ImageURL),
                    placeholder: UIImage.FromBundle("ad_placeholder.jpg")
                    );
            }
            catch (Exception ex)
            {
                string debugLine = ex.Message;
            }



            var labelAttribute = new UIStringAttributes
            {
                Font = UIFont.BoldSystemFontOfSize(18)
            };

            var brokerLabelAttribute = new UIStringAttributes
            {
                Font = UIFont.BoldSystemFontOfSize(15)
            };
            var brokerValueAttribute = new UIStringAttributes
            {
                Font            = UIFont.SystemFontOfSize(15),
                ForegroundColor = UIColor.Blue
            };



            Ad1NameButton.SetTitle(ad1.Name, UIControlState.Normal);
            Ad1NameButton.Layer.BorderWidth  = 1;
            Ad1NameButton.Layer.BorderColor  = UIColor.White.CGColor;
            Ad1NameButton.Layer.CornerRadius = 5;


            string price = "";

            if (ad1.Price.Length == 0)
            {
                price = "Call";
            }
            else
            {
                price = ad1.Price;
            }

            AircraftDetails[] aircraftDetails;


            if (ad1.IsFeatured)
            {
                var airframeDetails    = ad1.FeaturedSpec.AirframeDetails.Replace("<br>", "\n");
                var engineDetails      = ad1.FeaturedSpec.EngDetails.Replace("<br>", "\n");
                var interiorDetails    = ad1.FeaturedSpec.IntDetails.Replace("<br>", "\n");
                var exteriorDetails    = ad1.FeaturedSpec.ExtDetails.Replace("<br>", "\n");
                var maintenanceDetails = ad1.FeaturedSpec.Maintenance.Replace("<br>", "\n");
                var avionicsDetails    = ad1.FeaturedSpec.AvDetails.Replace("<br>", "\n");
                var additionalDetails  = ad1.FeaturedSpec.DescriptionDetails.Replace("<br>", "\n");

                aircraftDetails = new AircraftDetails[] {
                    new AircraftDetails("Price:", price, false),
                    new AircraftDetails("Offered by:", ad1.BrokerName, true),
                    new AircraftDetails("Registration:", HelperMethods.GetRegistrationString(ad1, labelAttribute), false),
                    new AircraftDetails("Serial Number:", HelperMethods.GetSerialString(ad1, labelAttribute), false),
                    new AircraftDetails("Time:", HelperMethods.GetTotalTimeString(ad1, labelAttribute), false),
                    new AircraftDetails("Location:", ad1.Location, false),
                    new AircraftDetails("Summary:", ad1.Teaser == string.Empty ? "Inquire for Details" : ad1.Teaser, false),
                    new AircraftDetails("AIRFRAME:", airframeDetails == "" ? "N/A" : airframeDetails, false),
                    new AircraftDetails("ENGINE(S):", engineDetails == "" ? "N/A" : engineDetails, false),
                    new AircraftDetails("INTERIOR:", interiorDetails == "" ? "N/A" : interiorDetails, false),
                    new AircraftDetails("EXTERIOR:", exteriorDetails == "" ? "N/A" : exteriorDetails, false),
                    new AircraftDetails("MAINTENANCE:", maintenanceDetails == "" ? "N/A" : maintenanceDetails, false),
                    new AircraftDetails("AVIONICS:", avionicsDetails == "" ? "N/A" : avionicsDetails, false),
                    new AircraftDetails("ADDITIONAL DETAILS:", additionalDetails == "" ? "N/A" : additionalDetails, false)
                };
            }
            else
            {
                aircraftDetails = new AircraftDetails[] {
                    new AircraftDetails("Price:", price, false),
                    new AircraftDetails("Offered by:", ad1.BrokerName, true),
                    new AircraftDetails("Registration:", HelperMethods.GetRegistrationString(ad1, labelAttribute), false),
                    new AircraftDetails("Serial Number:", HelperMethods.GetSerialString(ad1, labelAttribute), false),
                    new AircraftDetails("Time:", HelperMethods.GetTotalTimeString(ad1, labelAttribute), false),
                    new AircraftDetails("Location:", ad1.Location, false),
                    new AircraftDetails("Summary:", ad1.Teaser == string.Empty ? "Inquire for Details" : ad1.Teaser, false),
                };
            }



            #region price changed
            if (!HelperMethods.ShowPriceChangedLabel(ad1.PriceLastUpdated))
            {
                Ad1PriceChangeLabel.Alpha = 0f;
            }

            #endregion


            //Set initial state of like buttons
            if (DataObject.Ads[0].IsLiked)
            {
                HelperMethods.SetInitialLikeButtonState(AdLike1, DataObject.Ads[0]);
            }



            //webview image tap gestures
            AdImage1.UserInteractionEnabled = true;

            tapGesture1 = new UITapGestureRecognizer(TapImageAction1);

            int currentIndex = this.DataObject.MagazinePageIndex;
            int totalPages   = this.DataObject.TotalPages;

            PageIndicator.SetIndicatorState(currentIndex, totalPages);


            loadSpeciafication();

            //SpecTableView.RegisterClassForCellReuse(typeof(AircraftDetailsLabelCell), AircraftDetailsTableSource.CellLabelIdentifier);

            SpecTableView.Source = new AircraftDetailsTableSource(aircraftDetails, DataObject.Ads[0]);
        }
        void AdSortButton_TouchUpInside(object sender, EventArgs e)
        {
            if (!Settings.IsRegistered)
            {
                if (sender == Ad1NameButton)
                {
                    HelperMethods.MakeModelRegistrationRequiredPrompt(this, sender as UIButton);
                }
                //if (sender == Ad1BrokerButton)
                //{
                //    HelperMethods.SellerRegistrationRequiredPrompt(this, sender as UIButton);
                //}
                return;
            }

            Ad   ad           = new Ad();
            bool isAdNameSort = false;

            if (sender == Ad1NameButton)
            {
                ad           = DataObject.Ads[0];
                isAdNameSort = true;
            }


            //if (sender == Ad1BrokerButton)
            //{
            //    ad = DataObject.Ads[0];
            //    isAdNameSort = false;
            //}

            LoadingOverlay loadingIndicator = new LoadingOverlay(this.View.Frame, isAdNameSort ? "Loading Aircraft by Selected Type" : "Loading Aircraft by Selected Broker");

            this.View.AddSubview(loadingIndicator);

            var pageViewController         = this.ParentViewController as UIPageViewController;
            var magFlipBoardViewController = pageViewController.ParentViewController as MagazineFlipBoardViewController;

            var       modelController = magFlipBoardViewController.ModelController;
            List <Ad> adList          = new List <Ad>();

            Task.Run(async() =>
            {
                adList = (await Ad.GetAdsByClassificationAsync(DataObject.SelectedClassification)).ToList();

                //get ads with this name and move them to the from of the list
                List <Ad> similarAdList = new List <Ad>();

                if (isAdNameSort)
                {
                    similarAdList = adList.Where(row => row.Name == ad.Name).OrderBy(r => r.IsFeatured).ToList();
                }
                else
                {
                    similarAdList = adList.Where(row => row.BrokerName == ad.BrokerName).OrderBy(r => r.IsFeatured).ToList();
                }


                for (int i = 0; i < similarAdList.Count(); i++)
                {
                    adList.Remove(similarAdList[i]);
                    adList.Insert(0, similarAdList[i]);
                }

                InvokeOnMainThread(() =>
                {
                    modelController.LoadModalController(adList, DataObject.SelectedClassification);
                    loadingIndicator.Hide();
                    var startingViewController = modelController.GetViewController(0, false);
                    var viewControllers        = new UIViewController[] { startingViewController };
                    pageViewController.SetViewControllers(viewControllers, UIPageViewControllerNavigationDirection.Forward, true, null);

                    HelperMethods.SendBasicAlert("", "Aircraft arranged by " + (isAdNameSort ? ad.Name : ad.BrokerName));
                });
            });
        }
        //[Export("demo:")]
        //void RunDemo(NSString arg)
        //{
        //	//SpecTableView.FlashScrollIndicators();
        //	//PerformSelector(new ObjCRuntime.Selector("demo:"), null, 1);
        //}


        void TapImageAction1(UITapGestureRecognizer tap)
        {
            HelperMethods.LoadWebViewWithAd(tap, DataObject.Ads[0], this.View);
        }