public UIView getDistanceView(int index)
            {
                botones.ElementAt(index).Frame = new CGRect(0, 0, Images.mapa.Size.Width, Images.mapa.Size.Height);
                botones.ElementAt(index).SetBackgroundImage(Images.mapa, UIControlState.Normal);
                botones.ElementAt(index).BackgroundColor = UIColor.Clear;
                distancias.ElementAt(index).Frame        = new CGRect(0, botones.ElementAt(index).Bounds.Height, 60f, 25f);
                //PointF viewPosition = botones.ElementAt (index).ConvertPointToView (new PointF (), controller.tblStores);
                //NSIndexPath indexPath = controller.tblStores.IndexPathForRowAtPoint (viewPosition);

                Double distance = location.Location.DistanceFrom(new CLLocation(Double.Parse(tableItems[index].tienda_latitud), Double.Parse(tableItems[index].tienda_longitud))) / 1000;

                distancias.ElementAt(index).Text        = " " + Math.Round(distance, 2) + "km";
                distancias.ElementAt(index).Font        = UIFont.SystemFontOfSize(12);
                vistas.ElementAt(index).Frame           = new CGRect(0, 0, distancias.ElementAt(index).Bounds.Width, botones.ElementAt(index).Bounds.Height + distancias.ElementAt(index).Bounds.Height);
                botones.ElementAt(index).TouchUpInside += (sender, e) => {
                    SecondMapViewController mapView = new SecondMapViewController();
                    mapView.setTienda(tableItems[index]);
                    this.controller.NavigationController.PushViewController(mapView, true);
                };
                vistas.ElementAt(index).AddSubview(botones.ElementAt(index));
                vistas.ElementAt(index).AddSubview(distancias.ElementAt(index));
                return(vistas.ElementAt(index));
            }
