public class MovieActivity extends BaseActivity {

    final int STATUS_IMAGES = 1;
    final int STATUS_VIDEOS = 2;
    int status = STATUS_IMAGES;
    MovieFragment fragment;
    boolean afficheCasting = false;
    boolean afficheCinemas = false;
    Menu menu;

    boolean recherche = false;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.adView)
    AdView adView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie);
        ButterKnife.bind(this);

        Analytics.screen("movie");

        getAdsManager().executeAdView(adView);

        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(Color.WHITE);
        getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.ab_back_mtrl_am_alpha));

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.ab_back_mtrl_am_alpha));

        Intent intent = getIntent();
        String title = intent.getStringExtra(MovieFragment.ACTIONBAR_TITLE);
        String jsonMovie = intent.getStringExtra(MovieFragment.MOVIE);
        fragment = MovieFragment.newInstance(title, jsonMovie);

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragmentLayout, fragment)
                .commitAllowingStateLoss();

        invalidateOptionsMenu();

    }


    public void afficherCasting() {
        afficheCasting = true;
        invalidateOptionsMenu();
    }

    public void afficherCinemas() {
        afficheCinemas = true;
        invalidateOptionsMenu();
    }

    private void chargerFavoris() {
        AccessBaseFavoris db = new AccessBaseFavoris(this);
        db.open();

        if (fragment != null && fragment.getMovie() != null && db.isFavoris(fragment.getMovie().getCode() + "", BaseFavoris.TYPE_FAVORIS_FILM)) {
            menu.getItem(2).setIcon(R.drawable.ic_favoris_on);
        } else
            menu.getItem(2).setIcon(R.drawable.ic_favoris_off);
        db.close();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu = menu;

        if (afficheCasting) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.movie_menu_cinema, menu);

            /*
            final MenuItem searchItem = menu.findItem(R.id.search);
            final SearchView searchView = (SearchView) searchItem.getActionView();
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                public boolean onQueryTextChange(String text) {
                    return false;
                }

                public boolean onQueryTextSubmit(String text) {
                    getSupportActionBar().setTitle(text);

                    fragment.search(text);
                    searchItem.collapseActionView();
                    recherche = true;
                    return false;
                }
            });

            searchView.setOnCloseListener(new SearchView.OnCloseListener() {
                @Override
                public boolean onClose() {
                    //afficherMovieNow();
                    //refreshActionBar();
                    return false;
                }
            });
            */


        } else {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.movie_menu, menu);

            chargerFavoris();


            try {
                switch (status) {
                    case STATUS_IMAGES:
                        menu.getItem(0).setIcon(R.drawable.ic_picture_80);
                        menu.getItem(1).setIcon(R.drawable.ic_bandeannonce_30);
                        break;
                    case STATUS_VIDEOS:
                        menu.getItem(0).setIcon(R.drawable.ic_picture_30);
                        menu.getItem(1).setIcon(R.drawable.ic_bandeannonce_80);
                        break;
                }
            } catch (Exception e) {
            }
        }

        return true;
    }

    public void changerActionBarColor(int color, int textColor) {
        try {
            ActionBar bar = getActionBar();
            bar.setBackgroundDrawable(new ColorDrawable(color));

            int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
            if (actionBarTitleId > 0) {
                TextView title = (TextView) findViewById(actionBarTitleId);
                if (title != null) {
                    title.setTextColor(textColor);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if (afficheCasting) {
            afficheCasting = false;
            fragment.fermerCasting();
            invalidateOptionsMenu();
        } else
            super.onBackPressed();

        recherche = false;
    }


    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.menu_images:
                status = STATUS_IMAGES;
                fragment.afficherImages();
                invalidateOptionsMenu();
                return true;
            case R.id.menu_bandesAnnonces:
                status = STATUS_VIDEOS;
                fragment.afficherBandesAnnonces();
                invalidateOptionsMenu();
                return true;

            case R.id.menu_favoris:
                AccessBaseFavoris db = new AccessBaseFavoris(this);
                db.open();

                if (fragment != null && fragment.getMovie() != null) {

                    if (db.isFavoris(fragment.getMovie().getCode() + "", BaseFavoris.TYPE_FAVORIS_FILM)) {
                        db.deleteFavoris(fragment.getMovie().getCode() + "", BaseFavoris.TYPE_FAVORIS_FILM);
                    } else {
                        db.insertFavoris(fragment.getMovie().getCode() + "", BaseFavoris.TYPE_FAVORIS_FILM);
                    }

                }

                invalidateOptionsMenu();

                db.close();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

} public class StarActivity extends BaseActivity {

    final int STATUS_IMAGES = 1;
    final int STATUS_FILMO = 2;
    int status = STATUS_IMAGES;
    StarFragment fragment;
    Menu menu;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie);
        ButterKnife.bind(this);

        Analytics.screen("star");

        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(Color.WHITE);
        getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.ab_back_mtrl_am_alpha));

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.ab_back_mtrl_am_alpha));

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragmentLayout, fragment = StarFragment.newInstance(getIntent().getStringExtra(StarFragment.PERSON)))
                .commitAllowingStateLoss();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu = menu;
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.star_menu, menu);
        chargerFavoris();

        try {
            switch (status) {
                case STATUS_IMAGES:
                    afficherPhoto();
                    break;
                case STATUS_FILMO:
                    afficherFilmo();
                    break;
            }
        } catch (Exception e) {
        }

        return true;
    }

    private void chargerFavoris() {

        if (fragment != null && fragment.getPerson() != null && fragment.getPerson().getCode() != null) {
            Integer code = fragment.getPerson().getCode();

            AccessBaseFavoris db = new AccessBaseFavoris(this);
            db.open();

            if (db.isFavoris(code + "", BaseFavoris.TYPE_FAVORIS_STAR)) {
                menu.getItem(2).setIcon(R.drawable.ic_favoris_on);
            } else {
                menu.getItem(2).setIcon(R.drawable.ic_favoris_off);
            }

            db.close();
        }
    }

    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                super.onBackPressed();
                return true;
            case R.id.menu_images:
                status = STATUS_IMAGES;
                fragment.afficherPhotos(0);
                invalidateOptionsMenu();
                return true;
            case R.id.menu_filmo:
                status = STATUS_FILMO;
                fragment.afficherFilmosFond();
                invalidateOptionsMenu();
                return true;

            case R.id.menu_favoris:
                AccessBaseFavoris db = new AccessBaseFavoris(this);
                db.open();

                if (fragment != null && fragment.getPerson() != null && fragment.getPerson().getCode() != null) {

                    Integer code = fragment.getPerson().getCode();

                    if (db.isFavoris(code + "", BaseFavoris.TYPE_FAVORIS_STAR)) {
                        db.deleteFavoris(code + "", BaseFavoris.TYPE_FAVORIS_STAR);
                        //Toast.makeText(this,"On supprime",Toast.LENGTH_SHORT).show();
                    } else {
                        db.insertFavoris(code + "", BaseFavoris.TYPE_FAVORIS_STAR);
                        //Toast.makeText(this,"On insere",Toast.LENGTH_SHORT).show();

                    }

                }
                db.close();

                invalidateOptionsMenu();

                return true;
        }
        ;
        return super.onOptionsItemSelected(item);
    }

    public void afficherFilmo() {
        menu.getItem(0).setIcon(R.drawable.ic_picture2_30);
        menu.getItem(1).setIcon(R.drawable.ic_filmo_80);
    }

    public void afficherPhoto() {
        menu.getItem(0).setIcon(R.drawable.ic_picture2_80);
        menu.getItem(1).setIcon(R.drawable.ic_filmo_30);
    }
} public class BandesAnnoncesPagerAdapter extends FragmentStatePagerAdapter {

    final List<Media> bandesAnnonces;
    final OnBandeAnnonceClickedListener listener;
    final Movie movie;
    final boolean theater;
    BitmapDrawable bobine;

    public BandesAnnoncesPagerAdapter(FragmentManager fm, List<Media> bandesAnnonces, Movie movie, OnBandeAnnonceClickedListener listener, boolean theater) {
        super(fm);
        this.bandesAnnonces = bandesAnnonces;
        this.listener = listener;
        this.movie = movie;
        this.theater = theater;

        //bobine = new BitmapDrawable(BitmapFactory.decodeResource(activity.getResources(), R.drawable.pellicule));
        //bobine.setTileModeX(Shader.TileMode.REPEAT);
        //bobine.setTileModeY(Shader.TileMode.CLAMP);
    }

    @Override
    public Fragment getItem(int position) {
        return BandeAnnonceFragment.newInstance(position, bandesAnnonces.get(position), movie, theater).setListener(listener);
    }

    @Override
    public int getCount() {
        return bandesAnnonces.size();
    }

    public interface OnBandeAnnonceClickedListener {
        void onBandeAnnonceClicked(Media bandeAnnonce);
    }

    public static class BandeAnnonceFragment extends Fragment {

        @BindView(R.id.image)
        ImageView image;
        @BindView(R.id.title)
        TextView title;
        private OnBandeAnnonceClickedListener listener;

        public static BandeAnnonceFragment newInstance(int position, Media media, Movie movie, boolean theater) {
            final Bundle args = new Bundle();
            args.putInt("position", position);
            args.putBoolean("theater", theater);
            final Gson gson = new Gson();
            args.putString("media", gson.toJson(media));
            args.putString("movie", gson.toJson(movie));
            final BandeAnnonceFragment fragment = new BandeAnnonceFragment();
            fragment.setArguments(args);
            return fragment;
        }

        public BandeAnnonceFragment setListener(OnBandeAnnonceClickedListener listener) {
            this.listener = listener;
            return this;
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            ButterKnife.bind(this, view);

            final Gson gson = new Gson();
            final Media bandeAnnonce = gson.fromJson(getArguments().getString("media"), Media.class);
            final Movie movie = gson.fromJson(getArguments().getString("movie"), Movie.class);

            String urlImage = bandeAnnonce.getThumbnail().getHref(getContext().getResources().getInteger(R.integer.fragment_movie_bande_annonce_height));
            Picasso.with(getActivity()).load(urlImage).into(image);

                /*
                view.findViewById(R.id.bobineTop).setBackgroundDrawable(bobine);
                view.findViewById(R.id.bobineBottom).setBackgroundDrawable(bobine);
                */


            String titre = bandeAnnonce.getTitle().replace(movie.getTitle(), "").replace(movie.getOriginalTitle(), "").replace("\"\"", "").replace(":", "").trim();
            if (titre.startsWith("-"))
                titre = titre.substring(1, titre.length()).trim();

            title.setText(titre);

            view.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            if (listener != null) {
                                                listener.onBandeAnnonceClicked(bandeAnnonce);
                                            }
                                        }
                                    }
            );
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            if (getArguments().getBoolean("theater"))
                return inflater.inflate(R.layout.bande_annonce_pager_theater, container, false);
            else
                return inflater.inflate(R.layout.bande_annonce_pager_movie, container, false);
        }

    }
} public interface OnBandeAnnonceClickedListener {
    void onBandeAnnonceClicked(Media bandeAnnonce);
} public class ImagesPagerAdapter extends FragmentStatePagerAdapter {

    final List<String> imagesUrl;

    public ImagesPagerAdapter(FragmentManager fm, List<String> imagesUrl) {
        super(fm);
        this.imagesUrl = imagesUrl;
    }

    @Override
    public Fragment getItem(final int position) {
        return ImageFragment.newInstance(imagesUrl.get(position), position);
    }

    @Override
    public int getCount() {
        return imagesUrl.size();
    }

    public static class ImageFragment extends Fragment {
        @BindView(R.id.parallaxContent) PhotoView image;
        String urlImage;

        public static ImageFragment newInstance(String urlImage, int position) {
            Bundle args = new Bundle();
            args.putString("urlImage", urlImage);
            args.putInt("position", position);
            ImageFragment fragment = new ImageFragment();
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            ButterKnife.bind(this, view);

            urlImage = getArguments().getString("urlImage");
            Picasso.with(getContext()).load(urlImage).into(image);

            image.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    new AlertDialog.Builder(getActivity())
                            .setMessage(R.string.message_fond_ecran)
                            .setTitle(R.string.titre_fond_ecran)
                            .setPositiveButton(R.string.oui, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                    new LoadWalpaper().execute();
                                }
                            })
                            .setNegativeButton(R.string.non, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            }).show();

                    return false;
                }
            });
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.image_pager_movie, container, false);
        }

        class LoadWalpaper extends AsyncTask<Object, Void, Void> {

            @Override
            protected Void doInBackground(Object... objects) {

                DisplayMetrics metrics = new DisplayMetrics();
                getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
                int height = metrics.heightPixels;
                int width = metrics.widthPixels;

                WallpaperManager wallpaperManager = WallpaperManager.getInstance(getActivity());
                wallpaperManager.setWallpaperOffsetSteps(1, 1);
                wallpaperManager.suggestDesiredDimensions(width, height);

                try {
                    String urlWalpaper = urlImage.replace("/r_10000_" + getActivity().getResources().getInteger(R.integer.fragment_movie_fond_height), "/r_" + (width) + "_" + (height));
                    wallpaperManager.setStream(new URL(urlWalpaper).openStream());


                     /*   Bitmap bmap2 = BitmapFactory.decodeStream(new URL(urlWalpaper).openStream());

                        DisplayMetrics metrics = new DisplayMetrics();
                        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                        int height = metrics.heightPixels;
                        int width = metrics.widthPixels;
                        Bitmap bitmap = Bitmap.createScaledBitmap(bmap2, width, height, true);
activity.setWallpaper(bitmap);
                           // wallpaperManager.setBitmap(bitmap);
*/

                } catch (Exception e) {
                    if (e.getMessage() != null)
                        e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void v) {
                super.onPostExecute(v);
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), R.string.fond_ecran_change, Toast.LENGTH_LONG).show();
                    }
                });

            }
        }
    }

} public class ObjectAdapter<OBJECT> extends ArrayAdapter<OBJECT> {

    public ObjectAdapterLoadMore listener;
    Context context;
    int layoutId;
    Class cellClass;

    ArrayList<Integer> apparitions = new ArrayList<Integer>();

    public ObjectAdapter(Context context, List<OBJECT> objets, int layoutId, Class<? extends ViewCell> cellClass) {
        super(context, layoutId, objets);
        this.context = context;
        this.layoutId = layoutId;
        this.cellClass = cellClass;

        //this.cells = new ViewCell[this.objects.size()];
    }

    @Override
    public int getCount() {
        int count = 0;
        try {
            count = super.getCount();
        } catch (Exception e) {
        }
        return count;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null)
            view = View.inflate(context, layoutId, null);

        ViewCell cell = null;
        if (view.getTag() != null && view.getTag() instanceof ViewCell)
            cell = (ViewCell) view.getTag();
        if (view.getTag() == null || !(view.getTag() instanceof ViewCell)) {
            try {
                cell = (ViewCell) Class.forName(cellClass.getName()).newInstance();
                cell.construire(context, view);
            } catch (Exception e) {
                e.printStackTrace();
            }
            view.setTag(cell);
        }
        cell.construire((OBJECT) getItem(i), i);


        int apparition = apparaitre(i);
        if (apparition == 1) {
            try {
                cell.animer();
            } catch (Exception e) {
            }
        }

        if (apparition >= 1 && listener != null && getCount() > 4 && i >= (getCount() - 3)) {
            listener.loadMore();
        }

        return view;
    }

    public int apparaitre(int positon) {
        int apparition = apparitions.size() <= positon ? 0 : apparitions.get(positon);
        apparition++;
        apparitions.add(positon, apparition);
        return apparition;
    }

    public interface ObjectAdapterLoadMore {
        public void loadMore();
    }
} public class ObjectAdapterLayout<OBJECT> extends ObjectAdapter<OBJECT> {

    public ObjectAdapterLayout(Context context, List<OBJECT> objets, int layoutId, Class<? extends ViewCell> cellClass, ViewGroup layout) {
        super(context, objets, layoutId, cellClass);

        for (int i = 0; i < getCount(); ++i) {
            try {
                layout.addView(getView(i, null, layout));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
} public class BaseActivity extends AppCompatActivity implements LifecycleRegistryOwner {

    private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
    private AdsManager adsManager;

    public LifecycleRegistry getLifecycle() {
        return this.mRegistry;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adsManager = new AdsManager(this, getLifecycle());
        //if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        //    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        //}
    }

    public AdsManager getAdsManager() {
        return adsManager;
    }

    public MainApplication getApp() {
        return ((MainApplication) getApplication());
    }
} public abstract class BaseFragment extends Fragment implements View.OnClickListener {

    protected View fragmentView;
    boolean tournerRoulette = false;

    public void setFragmentView(View fragmentView) {
        this.fragmentView = fragmentView;
    }

    public View findViewById(int id) {
        if (fragmentView != null)
            return fragmentView.findViewById(id);
        else
            return null;
    }

    protected void charger(){}

    protected void remplir(){}

    protected void ajouterListeners(){}

    public void search(String text) {
    }

    public void afficherVide(boolean afficher) {
        try {
            if (afficher)
                fragmentView.findViewById(R.id.empty).setVisibility(View.VISIBLE);
            else
                fragmentView.findViewById(R.id.empty).setVisibility(View.INVISIBLE);
        } catch (Exception e) {
        }
    }

    protected void tournerRoulette(boolean tourner) {
        tournerRoulette(tourner, R.id.placeholder_image);
    }

    protected void tournerRoulette(boolean tourner, int id) {

        final View roulette = findViewById(id);

        if (roulette != null) {
            if (tourner) {
                roulette.setVisibility(View.VISIBLE);
                int previousDegrees = 0;
                int degrees = 360;
                final RotateAnimation animation = new RotateAnimation(previousDegrees, degrees,
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animation.setFillEnabled(true);
                animation.setFillAfter(true);
                animation.setDuration(1500);//Set the duration of the animation to 1 sec.
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (tournerRoulette) {
                            roulette.startAnimation(animation);
                        } else
                            roulette.animate().alpha(0).start();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                roulette.startAnimation(animation);
            } else {
                tournerRoulette = false;
            }
        }
    }

    public void onErreurReseau() {
        //Crouton.makeText(getActivity(), R.string.erreur_reseau, Style.ALERT).show();
        Toast.makeText(getActivity(), R.string.erreur_reseau, Toast.LENGTH_SHORT).show();
    }
} public class CastMember {

    @Expose
    private PersonSmall person;
    @Expose
    private ModelObject activity;
    @Expose
    private Picture picture;
    @Expose
    private String role;

    public PersonSmall getPerson() {
        return person;
    }

    public void setPerson(PersonSmall person) {
        this.person = person;
    }

    public ModelObject getActivity() {
        return activity;
    }

    public void setActivity(ModelObject activity) {
        this.activity = activity;
    }

    public Picture getPicture() {
        return picture;
    }

    public void setPicture(Picture picture) {
        this.picture = picture;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "CastMember{" +
                "person=" + person +
                ", activity=" + activity +
                ", picture=" + picture +
                ", role='" + role + '\'' +
                '}';
    }
} public class PersonFull extends Person {

    @Expose
    private Name name;

    @Expose
    private List<ModelObject> activity = new ArrayList<ModelObject>();

    public static PersonFull transformFull(PersonSmall person) {
        PersonFull p = new PersonFull();
        p.getActivity().addAll(person.getActivity());

        Log.d("PERSON1", person.toString());

        p.setPicture(person.getPicture());
        p.setCode(person.getCode());
        p.activity.clear();
        p.activity.addAll(person.getActivity());

        p.setStatistics(person.getStatistics());
        Name name = new Name();
        name.setFamily(person.getName());
        p.setName(name);

        Log.d("PERSON2", p.toString());

        return p;
    }

    public static List<PersonFull> transformListFull(List<PersonSmall> persons) {
        List<PersonFull> listFull = new ArrayList<PersonFull>();
        for (PersonSmall p : persons)
            listFull.add(transformFull(p));

        return listFull;
    }

    public List<ModelObject> getActivity() {
        return activity;
    }

    public void setActivity(List<ModelObject> activity) {
        this.activity = activity;
    }

    public Name getFullName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "PersonFull{" +
                "name=" + name +
                super.toString() + "}";
    }

    public String getActivities() {
        String activities = "";
        int i = 0;

        if (this.activity.size() > 0) {

            for (ModelObject act : this.activity) {
                Log.e("Activities", act.get$());
                if (i != 0)
                    activities += " / ";

                activities += act.get$();
                i++;
            }
        } else {
            if (this.getActivityShort() != null) {
                String s = getActivityShort();
                return s.replaceAll(",", "/");
            }
        }

        return activities;
    }
} public class Theater {

    public List<TheaterShowtime> showTimes;
    private List<Horaires> horaires = new ArrayList<Horaires>();
    private Map<String, List<Horaires>> horairesSemaine = new HashMap<String, List<Horaires>>();
    private List<String> horairesSemaineJours = new ArrayList<String>();
    @Expose
    private String code;
    @Expose
    private Double distance;
    @Expose
    private String name;
    @Expose
    private String address;
    @Expose
    private String postalCode;
    @Expose
    private String city;
    @Expose
    private Picture picture;
    @Expose
    private Geoloc geoloc;
    @Expose
    private List<Link> link = new ArrayList<Link>();
    @Expose
    private ModelObject cinemaChain;
    @Expose
    private Integer screenCount;
    @Expose
    private Integer hasPRMAccess;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Double getDistance() {
        return distance;
    }

    public void setDistance(Double distance) {
        this.distance = distance;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Picture getPicture() {
        return picture;
    }

    public void setPicture(Picture picture) {
        this.picture = picture;
    }

    public Geoloc getGeoloc() {
        return geoloc;
    }

    public void setGeoloc(Geoloc geoloc) {
        this.geoloc = geoloc;
    }

    public List<Link> getLink() {
        return link;
    }

    public void setLink(List<Link> link) {
        this.link = link;
    }

    public ModelObject getCinemaChain() {
        return cinemaChain;
    }

    public void setCinemaChain(ModelObject cinemaChain) {
        this.cinemaChain = cinemaChain;
    }

    public Integer getScreenCount() {
        return screenCount;
    }

    public void setScreenCount(Integer screenCount) {
        this.screenCount = screenCount;
    }

    public Integer getHasPRMAccess() {
        return hasPRMAccess;
    }

    public void setHasPRMAccess(Integer hasPRMAccess) {
        this.hasPRMAccess = hasPRMAccess;
    }

    public List<Horaires> getHorraires() {
        return horaires;
    }

    public void setHorraires(List<Horaires> horraires) {
        this.horaires = horraires;
    }

    public Map<String, List<Horaires>> getHorairesSemaine() {
        return horairesSemaine;
    }

    public void setHorairesSemaine(Map<String, List<Horaires>> horairesSemaine) {
        this.horairesSemaine = horairesSemaine;
    }

    public List<Horaires> getHoraires() {
        return horaires;
    }

    public void setHoraires(List<Horaires> horaires) {
        this.horaires = horaires;
    }

    public List<String> getHorairesSemaineJours() {
        return horairesSemaineJours;
    }

    public void setHorairesSemaineJours(List<String> horairesSemaineJours) {
        this.horairesSemaineJours = horairesSemaineJours;
    }

    public void getShowTimes(String idMovie) {

        getHorairesSemaine().clear();
        getHorairesSemaineJours().clear();

        for (TheaterShowtime t : showTimes) {
            if (t.getMovieShowtimes() != null)
                for (MovieShowtime mst : t.getMovieShowtimes()) {

                    boolean avantPremiere = mst.getPreview().equals("true");
                    String formatEcran = null;
                    if (mst.getScreenFormat() != null)
                        formatEcran = mst.getScreenFormat().get$();
                    String version = mst.getVersion().get$();
                    String display = mst.getDisplay();

                    if (mst.getOnShow().getMovie().getCode().toString().equals(idMovie)) {

                        if (mst.getDisplay() != null && !mst.getDisplay().isEmpty()) {
                            String[] joursHorraires = mst.getDisplay().split("Séances du");

                            for (int i = 0; i < joursHorraires.length; i++) {

                                if (joursHorraires != null && joursHorraires.length > 0) {

                                    try {
                                        String[] jrs = joursHorraires[i].split(" : ");

                                        if (jrs.length > 1) {
                                            String jour = jrs[0].trim();
                                            String hrs = jrs[1].trim();

                                            Horaires horaires = new Horaires();
                                            horaires.setAvantPremier(avantPremiere);
                                            horaires.setDisplay(mst.getDisplay());
                                            if (mst.getScreenFormat() != null)
                                                horaires.setFormatEcran(mst.getScreenFormat().get$());
                                            horaires.setVersion(version);
                                            horaires.setDate(jour);

                                            if (horaires.isMoreThanToday()) {
                                                String[] horairesLignes = hrs.split(",");
                                                for (int j = 0; j < horairesLignes.length; ++j) {
                                                    String horraire = horairesLignes[j].trim().split(" ")[0].trim();
                                                    horaires.getSeances().add(horraire);
                                                }

                                                if (this.getHorairesSemaine().containsKey(jour)) {
                                                    this.getHorairesSemaine().get(jour).add(horaires);
                                                } else {
                                                    ArrayList<Horaires> horairesDuJour = new ArrayList<Horaires>();
                                                    horairesDuJour.add(horaires);

                                                    this.getHorairesSemaineJours().add(jour);

                                                    this.getHorairesSemaine().put(jour, horairesDuJour);
                                                }
                                            }
                                        }

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                            }

                        }
                    }
                }
        }
    }

    @Override
    public String toString() {
        return "Theater{" +
                "code='" + code + '\'' +
                ", distance=" + distance +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", postalCode='" + postalCode + '\'' +
                ", city='" + city + '\'' +
                ", picture=" + picture +
                ", geoloc=" + geoloc +
                ", link=" + link +
                ", cinemaChain=" + cinemaChain +
                ", screenCount=" + screenCount +
                ", hasPRMAccess=" + hasPRMAccess +
                '}';
    }
} public class LoadMovieFullTask extends AsyncTask<Object, Void, Movie> {

    boolean erreurReseau = false;
    private LoadMovieFullTaskCallBack callBack;

    public LoadMovieFullTask(LoadMovieFullTaskCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected Movie doInBackground(Object... data) {

        String idMovie = (String) data[0];

        Movie movie = null;
        try {
            movie = Service.movie(idMovie, Service.PROFILE_LARGE, Service.FILTER_MOVIE);
            if (movie != null)
                movie.setBandesAnnonces(Service.videoList(idMovie, 20)); //chargement des bandes annonces
        } catch (Service.NetworkException e) {
            e.printStackTrace();
            erreurReseau = true;
        }

        return movie;
    }

    @Override
    protected void onPostExecute(Movie movie) {
        super.onPostExecute(movie);
        try {
            if (callBack != null) {
                if (erreurReseau)
                    callBack.onErreurReseau();
                else
                    callBack.onLoadMovieFullTaskCallBack(movie);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface LoadMovieFullTaskCallBack {
        public void onLoadMovieFullTaskCallBack(Movie movie);

        public void onErreurReseau();
    }
} public interface LoadMovieFullTaskCallBack {
    public void onLoadMovieFullTaskCallBack(Movie movie);

    public void onErreurReseau();
} public class LoadShowTimesTask extends AsyncTask<Object, Void, List<Theater>> {

    boolean erreurReseau = false;
    boolean cinemaList = false;
    private LoadShowTimesTaskCallBack callBack;

    public LoadShowTimesTask(LoadShowTimesTaskCallBack callBack) {
        this.callBack = callBack;
    }

    public LoadShowTimesTask(LoadShowTimesTaskCallBack callBack, boolean cinemaList) {
        this.callBack = callBack;
        this.cinemaList = cinemaList;
    }

    public static void loadShowTimes(List<Theater> theaters, List<TheaterShowtime> showtimes) {
        for (TheaterShowtime ts : showtimes) {

            Theater cinema = ts.getPlace().getTheater();
            theaters.add(cinema);

            for (MovieShowtime mst : ts.getMovieShowtimes()) {

                boolean avantPremiere = mst.getPreview().equals("true");
                String formatEcran = null;
                if (mst.getScreenFormat() != null)
                    formatEcran = mst.getScreenFormat().get$();
                String version = mst.getVersion().get$();
                String display = mst.getDisplay();

                for (Scr scr : mst.getScr()) {
                    Horaires horaires = new Horaires();
                    horaires.setAvantPremier(avantPremiere);
                    horaires.setDisplay(display);
                    horaires.setFormatEcran(formatEcran);
                    horaires.setVersion(version);
                    horaires.setDate(scr.getD());


                    for (ModelObject t : scr.getT()) {
                        horaires.getSeances().add(t.get$());
                    }

                    if (!horaires.getSeances().isEmpty()) {
                        cinema.getHorraires().add(horaires);
                    }
                }

                if (display != null && !display.isEmpty()) {
                    String[] joursHorraires = display.split("Séances du");

                    for (int i = 0; i < joursHorraires.length; i++) {

                        if (joursHorraires != null && joursHorraires.length > 0) {

                            try {
                                String[] jrs = joursHorraires[i].split(" : ");

                                if (jrs.length > 1) {
                                    String jour = jrs[0].trim();
                                    String hrs = jrs[1].trim();

                                    Horaires horaires = new Horaires();
                                    horaires.setAvantPremier(avantPremiere);
                                    horaires.setDisplay(display);
                                    horaires.setFormatEcran(formatEcran);
                                    horaires.setVersion(version);
                                    horaires.setDate(jour);

                                    if (horaires.isMoreThanToday()) {
                                        String[] horairesLignes = hrs.split(",");
                                        for (int j = 0; j < horairesLignes.length; ++j) {
                                            String horraire = horairesLignes[j].trim().split(" ")[0].trim();
                                            horaires.getSeances().add(horraire);
                                        }

                                        //Log.d("horaires",jour + horaires.getSeances().toString());

                                        if (cinema.getHorairesSemaine().containsKey(jour)) {
                                            cinema.getHorairesSemaine().get(jour).add(horaires);
                                        } else {
                                            ArrayList<Horaires> horairesDuJour = new ArrayList<Horaires>();
                                            horairesDuJour.add(horaires);

                                            cinema.getHorairesSemaineJours().add(jour);
                                            cinema.getHorairesSemaine().put(jour, horairesDuJour);
                                        }
                                    }
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }

                }
            }
        }
    }

    @Override
    protected List<Theater> doInBackground(Object... data) {

        Movie movie = (Movie) data[0];

        if (cinemaList) {
            List<Theater> cinemas = (List<Theater>) data[1];
            StringBuffer sb = new StringBuffer();

            int taille = cinemas.size();

            Log.e("CINEMA_TAILLE", taille + "");

            for (int i = 0; i < taille; ++i) {
                Log.e("CINEMA", cinemas.get(i).getCode().toString());
                sb.append(cinemas.get(i).getCode());
                if (i < taille - 1)
                    sb.append(",");
            }

            cinemas.clear();

            try {
                List<TheaterShowtime> showtimes = Service.showtimelistForTheaterAndMovie(sb.toString(), movie.getCode().toString(), new Date(), 20, 1);

                //Log.d("SHOWTIME", showtimes.toString());

                //Log.e("SHOWTIMES", showtimes.toString());

                if (showtimes != null)
                    loadShowTimes(cinemas, showtimes);


                return cinemas;
            } catch (Service.NetworkException e) {
                e.printStackTrace();
                erreurReseau = true;
                return null;
            }
        } else {

            String lat = (String) data[1];
            String lng = (String) data[2];

            List<Theater> cinemas = new ArrayList<Theater>();

            try {
                List<TheaterShowtime> showtimes = Service.showtimelistWithLatLngAndMovie(lng, lat, "50", "" + movie.getCode(), new Date(), 10, 1);

                //Log.d("SHOWTIME", showtimes.toString());

                //Log.e("SHOWTIMES", showtimes.toString());

                if (showtimes != null)
                    loadShowTimes(cinemas, showtimes);


                return cinemas;
            } catch (Service.NetworkException e) {
                erreurReseau = true;
                return null;
            }
        }
    }

    @Override
    protected void onPostExecute(List<Theater> result) {
        super.onPostExecute(result);
        try {
            if (callBack != null) {
                if (erreurReseau)
                    callBack.onErreurReseau();
                else
                    callBack.onLoadShowTimesTaskCallBack(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public interface LoadShowTimesTaskCallBack {
        public void onLoadShowTimesTaskCallBack(List<Theater> result);

        public void onErreurReseau();
    }
} public class ActionBarHider {

    private Activity activity;
    private int idNotMove;
    private Toolbar toolbar;

    public ActionBarHider(Activity activity, Toolbar toolbar, int idNotMove){
        this.activity = activity;
        this.idNotMove = idNotMove;
        this.toolbar = toolbar;
    }

    private int getActionBarHeight() {
        return toolbar.getHeight();
        /*
        int actionBarHeight = 0;
        TypedValue tv = new TypedValue();
        if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());
        }
        return actionBarHeight;
        */
    }

    public void setActionBarTranslation(float percent) {
        float y =  (percent * getActionBarHeight());
        toolbar.setTranslationY(y);
        //toolbar.setAlpha(percent);
        /*

        ViewGroup content = ((ViewGroup) activity.findViewById(android.R.id.content).getParent());

        int children = content.getChildCount();
        for (int i = 0; i < children; i++) {
            View child = content.getChildAt(i);

            int id = child.getId();

            if (id != android.R.id.content && id != idNotMove) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    child.setTranslationY(y);
                } else {
                    AnimatorProxy.wrap(child).setTranslationY(y);
                }
            }
        }
        */
    }
} public class CellMember extends ViewCell<CastMember> implements View.OnClickListener {

    ImageView image;
    TextView nom;
    TextView prenom;
    TextView roles;

    @Override
    public void construire() {

    }

    @Override
    public void animer() {

    }

    @Override
    public void charger() {
        this.image = (ImageView) getView().findViewById(R.id.image);

        this.nom = (TextView) getView().findViewById(R.id.nom);
        this.prenom = (TextView) getView().findViewById(R.id.prenom);
        this.roles = (TextView) getView().findViewById(R.id.roles);
    }

    @Override
    public void remplir() {
        if (getObject() != null && getObject().getPerson() != null) {

            if (getObject().getPicture() != null && getObject().getPicture().getHref(0) != null) {
                String urlImage = getObject().getPicture().getHref(context.getResources().getInteger(R.integer.fragment_movie_casting_height));
                Picasso.with(context).load(urlImage).into(image);
            } else
                image.setImageResource(R.drawable.ic_placeholder_people);

            this.nom.setText(getObject().getPerson().getFullName());
            this.prenom.setText(getObject().getPerson().getFullName());

            this.roles.setText(getObject().getRole());

        }
    }

    @Override
    public void ajouterListeners() {
        getView().setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        try {
            Intent intent = new Intent(context, StarActivity.class);

            getObject().getPerson().setPicture(getObject().getPicture());

            PersonFull person = PersonFull.transformFull(getObject().getPerson());

            intent.putExtra(StarFragment.PERSON, (new Gson()).toJson(person));

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                Bundle b = ActivityOptions.makeScaleUpAnimation(image, 0, 0, 100, 100).toBundle();

                context.startActivity(intent, b);
            } else
                context.startActivity(intent);
        } catch (Exception e) {
        }

    }
} public class DoubleProgress extends LinearLayout {

    private static final String TAG = "DoubleProgress";

    View mView;

    String stringHaut = "Haut";
    String stringBas = "Bas";
    float max;
    int temps;
    int attente;
    int textFromAlpha = 40;
    int textToAlpha = 100;

    View barreHaut, barreBas;
    View progressBarHaut, progressBarBas;
    TextView valeurHaut, valeurBas;
    TextView texteHaut, texteBas;

    float vHaut = 0;
    float vBas = 0;

    public DoubleProgress(Context context) {
        this(context, null);
    }

    public DoubleProgress(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.DoubleProgress);
        try {
            stringHaut = styledAttrs.getString(R.styleable.DoubleProgress_texteHaut);
            stringBas = styledAttrs.getString(R.styleable.DoubleProgress_texteBas);
            max = styledAttrs.getFloat(R.styleable.DoubleProgress_max, 5);
            temps = styledAttrs.getInt(R.styleable.DoubleProgress_temps, 1000);
            attente = styledAttrs.getInt(R.styleable.DoubleProgress_attente, 0);
            textFromAlpha = styledAttrs.getInt(R.styleable.DoubleProgress_attente, 0);
            textToAlpha = styledAttrs.getInt(R.styleable.DoubleProgress_attente, 0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            styledAttrs.recycle();
        }

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mView = inflater.inflate(R.layout.double_progress, this, true); //ajoute la view

        charger();
        remplir();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    private void charger() {
        barreHaut = mView.findViewById(R.id.barreHaut);
        barreBas = mView.findViewById(R.id.barreBas);

        progressBarHaut = barreHaut.findViewById(R.id.progressBar);
        progressBarBas = barreBas.findViewById(R.id.progressBar);

        valeurHaut = (TextView) barreHaut.findViewById(R.id.valeur);
        valeurBas = (TextView) barreBas.findViewById(R.id.valeur);

        texteHaut = (TextView) barreHaut.findViewById(R.id.text);
        texteBas = (TextView) barreBas.findViewById(R.id.text);
    }

    private void remplir() {
        texteHaut.setText(stringHaut);
        texteBas.setText(stringBas);
    }

    public void setValeurHaut(float f) {
        vHaut = f;
    }

    public void setValeurBas(float f) {
        vBas = f;
    }

    public void animer() {

        /**
         * Attente de la largeur de la vue barreHaut
         */
        barreHaut.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressLint("NewApi")
            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                //now we can retrieve the width and height
                int width = barreHaut.getWidth();

                animer(width);

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
                    barreHaut.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                else
                    barreHaut.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }

    private void animer(int width) {

        valeurHaut.setText("");
        valeurBas.setText("");

        ViewGroup.LayoutParams params = progressBarHaut.getLayoutParams();
        params.width = 0;
        progressBarHaut.setLayoutParams(params);

        ViewGroup.LayoutParams params2 = progressBarBas.getLayoutParams();
        params2.width = 0;
        progressBarBas.setLayoutParams(params2);

        float largeurMax = barreHaut.getWidth();
        float pourcentHaut = vHaut / max;
        float pourcentBas = vBas / max;

        int largeurHaut = (int) (largeurMax * pourcentHaut);
        int largeurtBas = (int) (largeurMax * pourcentBas);

        final AnimatorSet anim = new AnimatorSet();
        anim.setInterpolator(new AccelerateInterpolator());
        anim.setDuration((long) temps);
        anim.playTogether(
                ValueAnimator.ofObject(new WidthEvaluator(progressBarHaut, valeurHaut, vHaut), 0, largeurHaut),
                ValueAnimator.ofObject(new WidthEvaluator(progressBarBas, valeurBas, vBas), 0, largeurtBas)
        );

        this.postDelayed(new Runnable() {
            @Override
            public void run() {
                anim.start();
            }
        }, attente);

    }

    private class WidthEvaluator extends IntEvaluator {

        private View v;
        private TextView tv;
        private float valeur;

        public WidthEvaluator(View v, TextView tv, float valeur) {
            this.v = v;
            this.tv = tv;
            this.valeur = valeur;
        }


        @Override
        public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
            int num = super.evaluate(fraction, startValue, endValue);

            tv.setText(String.format("%.1f", fraction * valeur).replace(",", "."));

            ViewGroup.LayoutParams params = v.getLayoutParams();
            params.width = num;
            v.setLayoutParams(params);

            return num;
        }
    }

} public class ObservableScrollViewAnimateVisible extends ObservableScrollView {
    List<View> vuesAAnimer = new ArrayList<View>();

    public ObservableScrollViewAnimateVisible(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void start() {
        /*


        //chargement des animations
        this.vuesAAnimer.addAll(ViewUtils.getViewsByTag(this, getResources().getString(R.string.animer)));
        for(View v : vuesAAnimer)
        {
            v.setAlpha(0);
        }
        postDelayed(new Runnable() {
            @Override
            public void run() {
                animerVues();
            }
        }, 500);

        */
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);

        animerVues();
    }

    @Override
    public void scrollTo(int x, int y) {
        super.scrollTo(x, y);

        animerVues();
    }

    public void animerVues() {
        List<View> vs = new ArrayList<View>();
        for (View v : vuesAAnimer) {
            Rect scrollBounds = new Rect();
            getHitRect(scrollBounds);
            if (v.getLocalVisibleRect(scrollBounds)) {
                vs.add(v);
            } else {
                // NONE of the view is within the visible window
            }
        }

        for (View v : vs) {
            AnimatorSet animatorSet = new AnimatorSet();
            animatorSet.setDuration(1000);
            animatorSet.playTogether(
                    ObjectAnimator.ofFloat(v, "alpha", 0, 1),
                    ObjectAnimator.ofFloat(v, "translationY", 200, 0)
            );
            animatorSet.start();

            vuesAAnimer.remove(v);
        }

    }

} public class TextViewEx extends TypefacedTextView
{       
    private Paint paint = new Paint();

    private String [] blocks;
    private float spaceOffset = 0;
    private float horizontalOffset = 0;
    private float verticalOffset = 0;
    private float horizontalFontOffset = 0;
    private float dirtyRegionWidth = 0;
    private boolean wrapEnabled = false;
    int left,top,right,bottom=0;
    private Align _align=Align.LEFT;
    private float strecthOffset;
    private float wrappedEdgeSpace;
    private String block;
    private String wrappedLine;
    private String [] lineAsWords;
    private Object[] wrappedObj;
    
    private Bitmap cache = null;
    private boolean cacheEnabled = false;
    
    public TextViewEx(Context context, AttributeSet attrs, int defStyle) 
    {
        super(context, attrs);
        //set a minimum of left and right padding so that the texts are not too close to the side screen
    }

    public TextViewEx(Context context, AttributeSet attrs) 
    {
        super(context, attrs);
    }

    public TextViewEx(Context context) 
    {
        super(context,null);
    }
    
    @Override
	public void setPadding(int left, int top, int right, int bottom) {
		// TODO Auto-generated method stub
    	
		super.setPadding(left+10, top, right+10, bottom);
	}

	@Override
    public void setDrawingCacheEnabled(boolean cacheEnabled) 
    {
        this.cacheEnabled = cacheEnabled;
    }

    public void setText(String st, boolean wrap)
    {
        wrapEnabled = wrap;
        super.setText(st);
    }

    public void setTextAlign(Align align)
    {
    	_align=align;
    }
	@SuppressLint("NewApi")
	@Override
    protected void onDraw(Canvas canvas) 
    { 
        // If wrap is disabled then,
        // request original onDraw
        if(!wrapEnabled)
        {
            super.onDraw(canvas);
            return;
        }
        
        // Active canas needs to be set
        // based on cacheEnabled
        Canvas activeCanvas = null;

        // Set the active canvas based on
        // whether cache is enabled
        if (cacheEnabled) {

            if (cache != null) 
            {
                // Draw to the OS provided canvas
                // if the cache is not empty
                canvas.drawBitmap(cache, 0, 0, paint);
                return;
            } 
            else  
            {
                // Create a bitmap and set the activeCanvas
                // to the one derived from the bitmap
                cache = Bitmap.createBitmap(getWidth(), getHeight(), 
                        Config.ARGB_4444);
                activeCanvas = new Canvas(cache);
            }
        } 
        else 
        {
            // Active canvas is the OS
            // provided canvas
            activeCanvas = canvas;
        }
        
        // Pull widget properties
        paint.setColor(getCurrentTextColor());
        paint.setTypeface(getTypeface());
        paint.setTextSize(getTextSize());
        paint.setTextAlign(_align);
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        
        //minus out the paddings pixel         
        dirtyRegionWidth = getWidth()-getPaddingLeft()-getPaddingRight();
        int maxLines = Integer.MAX_VALUE;
		int currentapiVersion = Build.VERSION.SDK_INT;
		if (currentapiVersion >= Build.VERSION_CODES.JELLY_BEAN){
			maxLines = getMaxLines();
		}
        int lines = 1;
        blocks = getText().toString().split("((?<=\n)|(?=\n))");
        verticalOffset = horizontalFontOffset = getLineHeight() - 3f; // Temp fix
        spaceOffset = paint.measureText(" ");   

        for(int i = 0; i < blocks.length && lines <= maxLines; i++)
        {
            block = blocks[i];
            horizontalOffset = 0;

            if(block.length() == 0)
            {
                continue;
            }           
            else if(block.equals("\n"))
            {
                verticalOffset += horizontalFontOffset;
                continue;
            }

            if(lines == maxLines )
                verticalOffset = 0;

            block = block.trim();
            
            if(block.length() == 0) 
            {
                continue;
            }


            wrappedObj = TextJustifyUtils.createWrappedLine(block, paint, spaceOffset, dirtyRegionWidth);
            
            wrappedLine = ((String) wrappedObj[0]);
            wrappedEdgeSpace = (Float) wrappedObj[1];
            lineAsWords = wrappedLine.split(" ");
            strecthOffset = wrappedEdgeSpace != Float.MIN_VALUE ? wrappedEdgeSpace/(lineAsWords.length - 1) : 0;
            
            for(int j = 0; j < lineAsWords.length; j++)
            {
                String word = lineAsWords[j];
                if (lines == maxLines && j == lineAsWords.length - 1) 
                {
                    activeCanvas.drawText("...", horizontalOffset, verticalOffset, paint);
                	 

                } 
                else if(j==0){
                	//if it is the first word of the line, text will be drawn starting from right edge of textview
                	if (_align==Align.RIGHT)
                	{
                	 activeCanvas.drawText(word, getWidth()-(getPaddingRight()), verticalOffset, paint);
                	// add in the paddings to the horizontalOffset
                	 horizontalOffset+=getWidth()-(getPaddingRight());
                	}
                	else
                	{
                		 activeCanvas.drawText(word, getPaddingLeft(), verticalOffset, paint);
                     	 horizontalOffset+=getPaddingLeft();
                	}
                	
                }
                else 
                {
                    activeCanvas.drawText(word, horizontalOffset, verticalOffset, paint);
                }
                if (_align==Align.RIGHT)
                	horizontalOffset -=  paint.measureText(word) + spaceOffset + strecthOffset;
                else
                	horizontalOffset += paint.measureText(word) + spaceOffset + strecthOffset;
            }

            lines++;
            
            if(blocks[i].length() > 0)
            {
                blocks[i] = blocks[i].substring(wrappedLine.length());              
                verticalOffset += blocks[i].length() > 0 ? horizontalFontOffset : 0;                
                i--;
            }
        }
        
        if (cacheEnabled)
        {
            // Draw the cache onto the OS provided
            // canvas.
            canvas.drawBitmap(cache, 0, 0, paint);
        }
    }
}
import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.ActivityOptions;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.bdc.ociney.R;
import com.bdc.ociney.activity.MovieActivity;
import com.bdc.ociney.activity.StarActivity;
import com.bdc.ociney.adapter.BandesAnnoncesPagerAdapter;
import com.bdc.ociney.adapter.BandesAnnoncesPagerAdapter.OnBandeAnnonceClickedListener;
import com.bdc.ociney.adapter.ImagesPagerAdapter;
import com.bdc.ociney.adapter.ObjectAdapter;
import com.bdc.ociney.adapter.ObjectAdapterLayout;
import com.bdc.ociney.core.BaseActivity;
import com.bdc.ociney.fragment.core.BaseFragment;
import com.bdc.ociney.modele.Media;
import com.bdc.ociney.modele.Movie.Movie;
import com.bdc.ociney.modele.Person.CastMember;
import com.bdc.ociney.modele.Person.PersonFull;
import com.bdc.ociney.modele.Theater.Theater;
import com.bdc.ociney.task.LoadMovieFullTask;
import com.bdc.ociney.task.LoadMovieFullTask.LoadMovieFullTaskCallBack;
import com.bdc.ociney.task.LoadShowTimesTask;
import com.bdc.ociney.utils.actionbar.ActionBarHider;
import com.bdc.ociney.utils.transformation.CircleTransform;
import com.bdc.ociney.utils.transformation.ParallaxTransformer;
import com.bdc.ociney.view.CellMember;
import com.bdc.ociney.view.DoubleProgress;
import com.bdc.ociney.view.ObservableScrollViewAnimateVisible;
import com.bdc.ociney.view.textview.TextViewEx;
import com.github.florent37.androidanalytics.Analytics;
import com.google.android.gms.location.LocationRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.patloew.rxlocation.RxLocation;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.squareup.picasso.Picasso;
import com.tbruyelle.rxpermissions2.RxPermissions;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.picasso.transformations.BlurTransformation;
package com.bdc.ociney.fragment;





public class MovieFragment extends BaseFragment implements LoadMovieFullTaskCallBack, OnBandeAnnonceClickedListener {

    public static final String MOVIE = "movie";
    public static final String ACTIONBAR_TITLE = "ACTIONBAR_TITLE";
    public String actionbarTitle = "";
    Toolbar toolbar;
    Movie movie;
    List<Theater> cinemas = new ArrayList<Theater>();

    @BindView(R.id.scrollView)
    ObservableScrollViewAnimateVisible scrollView;