@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setupActionBar();

    if (savedInstanceState == null) {
      if (ServiceUtils.hasTraktCredentials(this)) {
        // immediately show credentials to allow disconnecting
        ConnectTraktCredentialsFragment f = ConnectTraktCredentialsFragment.newInstance();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(android.R.id.content, f);
        ft.commit();
      } else {
        // display trakt introduction
        ConnectTraktFragment f = new ConnectTraktFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(android.R.id.content, f);
        ft.commit();
      }
    }
  }
  @Override
  public List<Movie> loadInBackground() {
    ServiceManager manager = ServiceUtils.getTmdbServiceManager(getContext());

    try {
      ResultsPage page;
      if (TextUtils.isEmpty(mQuery)) {
        page = manager.moviesService().nowPlaying().fire();
      } else {
        page = manager.searchService().movieSearch(mQuery).fire();
      }
      if (page != null && page.results != null) {
        return page.results;
      }
    } catch (TmdbException e) {
      Utils.trackException(getContext(), TAG, e);
      Log.w(TAG, e);
    } catch (ApiException e) {
      Utils.trackException(getContext(), TAG, e);
      Log.w(TAG, e);
    }

    return null;
  }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
      mShowTvdbId = cursor.getInt(DetailsQuery.REF_SHOW_ID);
      mSeasonNumber = cursor.getInt(DetailsQuery.SEASON);
      mEpisodeNumber = cursor.getInt(DetailsQuery.NUMBER);
      final String showTitle = cursor.getString(DetailsQuery.SHOW_TITLE);
      final String episodeTitle = cursor.getString(DetailsQuery.TITLE);
      final long airTime = cursor.getLong(DetailsQuery.FIRSTAIREDMS);

      // Title and description
      ((TextView) view.findViewById(R.id.title)).setText(cursor.getString(DetailsQuery.TITLE));
      ((TextView) view.findViewById(R.id.description))
          .setText(cursor.getString(DetailsQuery.OVERVIEW));

      // Show title button
      TextView showtitle = (TextView) view.findViewById(R.id.showTitle);
      if (!isShowingShowLink()) {
        showtitle.setVisibility(View.GONE);
      } else {
        showtitle.setVisibility(View.VISIBLE);
        showtitle.setText(showTitle);
        showtitle.setOnClickListener(
            new OnClickListener() {
              public void onClick(View v) {
                Intent upIntent = new Intent(getActivity(), OverviewActivity.class);
                upIntent.putExtra(OverviewFragment.InitBundle.SHOW_TVDBID, mShowTvdbId);
                upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(upIntent);
                getActivity()
                    .overridePendingTransition(
                        R.anim.fragment_slide_right_enter, R.anim.fragment_slide_right_exit);
                getActivity().finish();
              }
            });
      }

      // Show poster background
      if (getArguments().getBoolean("showposter")) {
        final ImageView background =
            (ImageView) getActivity().findViewById(R.id.episodedetails_background);
        Utils.setPosterBackground(
            background, cursor.getString(DetailsQuery.SHOW_POSTER), getActivity());
      }

      SpannableStringBuilder airTimeAndNumberText = new SpannableStringBuilder();
      // Air day and time
      TextView airdateText = (TextView) view.findViewById(R.id.airDay);
      TextView airtimeText = (TextView) view.findViewById(R.id.airTime);
      if (airTime != -1) {
        airdateText.setText(Utils.formatToDate(airTime, getActivity()));
        String[] dayAndTime = Utils.formatToTimeAndDay(airTime, getActivity());
        airTimeAndNumberText
            .append(
                getString(R.string.release_date_and_day, dayAndTime[2], dayAndTime[1])
                    .toUpperCase(Locale.getDefault()))
            .append("  ");
      } else {
        airdateText.setText(R.string.unknown);
      }

      // number
      int numberStartIndex = airTimeAndNumberText.length();
      airTimeAndNumberText.append(
          getString(R.string.season_number, mSeasonNumber).toUpperCase(Locale.getDefault()));
      airTimeAndNumberText.append(" ");
      airTimeAndNumberText.append(
          getString(R.string.episode_number, mEpisodeNumber).toUpperCase(Locale.getDefault()));
      final int episodeAbsoluteNumber = cursor.getInt(DetailsQuery.ABSOLUTE_NUMBER);
      if (episodeAbsoluteNumber > 0 && episodeAbsoluteNumber != mEpisodeNumber) {
        airTimeAndNumberText.append(" (").append(String.valueOf(episodeAbsoluteNumber)).append(")");
      }
      airTimeAndNumberText.setSpan(
          new TextAppearanceSpan(mContext, R.style.TextAppearance_Small_Dim),
          numberStartIndex,
          airTimeAndNumberText.length(),
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      airtimeText.setText(airTimeAndNumberText);

      // Last edit date
      TextView lastEdit = (TextView) view.findViewById(R.id.lastEdit);
      long lastEditRaw = cursor.getLong(DetailsQuery.LASTEDIT);
      if (lastEditRaw > 0) {
        lastEdit.setText(
            DateUtils.formatDateTime(
                context,
                lastEditRaw * 1000,
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME));
      } else {
        lastEdit.setText(R.string.unknown);
      }

      // Guest stars
      Utils.setLabelValueOrHide(
          view.findViewById(R.id.labelGuestStars),
          (TextView) view.findViewById(R.id.guestStars),
          Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.GUESTSTARS)));
      // DVD episode number
      Utils.setLabelValueOrHide(
          view.findViewById(R.id.labelDvd),
          (TextView) view.findViewById(R.id.dvdNumber),
          cursor.getDouble(DetailsQuery.DVDNUMBER));
      // Directors
      String directors = Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.DIRECTORS));
      Utils.setValueOrPlaceholder(view.findViewById(R.id.directors), directors);
      // Writers
      String writers = Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.WRITERS));
      Utils.setValueOrPlaceholder(view.findViewById(R.id.writers), writers);

      // Episode image
      FrameLayout imageContainer = (FrameLayout) view.findViewById(R.id.imageContainer);
      final String imagePath = cursor.getString(DetailsQuery.IMAGE);
      onLoadImage(imagePath, imageContainer);
      imageContainer.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              Intent fullscreen = new Intent(getActivity(), FullscreenImageActivity.class);
              fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_PATH, imagePath);
              fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_TITLE, showTitle);
              fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_SUBTITLE, episodeTitle);
              ActivityCompat.startActivity(
                  getActivity(),
                  fullscreen,
                  ActivityOptionsCompat.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight())
                      .toBundle());
            }
          });

      mEpisodeFlag = cursor.getInt(DetailsQuery.WATCHED);
      // Watched button
      boolean isWatched = EpisodeTools.isWatched(mEpisodeFlag);
      ImageButton seenButton = (ImageButton) view.findViewById(R.id.imageButtonBarWatched);
      seenButton.setImageResource(
          isWatched
              ? R.drawable.ic_ticked
              : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatch));
      seenButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onToggleWatched();
              fireTrackerEvent("Toggle watched");
            }
          });
      CheatSheet.setup(seenButton, isWatched ? R.string.unmark_episode : R.string.mark_episode);

      // skip button
      boolean isSkipped = EpisodeTools.isSkipped(mEpisodeFlag);
      ImageButton skipButton = (ImageButton) view.findViewById(R.id.imageButtonBarSkip);
      skipButton.setVisibility(
          isWatched ? View.GONE : View.VISIBLE); // if watched do not allow skipping
      skipButton.setImageResource(
          isSkipped
              ? R.drawable.ic_action_playback_next_highlight
              : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableSkip));
      skipButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onToggleSkipped();
              fireTrackerEvent("Toggle skipped");
            }
          });
      CheatSheet.setup(skipButton, isSkipped ? R.string.action_dont_skip : R.string.action_skip);

      // Collected button
      mCollected = cursor.getInt(DetailsQuery.COLLECTED) == 1;
      ImageButton collectedButton = (ImageButton) view.findViewById(R.id.imageButtonBarCollected);
      collectedButton.setImageResource(
          mCollected
              ? R.drawable.ic_collected
              : Utils.resolveAttributeToResourceId(
                  getActivity().getTheme(), R.attr.drawableCollect));
      collectedButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onToggleCollected();
              fireTrackerEvent("Toggle collected");
            }
          });
      CheatSheet.setup(collectedButton, mCollected ? R.string.uncollect : R.string.collect);

      // menu button
      View menuButton = view.findViewById(R.id.imageButtonBarMenu);
      registerForContextMenu(menuButton);
      menuButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              getActivity().openContextMenu(v);
            }
          });

      // TVDb rating
      RelativeLayout ratings = (RelativeLayout) view.findViewById(R.id.ratingbar);
      String ratingText = cursor.getString(DetailsQuery.RATING);
      if (ratingText != null && ratingText.length() != 0) {
        TextView ratingValue = (TextView) ratings.findViewById(R.id.textViewRatingsTvdbValue);
        ratingValue.setText(ratingText);
      }
      ratings.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onRateOnTrakt();
            }
          });
      ratings.setFocusable(true);
      CheatSheet.setup(ratings, R.string.menu_rate_episode);

      // fetch trakt ratings
      onLoadTraktRatings(ratings, true);

      // Google Play button
      View playButton = view.findViewById(R.id.buttonGooglePlay);
      ServiceUtils.setUpGooglePlayButton(showTitle + " " + episodeTitle, playButton, TAG);

      // Amazon button
      View amazonButton = view.findViewById(R.id.buttonAmazon);
      ServiceUtils.setUpAmazonButton(showTitle + " " + episodeTitle, amazonButton, TAG);

      // YouTube button
      View youtubeButton = view.findViewById(R.id.buttonYouTube);
      ServiceUtils.setUpYouTubeButton(showTitle + " " + episodeTitle, youtubeButton, TAG);

      // IMDb button
      String imdbId = cursor.getString(DetailsQuery.IMDBID);
      if (TextUtils.isEmpty(imdbId)) {
        // fall back to show IMDb id
        imdbId = cursor.getString(DetailsQuery.SHOW_IMDBID);
      }
      ServiceUtils.setUpImdbButton(
          imdbId, view.findViewById(R.id.buttonShowInfoIMDB), TAG, getActivity());

      // TVDb button
      final int seasonTvdbId = cursor.getInt(DetailsQuery.REF_SEASON_ID);
      ServiceUtils.setUpTvdbButton(
          mShowTvdbId, seasonTvdbId, getEpisodeTvdbId(), view.findViewById(R.id.buttonTVDB), TAG);

      // trakt button
      ServiceUtils.setUpTraktButton(
          mShowTvdbId, mSeasonNumber, mEpisodeNumber, view.findViewById(R.id.buttonTrakt), TAG);

      // Web search button
      View webSearch = view.findViewById(R.id.buttonWebSearch);
      ServiceUtils.setUpWebSearchButton(showTitle + " " + episodeTitle, webSearch, TAG);

      // trakt shouts button
      view.findViewById(R.id.buttonShouts)
          .setOnClickListener(
              new OnClickListener() {
                @Override
                public void onClick(View v) {
                  Intent intent = new Intent(getActivity(), TraktShoutsActivity.class);
                  intent.putExtras(
                      TraktShoutsActivity.createInitBundleEpisode(
                          mShowTvdbId, mSeasonNumber, mEpisodeNumber, episodeTitle));
                  startActivity(intent);
                  fireTrackerEvent("Comments");
                }
              });

      // Check in button
      final int episodeTvdbId = cursor.getInt(DetailsQuery._ID);
      View checkinButton = view.findViewById(R.id.imageButtonBarCheckin);
      checkinButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              // display a check-in dialog
              CheckInDialogFragment f =
                  CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId);
              f.show(getFragmentManager(), "checkin-dialog");
              fireTrackerEvent("Check-In");
            }
          });
      CheatSheet.setup(checkinButton);
    }