Esempio n. 2
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            try{
                UIBarButtonItem home = new UIBarButtonItem();
                home.Style  = UIBarButtonItemStyle.Plain;
                home.Target = this;
                home.Image  = UIImage.FromFile("Images/home.png");
                this.NavigationItem.RightBarButtonItem = home;
                UIViewController[] vistas = NavigationController.ViewControllers;
                home.Clicked += (sender, e) => {
                    this.NavigationController.PopToViewController(vistas[0], true);
                };

                //Configuramos la vista popup de nueva lista
                NewListView.Layer.BorderWidth  = 1.0f;
                NewListView.Layer.BorderColor  = UIColor.Black.CGColor;
                NewListView.Layer.CornerRadius = 8;
                tblLists.Add(this.NewListView);
                NewListView.Hidden = true;
                //Configuramos la vista popup de cantidad
                QuantityView.Layer.BorderWidth  = 1.0f;
                QuantityView.Layer.BorderColor  = UIColor.Black.CGColor;
                QuantityView.Layer.CornerRadius = 8;
                this.Add(QuantityView);
                QuantityView.Hidden = true;

                //Configuramos la vista de popup de listas
                ListsView.Layer.BorderWidth  = 1.0f;
                ListsView.Layer.BorderColor  = UIColor.Black.CGColor;
                ListsView.Layer.CornerRadius = 8;
                this.Add(this.ListsView);
                ListsView.Hidden = true;

                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    this.btnMapa.SetBackgroundImage(Images.mapa, UIControlState.Normal);
                }
                else
                {
                    this.btnMapa.SetBackgroundImage(Images.mapa, UIControlState.Normal);
                }

                this.btnMapa.TouchUpInside += (sender, e) => {
                    SecondMapViewController mapView = new SecondMapViewController();
                    mapView.setTienda(this.producto);
                    NavigationController.PushViewController(mapView, true);
                };

                var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                _pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

                //Hacemos la conexion a la bd para buscar si hay un usuario registrado
                using (var db = new SQLite.SQLiteConnection(_pathToDatabase))
                {
                    people = new List <Person> (from p in db.Table <Person> () select p);
                }

                NSUrl nsUrl = new NSUrl(producto.imagen);
                data = NSData.FromUrl(nsUrl);
                if (data != null)
                {
                    Images.imagenDetalle   = UIImage.LoadFromData(data);
                    this.imgProducto.Image = Images.imagenDetalle;
                }
                else
                {
                    this.imgProducto.Image = Images.sinImagen;
                }

                //Establecemos la informacion del producto
                this.lblNombre.Text = producto.nombre;
                double precio = Double.Parse(producto.precio);
                this.lblPrecio.Text      = precio.ToString("C2");
                this.lblDescripcion.Text = producto.descripcion;
                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    this.lblDescripcion.Font = UIFont.SystemFontOfSize(10);
                }
                else
                {
                    this.lblDescripcion.Font = UIFont.SystemFontOfSize(25);
                }
                //Establecemos la informacion de la tienda
                NSUrl  nsurl = new NSUrl(producto.tienda_imagen);
                NSData data1 = NSData.FromUrl(nsurl);
                if (data1 != null)
                {
                    Images.imagenDetalleTienda = UIImage.LoadFromData(data1);
                    this.imgTienda.Image       = Images.imagenDetalleTienda;
                }
                else
                {
                    this.imgTienda.Image = Images.sinImagen;
                }
                this.lblTiendaNombre.Text    = producto.tienda_nombre;
                this.lblTiendaDireccion.Text = producto.tienda_direccion + "\n \nTeléfono: " + producto.tienda_telefono;
                if (distancia != 0)
                {
                    this.lblTiendaDistancia.Text = "A " + Math.Round(distancia, 2) + "km de tu ubicación";
                }
                else
                {
                    this.lblTiendaDistancia.Text = "Distancia no disponible";
                }
                this.lblVigencia.Text = "Vigencia del " + producto.inicio_validez + " Al " + producto.final_validez;

                this.btnLista.TouchUpInside += (sender, e) => {
                    if (people.Count > 0)
                    {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Añadir a mi lista", Message = "¿Deseas añadir este producto a una de tus listas?"
                        };
                        alert.AddButton("Añadir");
                        alert.AddButton("Cancelar");
                        alert.Show();
                        alert.Clicked += (s, o) => {
                            if (o.ButtonIndex == 0)
                            {
                                QuantityView.Hidden = false;
                            }
                        };
                    }
                    else
                    {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Espera!", Message = "Debes iniciar sesión para acceder a tus listas"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }
                };

                int cantidad = 1;
                this.cmpCantidad.Text = cantidad.ToString();
                btnMas.TouchUpInside += (sender, e) => {
                    cantidad++;
                    this.cmpCantidad.Text = cantidad.ToString();
                };

                btnMenos.TouchUpInside += (sender, e) => {
                    cantidad--;
                    if (cantidad < 1)
                    {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Espera!", Message = "La cantidad minima es 1"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                        cantidad = 1;
                        this.cmpCantidad.Text = cantidad.ToString();
                    }
                    else
                    {
                        this.cmpCantidad.Text = cantidad.ToString();
                    }
                };

                this.btnAceptarCantidad.TouchUpInside += (sender, e) => {
                    try{
                        if (cmpCantidad.Text.Equals(""))
                        {
                            UIAlertView alert = new UIAlertView()
                            {
                                Title = "Espera!", Message = "Debes ingresar la cantidad"
                            };
                            alert.AddButton("Registrar");
                            alert.AddButton("Cancelar");
                            alert.Show();
                        }
                        else
                        {
                            cmpCantidad.ResignFirstResponder();
                            QuantityView.Hidden = true;
                            ls = new ListsService();
                            Person persona = people.ElementAt(0);
                            ls.setUserId(persona.ID.ToString());
                            List <ListsService> tableItems = ls.All();
                            if (tableItems.Count > 0)
                            {
                                this.tblLists.Source = new AddToListsTableSource(tableItems, this, this.producto, int.Parse(cmpCantidad.Text));
                                ListsView.Add(this.tblLists);
                                this.tblLists.ReloadData();
                                ListsView.Hidden = false;
                                cmpCantidad.Text = "";
                            }
                            else
                            {
                                UIAlertView alert = new UIAlertView()
                                {
                                    Title = "No tienes listas", Message = "No tienes listas registradas, porfavor ve a \"Mis listas\" para crear una nueva"
                                };
                                alert.AddButton("Registrar");
                                alert.AddButton("Cancelar");
                                alert.Show();
                            }
                        }
                    }catch (System.FormatException ex) {
                        Console.WriteLine(ex.ToString());
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Espera!", Message = "Debes ingresar solo números"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                        QuantityView.Hidden = false;
                    }catch (System.Net.WebException) {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Ups :S", Message = "Algo salio mal,no se pudieron cargar tus listas, verifica tu conexión a internet e inténtalo de nuevo"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }catch (System.Exception ext) {
                        Console.WriteLine(ext.ToString());
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Ups :S", Message = "Ocurrió un problema, inténtalo de nuevo"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }
                };

                btnCerrarLista.TouchUpInside += (sender, e) => {
                    ListsView.Hidden = true;
                };

                btnBadPrice.TouchUpInside += (sender, e) => {
                    if (MainView.userId != 0)
                    {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Gracias por su reporte", Message = "Estamos revisando constantemente los precios de los productos y le agradecemos su aportación, ¿le gustaría reportar el precio de este producto para su revision?"
                        };
                        alert.AddButton("SI");
                        alert.AddButton("NO");
                        alert.Clicked += (s, o) => {
                            try{
                                if (o.ButtonIndex == 0)
                                {
                                    ReportService report    = new ReportService();
                                    String        respuesta = report.SetData(MainView.userId.ToString(), this.producto.id, this.producto.tienda_id, this.producto.precio);
                                    if (respuesta.Equals("\"correct\""))
                                    {
                                        UIAlertView alert2 = new UIAlertView()
                                        {
                                            Title = "Muchas gracias!", Message = "En FixBuy estamos comprometidos con ofrecer siempre la informacion correcta, muchas gracias por tu reporte =)"
                                        };
                                        alert2.AddButton("Aceptar");
                                        alert2.Show();
                                    }
                                    else
                                    {
                                        UIAlertView alert3 = new UIAlertView()
                                        {
                                            Title = "UPS :S", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo"
                                        };
                                        alert3.AddButton("Aceptar");
                                        alert3.Show();
                                    }
                                }
                            }catch (System.Net.WebException) {
                                UIAlertView alerta = new UIAlertView()
                                {
                                    Title = "UPS :S", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo"
                                };
                                alerta.AddButton("Aceptar");
                                alerta.Show();
                            }catch (Exception) {
                                UIAlertView alerta = new UIAlertView()
                                {
                                    Title = "UPS :S", Message = "Algo salio mal, por favor intentalo de nuevo"
                                };
                                alerta.AddButton("Aceptar");
                                alerta.Show();
                            }
                        };
                        alert.Show();
                    }
                    else
                    {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Espera!", Message = "Debes iniciar sesión para poder reportar el precio incorrecto"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }
                };

                btnFacebook.TouchUpInside += (sender, e) => {
                    try{
                        if (MainView.isWithFacebook == true)
                        {
                            UIAlertView alert = new UIAlertView()
                            {
                                Title = "Quieres publicar este producto?", Message = "Deseas publicar este producto en tu perfil de Facebook?"
                            };
                            alert.AddButton("Aceptar");
                            alert.AddButton("Cancelar");
                            alert.Clicked += (s, o) => {
                                if (o.ButtonIndex == 0)
                                {
                                    var post = new NSMutableDictionary();
                                    if (data != null)
                                    {
                                        post.Add(new NSString("message"), new NSString(producto.imagen + "\t" + producto.nombre + "\t(" + producto.descripcion + ")" + "\nGracias a FixBuy encontre mi producto =D"));
                                    }
                                    else
                                    {
                                        post.Add(new NSString("message"), new NSString(producto.nombre + "\t(" + producto.descripcion + ")" + "\nGracias a FixBuy encontre mi producto =D "));
                                    }
                                    // Ask for publish_actions permissions in context
                                    if (!FBSession.ActiveSession.Permissions.Contains("publish_actions"))
                                    {
                                        // No permissions found in session, ask for it
                                        FBSession.ActiveSession.RequestNewPublishPermissions(new [] { "publish_actions" }, FBSessionDefaultAudience.Friends, (session, error) => {
                                            if (error != null)
                                            {
                                                InvokeOnMainThread(() => new UIAlertView("Ups =S", "Ocurrio un error intentalo de nuevo", null, "Aceptar", null).Show());
                                            }
                                            else
                                            {
                                                // If permissions granted, publish the story
                                                FBRequestConnection.StartWithGraphPath("me/feed", post, "POST", (connection, result, err) => {
                                                    if (err != null)
                                                    {
                                                        InvokeOnMainThread(() => new UIAlertView("Ups =S", "Ocurrio un error intentalo de nuevo", null, "Aceptar", null).Show());
                                                    }
                                                    else
                                                    {
                                                        HelloId = (result as FBGraphObject)["id"] as NSString;
                                                        InvokeOnMainThread(() => new UIAlertView("Producto publicado =)", "El producto que FixBuy te ayudo a encontrar a sido publicado en tu biografia =)", null, "Aceptar", null).Show());
                                                    }
                                                });
                                            }
                                        });
                                    }
                                    else
                                    {
                                        // If permissions is found, publish the story
                                        FBRequestConnection.StartWithGraphPath("me/feed", post, "POST", (connection, result, err) => {
                                            if (err != null)
                                            {
                                                InvokeOnMainThread(() => new UIAlertView("Ups =S", "Ocurrio un error intentalo de nuevo", null, "Ok", null).Show());
                                            }
                                            else
                                            {
                                                HelloId = (result as FBGraphObject)["id"] as NSString;
                                                InvokeOnMainThread(() => new UIAlertView("Producto publicado =)", "El producto que FixBuy te ayudo a encontrar a sido publicado en tu biografia =)", null, "Aceptar", null).Show());
                                            }
                                        });
                                    }
                                }
                            };
                            alert.Show();
                        }
                        else
                        {
                            InvokeOnMainThread(() => new UIAlertView("No has entrado a Facebook", "Debes iniciar sesion en Facebook para poder publicar tu producto, por favor regresa a la pantalla inicial para iniciar sesion en Facebook", null, "Aceptar", null).Show());
                        }
                    }catch (Exception exc) {
                        Console.WriteLine("UPS: " + exc.ToString());
                    }
                    //Console.WriteLine(HelloId.ToString());
                };

                btnNuevaLista.TouchUpInside += (sender, e) => {
                    this.NewListView.Hidden = false;
                };

                btnAceptarNuevaLista.TouchUpInside += (sender, e) => {
                    try{
                        if (cmpNewList.Text == "")
                        {
                            UIAlertView alert = new UIAlertView()
                            {
                                Title = "Espera!", Message = "Debes ingresar el nombre de la lista"
                            };
                            alert.AddButton("Aceptar");
                            alert.Show();
                        }
                        else
                        {
                            nls = new NewListService();
                            String respuesta = nls.SetListData(cmpNewList.Text, MainView.userId.ToString());
                            if (respuesta.Equals("\"lista ya existe\""))
                            {
                                UIAlertView alert = new UIAlertView()
                                {
                                    Title = "Ups :S", Message = "Ese nombre de lista ya se encuentra registrado"
                                };
                                alert.AddButton("Aceptar");
                                alert.Show();
                                //cmpNewList.Hidden = true;
                                cmpNewList.Text = "";
                                cmpNewList.ResignFirstResponder();
                            }
                            else
                            {
                                UIAlertView alert = new UIAlertView()
                                {
                                    Title = "Lista creada", Message = "Tu nueva lista \"" + cmpNewList.Text + "\" ha sido creada =D"
                                };
                                alert.AddButton("Aceptar");
                                alert.Show();
                                ls = new ListsService();
                                ls.setUserId(MainView.userId.ToString());
                                List <ListsService> items = ls.All();
                                this.tblLists.Source = new AddToListsTableSource(items, this, producto, 1);
                                this.tblLists.ReloadData();
                                cmpNewList.Text    = "";
                                NewListView.Hidden = true;
                                cmpNewList.ResignFirstResponder();
                            }
                        }
                    }catch (System.Net.WebException) {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Ups =S", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }catch (Exception exc) {
                        Console.WriteLine(exc.ToString());
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Ups =S", Message = "Algo salio mal, por favor intentalo de nuevo"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }
                };

                btnCerrarNombreNL.TouchUpInside += (sender, e) => {
                    this.NewListView.Hidden = true;
                    this.cmpNewList.ResignFirstResponder();
                };
            }catch (Exception e) {
                Console.WriteLine(e.ToString());
                UIAlertView alert = new UIAlertView()
                {
                    Title = "Ups =S", Message = "Algo salio mal, por favor intentalo de nuevo."
                };
                alert.AddButton("Aceptar");
                alert.Show();
            }

            try{
                //Registramos la visita al producto en la aplicacion web
                RegisterVisit(producto.tienda_id, MainView.userId);
            }
            catch (Exception) {
                /*Atrapamos la excepcion en caso de que el registro de la visita no pueda hacerse
                 * sin mostrar ningun mensaje ni detener el flujo de la aplicacion*/
            }

            try{
                //Leemos el servicio de los banners
                this.bannersService = new BannersService();
                banners             = bannersService.All();
            } catch (System.Net.WebException) {
                UIAlertView alert = new UIAlertView()
                {
                    Title = "UPS :S", Message = "Hubo un error al conectarse a internet la seccion de banners no puede mostrarse, por favor verifica tu conexión a internet"
                };
                alert.AddButton("Aceptar");
                alert.Show();
            }

            button = new UIButton(new CGRect(0, 0, bannerImage.Bounds.Width, bannerImage.Bounds.Height));
            bannerImage.Add(button);
            button.TouchUpInside += (sender, e) => {
                try{
                    if (bannerError == false)
                    {
                        if (element.imagen != "")
                        {
                            NSUrl url = new NSUrl(element.link);
                            UIApplication.SharedApplication.OpenUrl(url);
                        }
                    }
                }catch (Exception) {
                    //solo atrapamos la excepcion, no hacemos nada
                }
            };
        }
Esempio n. 3
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			try{
				UIBarButtonItem home = new UIBarButtonItem();
				home.Style = UIBarButtonItemStyle.Plain;
				home.Target = this;
				home.Image = UIImage.FromFile("Images/home.png");
				this.NavigationItem.RightBarButtonItem = home;
				UIViewController[] vistas = NavigationController.ViewControllers;
				home.Clicked += (sender, e) => {
					this.NavigationController.PopToViewController(vistas[0], true);
				};
					
				//Configuramos la vista popup de nueva lista
				NewListView.Layer.BorderWidth = 1.0f;
				NewListView.Layer.BorderColor = UIColor.Black.CGColor;
				NewListView.Layer.CornerRadius = 8;
				tblLists.Add(this.NewListView);
				NewListView.Hidden = true;
				//Configuramos la vista popup de cantidad
				QuantityView.Layer.BorderWidth = 1.0f;
				QuantityView.Layer.BorderColor = UIColor.Black.CGColor;
				QuantityView.Layer.CornerRadius = 8;
				this.Add(QuantityView);
				QuantityView.Hidden = true;

				//Configuramos la vista de popup de listas
				ListsView.Layer.BorderWidth = 1.0f;
				ListsView.Layer.BorderColor = UIColor.Black.CGColor;
				ListsView.Layer.CornerRadius = 8;
				this.Add(this.ListsView);
				ListsView.Hidden = true;

				if(UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone){
					this.btnMapa.SetBackgroundImage(Images.mapa,UIControlState.Normal);
				}else{
					this.btnMapa.SetBackgroundImage(Images.mapa,UIControlState.Normal);
				}

				this.btnMapa.TouchUpInside += (sender, e) => {
					SecondMapViewController mapView = new SecondMapViewController();
					mapView.setTienda(this.producto);
					NavigationController.PushViewController(mapView,true);
				};

				var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
				_pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

				//Hacemos la conexion a la bd para buscar si hay un usuario registrado
				using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
				{
					people = new List<Person> (from p in db.Table<Person> () select p);
				}

				NSUrl nsUrl = new NSUrl (producto.imagen);
				data = NSData.FromUrl (nsUrl);
				if(data!= null){
					Images.imagenDetalle = UIImage.LoadFromData(data);
					this.imgProducto.Image = Images.imagenDetalle;
				}else{
					this.imgProducto.Image = Images.sinImagen;
				}
					
				//Establecemos la informacion del producto
				this.lblNombre.Text = producto.nombre;
				double precio = Double.Parse(producto.precio);
				this.lblPrecio.Text = precio.ToString("C2");
				this.lblDescripcion.Text = producto.descripcion;
				if(UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone){
					this.lblDescripcion.Font = UIFont.SystemFontOfSize(10);
				}else{
					this.lblDescripcion.Font = UIFont.SystemFontOfSize(25);
				}
				//Establecemos la informacion de la tienda
				NSUrl nsurl = new NSUrl(producto.tienda_imagen);
				NSData data1 = NSData.FromUrl(nsurl);
				if(data1 != null){
					Images.imagenDetalleTienda = UIImage.LoadFromData(data1);
					this.imgTienda.Image = Images.imagenDetalleTienda;
				}else{
					this.imgTienda.Image = Images.sinImagen;
				}
				this.lblTiendaNombre.Text = producto.tienda_nombre;
				this.lblTiendaDireccion.Text = producto.tienda_direccion + "\n \nTeléfono: " + producto.tienda_telefono;
				if(distancia != 0){
					this.lblTiendaDistancia.Text = "A "+ Math.Round(distancia,2)+"km de tu ubicación";
				}else{
					this.lblTiendaDistancia.Text = "Distancia no disponible";
				}
				this.lblVigencia.Text = "Vigencia del "+ producto.inicio_validez+ " Al "+ producto.final_validez;
			
				this.btnLista.TouchUpInside += (sender, e) => {
					if(people.Count > 0){
						UIAlertView alert = new UIAlertView () { 
							Title = "Añadir a mi lista", Message = "¿Deseas añadir este producto a una de tus listas?"
						};
						alert.AddButton("Añadir");
						alert.AddButton ("Cancelar");
						alert.Show();
						alert.Clicked += (s, o) => {
							if(o.ButtonIndex == 0){
								QuantityView.Hidden = false;
							}
						};
					}else{
						UIAlertView alert = new UIAlertView () { 
							Title = "Espera!", Message = "Debes iniciar sesión para acceder a tus listas"
						};
						alert.AddButton("Aceptar");
						alert.Show();
					}
				};

				int cantidad = 1;
				this.cmpCantidad.Text = cantidad.ToString();
				btnMas.TouchUpInside += (sender, e) => {
					cantidad ++;
					this.cmpCantidad.Text = cantidad.ToString();
				};

				btnMenos.TouchUpInside += (sender, e) => {
					cantidad --;
					if(cantidad < 1){
						UIAlertView alert = new UIAlertView () { 
							Title = "Espera!", Message = "La cantidad minima es 1"
						};
						alert.AddButton("Aceptar");
						alert.Show();
						cantidad = 1;
						this.cmpCantidad.Text = cantidad.ToString();
					}else{
						this.cmpCantidad.Text = cantidad.ToString();
					}
				};

				this.btnAceptarCantidad.TouchUpInside += (sender, e) => {
					try{
						if(cmpCantidad.Text.Equals("")){
							UIAlertView alert = new UIAlertView () { 
								Title = "Espera!", Message = "Debes ingresar la cantidad"
							};
							alert.AddButton("Registrar");
							alert.AddButton ("Cancelar");
							alert.Show();
						} else{
							cmpCantidad.ResignFirstResponder();
							QuantityView.Hidden = true;
							ls = new ListsService();
							Person persona = people.ElementAt(0);
							ls.setUserId (persona.ID.ToString());
							List<ListsService> tableItems = ls.All (); 
							if(tableItems.Count > 0){
								this.tblLists.Source = new AddToListsTableSource (tableItems, this,this.producto,int.Parse(cmpCantidad.Text));
								ListsView.Add(this.tblLists);
								this.tblLists.ReloadData();
								ListsView.Hidden = false;
								cmpCantidad.Text = "";
							}else{
								UIAlertView alert = new UIAlertView () { 
									Title = "No tienes listas", Message = "No tienes listas registradas, porfavor ve a \"Mis listas\" para crear una nueva"
								};
								alert.AddButton("Registrar");
								alert.AddButton ("Cancelar");
								alert.Show();
							}
						}
					}catch(System.FormatException ex ){
						Console.WriteLine(ex.ToString());
						UIAlertView alert = new UIAlertView () { 
							Title = "Espera!", Message = "Debes ingresar solo números"
						};
						alert.AddButton("Aceptar");
						alert.Show();
						QuantityView.Hidden = false;
					}catch(System.Net.WebException){
						UIAlertView alert = new UIAlertView () { 
							Title = "Ups :S", Message = "Algo salio mal,no se pudieron cargar tus listas, verifica tu conexión a internet e inténtalo de nuevo"
						};
						alert.AddButton("Aceptar");
						alert.Show();
					}catch(System.Exception ext){
						Console.WriteLine(ext.ToString());
						UIAlertView alert = new UIAlertView () { 
							Title = "Ups :S", Message = "Ocurrió un problema, inténtalo de nuevo"
						};
						alert.AddButton("Aceptar");
						alert.Show();
					}
				};

				btnCerrarLista.TouchUpInside += (sender, e) => {
					ListsView.Hidden = true;
				};

				btnBadPrice.TouchUpInside += (sender, e) => {
					if (MainView.userId != 0) {
						UIAlertView alert = new UIAlertView () { 
							Title = "Gracias por su reporte", Message = "Estamos revisando constantemente los precios de los productos y le agradecemos su aportación, ¿le gustaría reportar el precio de este producto para su revision?"
						} ;
						alert.AddButton ("SI");
						alert.AddButton ("NO");
						alert.Clicked += (s , o) => {
							try{
								if(o.ButtonIndex == 0){
									ReportService report = new ReportService();
									String respuesta = report.SetData(MainView.userId.ToString(),this.producto.id,this.producto.tienda_id,this.producto.precio);
									if (respuesta.Equals("\"correct\"")){
										UIAlertView alert2 = new UIAlertView () { 
											Title = "Muchas gracias!", Message = "En FixBuy estamos comprometidos con ofrecer siempre la informacion correcta, muchas gracias por tu reporte =)"
										} ;
										alert2.AddButton ("Aceptar");
										alert2.Show ();
									}else{
										UIAlertView alert3 = new UIAlertView () { 
											Title = "UPS :S", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo"
										} ;
										alert3.AddButton ("Aceptar");
										alert3.Show ();
									}
								}
							}catch(System.Net.WebException){
								UIAlertView alerta = new UIAlertView () { 
									Title = "UPS :S", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo"
								} ;
								alerta.AddButton ("Aceptar");
								alerta.Show ();
							}catch(Exception){
								UIAlertView alerta = new UIAlertView () { 
									Title = "UPS :S", Message = "Algo salio mal, por favor intentalo de nuevo"
								} ;
								alerta.AddButton ("Aceptar");
								alerta.Show ();
							}
						};
						alert.Show ();
					}  else {
						UIAlertView alert = new UIAlertView () { 
							Title = "Espera!", Message = "Debes iniciar sesión para poder reportar el precio incorrecto"
						} ;
						alert.AddButton ("Aceptar");
						alert.Show ();
					}
				};

				btnFacebook.TouchUpInside += (sender, e) => {
					try{
					if(MainView.isWithFacebook == true){
						UIAlertView alert = new UIAlertView () { 
								Title = "Quieres publicar este producto?", Message = "Deseas publicar este producto en tu perfil de Facebook?"
						} ;
						alert.AddButton ("Aceptar");
						alert.AddButton("Cancelar");
							alert.Clicked += (s , o) => {
								if(o.ButtonIndex == 0){
									var post = new NSMutableDictionary ();
									if(data != null){
										post.Add (new NSString ("message"), new NSString (producto.imagen+ "\t"+producto.nombre+ "\t("+producto.descripcion+")" + "\nGracias a FixBuy encontre mi producto =D"));
									}else{
										post.Add (new NSString ("message"), new NSString (producto.nombre + "\t("+producto.descripcion+")" + "\nGracias a FixBuy encontre mi producto =D "));
									}
									// Ask for publish_actions permissions in context
									if (!FBSession.ActiveSession.Permissions.Contains ("publish_actions")) {
										// No permissions found in session, ask for it
										FBSession.ActiveSession.RequestNewPublishPermissions (new [] { "publish_actions" }, FBSessionDefaultAudience.Friends, (session, error) => {
											if (error != null) 
												InvokeOnMainThread (() => new UIAlertView ("Ups =S", "Ocurrio un error intentalo de nuevo", null, "Aceptar", null).Show ());
											else {
												// If permissions granted, publish the story
												FBRequestConnection.StartWithGraphPath ("me/feed", post, "POST", (connection, result, err) => {
													if (err != null)
														InvokeOnMainThread (() => new UIAlertView ("Ups =S", "Ocurrio un error intentalo de nuevo", null, "Aceptar", null).Show ());
													else {
														HelloId = (result as FBGraphObject)["id"] as NSString;
														InvokeOnMainThread (() => new UIAlertView ("Producto publicado =)", "El producto que FixBuy te ayudo a encontrar a sido publicado en tu biografia =)", null, "Aceptar", null).Show ());
													}
												});
											}
										});
									} else {
										// If permissions is found, publish the story
										FBRequestConnection.StartWithGraphPath ("me/feed", post, "POST", (connection, result, err) => {
											if (err != null)
												InvokeOnMainThread (() => new UIAlertView ("Ups =S", "Ocurrio un error intentalo de nuevo", null, "Ok", null).Show ());
											else {
												HelloId = (result as FBGraphObject)["id"] as NSString;
												InvokeOnMainThread (() => new UIAlertView ("Producto publicado =)", "El producto que FixBuy te ayudo a encontrar a sido publicado en tu biografia =)", null, "Aceptar", null).Show ());
											}
										});
									}
								}
							};
						alert.Show ();
					}else{
						InvokeOnMainThread (() => new UIAlertView ("No has entrado a Facebook", "Debes iniciar sesion en Facebook para poder publicar tu producto, por favor regresa a la pantalla inicial para iniciar sesion en Facebook", null, "Aceptar", null).Show ());
					}
					}catch(Exception exc){
						Console.WriteLine("UPS: " + exc.ToString());
					}
					//Console.WriteLine(HelloId.ToString());
				};

				btnNuevaLista.TouchUpInside += (sender, e) => {
					this.NewListView.Hidden = false;
				};

				btnAceptarNuevaLista.TouchUpInside += (sender, e) => {
					try{
						if(cmpNewList.Text == ""){
							UIAlertView alert = new UIAlertView () { 
								Title = "Espera!", Message = "Debes ingresar el nombre de la lista"
							};
							alert.AddButton("Aceptar");
							alert.Show ();
						}else{
							nls = new NewListService();
							String respuesta = nls.SetListData(cmpNewList.Text, MainView.userId.ToString());
							if(respuesta.Equals("\"lista ya existe\"")){
								UIAlertView alert = new UIAlertView () { 
									Title = "Ups :S", Message = "Ese nombre de lista ya se encuentra registrado"
								};
								alert.AddButton("Aceptar");
								alert.Show ();
								//cmpNewList.Hidden = true;
								cmpNewList.Text = "";
								cmpNewList.ResignFirstResponder();
							}else{
								UIAlertView alert = new UIAlertView () { 
									Title = "Lista creada", Message = "Tu nueva lista \""+cmpNewList.Text+"\" ha sido creada =D"
								};
								alert.AddButton("Aceptar");
								alert.Show ();
								ls = new ListsService();
								ls.setUserId(MainView.userId.ToString());
								List<ListsService> items = ls.All ();
								this.tblLists.Source = new AddToListsTableSource(items,this,producto,1);
								this.tblLists.ReloadData();
								cmpNewList.Text = "";
								NewListView.Hidden = true;
								cmpNewList.ResignFirstResponder();
							}
						}
					}catch(System.Net.WebException){
						UIAlertView alert = new UIAlertView () { 
							Title = "Ups =S", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo"
						};
						alert.AddButton("Aceptar");
						alert.Show ();
					}catch(Exception exc){
						Console.WriteLine(exc.ToString());
						UIAlertView alert = new UIAlertView () { 
							Title = "Ups =S", Message = "Algo salio mal, por favor intentalo de nuevo"
						};
						alert.AddButton("Aceptar");
						alert.Show ();
					}
				};

				btnCerrarNombreNL.TouchUpInside += (sender, e) => {
					this.NewListView.Hidden = true;
					this.cmpNewList.ResignFirstResponder();
				};

			}catch(Exception e){
				Console.WriteLine (e.ToString());
				UIAlertView alert = new UIAlertView () { 
					Title = "Ups =S", Message = "Algo salio mal, por favor intentalo de nuevo."
				};
				alert.AddButton("Aceptar");
				alert.Show ();
			}

			try{
				//Registramos la visita al producto en la aplicacion web
				RegisterVisit(producto.tienda_id,MainView.userId);
			}
			catch(Exception){
				/*Atrapamos la excepcion en caso de que el registro de la visita no pueda hacerse
				sin mostrar ningun mensaje ni detener el flujo de la aplicacion*/
			}

			try{
				//Leemos el servicio de los banners
				this.bannersService = new BannersService ();
				banners = bannersService.All ();
			} catch (System.Net.WebException){
				UIAlertView alert = new UIAlertView () { 
					Title = "UPS :S", Message = "Hubo un error al conectarse a internet la seccion de banners no puede mostrarse, por favor verifica tu conexión a internet"
				};
				alert.AddButton("Aceptar");
				alert.Show ();
			}

			button = new UIButton (new CGRect (0, 0, bannerImage.Bounds.Width, bannerImage.Bounds.Height));
			bannerImage.Add (button);
			button.TouchUpInside += (sender, e) => {
				try{
					if(bannerError == false){
						if(element.imagen != ""){
							NSUrl url = new NSUrl (element.link);
							UIApplication.SharedApplication.OpenUrl (url);
						}
					}
				}catch(Exception){
					//solo atrapamos la excepcion, no hacemos nada
				}
			};
		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            try{
                var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                _pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

                using (var db = new SQLite.SQLiteConnection(_pathToDatabase))
                {
                    people = new List <Person> (from p in db.Table <Person> () select p);
                }

                //inicializacion del manejador de localizacion.
                iPhoneLocationManager = new CLLocationManager();
                //Establecer la precision del manejador de localizacion.
                iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

                iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    newLocation = e.Locations [e.Locations.Length - 1];
                };

                productSearchDetailService.setProductBarcode(this.barcode, MainView.localityId.ToString(), MainView.userId);
                List <ProductSearchDetailService> tableItems = productSearchDetailService.All();

                this.productImages.Clear();
                foreach (var v in tableItems)
                {
                    Images image = new Images {
                        storeImageUrl = v.imagen
                    };
                    this.productImages.Add(image);
                }

                UIBarButtonItem home = new UIBarButtonItem();
                home.Style  = UIBarButtonItemStyle.Plain;
                home.Target = this;
                home.Image  = UIImage.FromFile("Images/home.png");
                this.NavigationItem.RightBarButtonItem = home;
                UIViewController[] vistas = NavigationController.ViewControllers;
                home.Clicked += (sender, e) => {
                    this.NavigationController.PopToViewController(vistas[0], true);
                };

                btnTiendaCercana.TouchUpInside += (sender, e) => {
                    try{
                        ProductSearchDetailService tiendac = nearestStore(newLocation, tableItems);
                        double distancia = newLocation.DistanceFrom(new CLLocation(Double.Parse(tiendac.tienda_latitud), Double.Parse(tiendac.tienda_longitud))) / 1000;
                        distancia = Math.Round(distancia, 2);
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Tu tienda mas cercana es:", Message = "" + tiendac.tienda_nombre + "\n " + tiendac.tienda_direccion + "\n" + "Distancia: " + distancia.ToString() + "km"
                        };
                        alert.AddButton("Aceptar");
                        alert.AddButton("Mapa");
                        alert.Clicked += (s, o) => {
                            if (o.ButtonIndex == 1)
                            {
                                SecondMapViewController mapView = new SecondMapViewController();
                                mapView.setTienda(tiendac);
                                this.NavigationController.PushViewController(mapView, true);
                            }
                        };
                        alert.Show();
                    }catch (NullReferenceException) {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Lo Sentimos =(", Message = "FixBuy no pudo obtener tu ubicación por favor ve a Ajustes/Privacidad/Localizacion y verifica que Fixbuy tenga permiso de saber tu ubicación"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }
                };

                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    if (CLLocationManager.LocationServicesEnabled)
                    {
                        this.tblStores.Source = new StoresTableSourceIphone(tableItems, this, iPhoneLocationManager, people.Count);
                    }
                    else
                    {
                        this.tblStores.Source = new StoresTableSourceIphone(tableItems, this, null, people.Count);
                    }
                }
                else
                {
                    if (CLLocationManager.LocationServicesEnabled)
                    {
                        this.tblStores.Source = new StoresTableSource(tableItems, this, iPhoneLocationManager, people.Count);
                    }
                    else
                    {
                        this.tblStores.Source = new StoresTableSource(tableItems, this, null, people.Count);
                    }
                }

                ProductSearchDetailService product = tableItems.ElementAt(0);
                NSUrl  nsUrl = new NSUrl(product.imagen);
                NSData data  = NSData.FromUrl(nsUrl);
                if (data != null)
                {
                    this.imgProduct.Image = UIImage.LoadFromData(data);
                }
                else
                {
                    this.imgProduct.Image = Images.sinImagen;
                }
                this.lblproduct.Text     = product.nombre;
                this.lblDescription.Text = product.descripcion;
                //this.tblStores.TableHeaderView = this.headerView;
                Add(this.tblStores);

                // Manejamos la actualizacion de la localizacion del dispositivo.
                iPhoneLocationManager.RequestAlwaysAuthorization();
                if (CLLocationManager.LocationServicesEnabled)
                {
                    iPhoneLocationManager.StartUpdatingLocation();
                }
            }catch (System.ArgumentOutOfRangeException) {
                didNotFidProduct();
            }catch (Exception ex) {
                Console.WriteLine("ESTA ES LA EXCEPCION: " + ex.ToString());
                this.imgProduct.Image          = UIImage.FromFile("Images/noImage.jpg");
                this.lblproduct.Text           = "Producto no encontrado =S";
                this.lblDescription.Text       = "";
                this.btnTiendaCercana.Hidden   = true;
                this.tblStores.BackgroundColor = UIColor.Clear;
                UIAlertView alert = new UIAlertView()
                {
                    Title = "Ups =(", Message = "Lo sentimos algo salio mal, por favor intentalo de nuevo"
                };
                alert.AddButton("Aceptar");
                alert.Show();
            }
        }
			public UIView getDistanceView(int index){
				botones.ElementAt(index).Frame = new CGRect (0, 0, Images.mapa.Size.Width, Images.mapa.Size.Height);
				botones.ElementAt(index).SetBackgroundImage (Images.mapa, UIControlState.Normal);
				botones.ElementAt(index).BackgroundColor = UIColor.Clear;
				distancias.ElementAt(index).Frame = new CGRect (0, botones.ElementAt(index).Bounds.Height, 60f, 25f);
				//PointF viewPosition = botones.ElementAt (index).ConvertPointToView (new PointF (), controller.tblStores);
				//NSIndexPath indexPath = controller.tblStores.IndexPathForRowAtPoint (viewPosition);

				Double distance = location.Location.DistanceFrom (new CLLocation(Double.Parse(tableItems[index].tienda_latitud),Double.Parse(tableItems[index].tienda_longitud)))/1000;
				distancias.ElementAt(index).Text =  " "+ Math.Round(distance,2)+ "km";
				distancias.ElementAt(index).Font = UIFont.SystemFontOfSize (12);
				vistas.ElementAt(index).Frame = new CGRect (0, 0, distancias.ElementAt(index).Bounds.Width, botones.ElementAt(index).Bounds.Height + distancias.ElementAt(index).Bounds.Height);
				botones.ElementAt(index).TouchUpInside += (sender, e) => {
					SecondMapViewController mapView = new SecondMapViewController();
					mapView.setTienda(tableItems[index]);
					this.controller.NavigationController.PushViewController(mapView, true);
				};
				vistas.ElementAt(index).AddSubview (botones.ElementAt(index));
				vistas.ElementAt(index).AddSubview (distancias.ElementAt(index));
				return vistas.ElementAt(index);
			}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			try{
				var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
				_pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

				using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
				{
					people = new List<Person> (from p in db.Table<Person> () select p);
				}

				//inicializacion del manejador de localizacion.
				iPhoneLocationManager = new CLLocationManager ();
				//Establecer la precision del manejador de localizacion.
				iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

				iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
					newLocation = e.Locations [e.Locations.Length - 1];
				};
					
				productSearchDetailService.setProductBarcode (this.barcode, MainView.localityId.ToString(), MainView.userId);
				List<ProductSearchDetailService> tableItems = productSearchDetailService.All ();

				this.productImages.Clear();
				foreach (var v in tableItems){
					Images image = new Images{ storeImageUrl = v.imagen};
					this.productImages.Add(image);
				}

				UIBarButtonItem home = new UIBarButtonItem();
				home.Style = UIBarButtonItemStyle.Plain;
				home.Target = this;
				home.Image = UIImage.FromFile("Images/home.png");
				this.NavigationItem.RightBarButtonItem = home;
				UIViewController[] vistas = NavigationController.ViewControllers;
				home.Clicked += (sender, e) => {
					this.NavigationController.PopToViewController(vistas[0], true);
				};

				btnTiendaCercana.TouchUpInside += (sender, e) => {
					try{
						ProductSearchDetailService tiendac= nearestStore(newLocation,tableItems);
						double distancia = newLocation.DistanceFrom(new CLLocation(Double.Parse(tiendac.tienda_latitud),Double.Parse(tiendac.tienda_longitud)))/1000;
						distancia = Math.Round(distancia,2);
						UIAlertView alert = new UIAlertView () { 
							Title = "Tu tienda mas cercana es:", Message = ""+ tiendac.tienda_nombre + "\n "+ tiendac.tienda_direccion+"\n"+"Distancia: " + distancia.ToString() +"km"
						};
						alert.AddButton("Aceptar");
						alert.AddButton("Mapa");
						alert.Clicked += (s , o) => {
							if(o.ButtonIndex == 1){
								SecondMapViewController mapView = new SecondMapViewController();
								mapView.setTienda(tiendac);
								this.NavigationController.PushViewController(mapView, true);
							}
						};
						alert.Show ();
					}catch(NullReferenceException){
						UIAlertView alert = new UIAlertView () { 
							Title = "Lo Sentimos =(", Message = "FixBuy no pudo obtener tu ubicación por favor ve a Ajustes/Privacidad/Localizacion y verifica que Fixbuy tenga permiso de saber tu ubicación"
						};
						alert.AddButton("Aceptar");
						alert.Show();
					}
				};  

				if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) {
					if (CLLocationManager.LocationServicesEnabled){
						this.tblStores.Source = new StoresTableSourceIphone (tableItems, this, iPhoneLocationManager,people.Count);
					}else{
						this.tblStores.Source = new StoresTableSourceIphone (tableItems, this, null,people.Count);
					}
				} else {
					if (CLLocationManager.LocationServicesEnabled){
						this.tblStores.Source = new StoresTableSource (tableItems, this, iPhoneLocationManager,people.Count);
					}else{
						this.tblStores.Source = new StoresTableSource (tableItems, this, null,people.Count);
					}
				}

				ProductSearchDetailService product = tableItems.ElementAt (0);
				NSUrl nsUrl = new NSUrl (product.imagen);
				NSData data = NSData.FromUrl (nsUrl);
				if(data!=null){
					this.imgProduct.Image = UIImage.LoadFromData (data);
				}else{
					this.imgProduct.Image = Images.sinImagen;
				}
				this.lblproduct.Text = product.nombre;
				this.lblDescription.Text = product.descripcion;
				//this.tblStores.TableHeaderView = this.headerView;
				Add (this.tblStores);

				// Manejamos la actualizacion de la localizacion del dispositivo.
				iPhoneLocationManager.RequestAlwaysAuthorization ();
				if (CLLocationManager.LocationServicesEnabled)
					iPhoneLocationManager.StartUpdatingLocation ();


			}catch(System.ArgumentOutOfRangeException){
				didNotFidProduct();
			}catch(Exception ex){
				Console.WriteLine ("ESTA ES LA EXCEPCION: " + ex.ToString ());
				this.imgProduct.Image = UIImage.FromFile("Images/noImage.jpg");
				this.lblproduct.Text = "Producto no encontrado =S";
				this.lblDescription.Text = "";
				this.btnTiendaCercana.Hidden = true;
				this.tblStores.BackgroundColor = UIColor.Clear;
				UIAlertView alert = new UIAlertView () { 
					Title = "Ups =(", Message = "Lo sentimos algo salio mal, por favor intentalo de nuevo"
				};
				alert.AddButton ("Aceptar");
				alert.Show ();
			} 
		}