public class DialogFragmentAbout extends DialogFragment {

    public static final String TAG = "df_about";


    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mainView = inflater.inflate(R.layout.dialog_about_app, null);

        String versionName = "-1";
        String build = "-1";
        try {
            PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionName = pInfo.versionName;
            build = String.valueOf(pInfo.versionCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        TextView tvVersion = (TextView) mainView.findViewById(R.id.tvVersion);
        tvVersion.setText(getString(R.string.version) + " " + versionName + " (" + getString(R.string.build) + " " + build + ")");

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getString(R.string.main_about))
                .setView(mainView)
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();
                            }
                        });

        return builder.create();
    }

} public class FragmentHelp extends Fragment implements ICustumziedBackPress, IControlStackHistory {

    public static final String TAG = "fragment_help";
    public static final String PREF_HELP_SHOWN = "help_shown";

    private HelpPagesAdapter helpPagesAdapter;
    private ViewPager vpHelp;
    private CircleIndicator indicatorHelp;
    private View.OnClickListener closeClickListener;

    public boolean isFromSlidingMenu;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_help, container, false);

        if (((IToolbarHolder) getActivity()).getToolbar() != null) {
            ((IToolbarHolder) getActivity()).getToolbar().setVisibility(View.GONE);
        }

        vpHelp = (ViewPager) view.findViewById(R.id.vpHelp);
        indicatorHelp = (CircleIndicator) view.findViewById(R.id.indicatorHelp);
        helpPagesAdapter = new HelpPagesAdapter(getChildFragmentManager());

        initCloseListener();
        helpPagesAdapter.setCloseClickListener(closeClickListener);
        vpHelp.setAdapter(helpPagesAdapter);
        indicatorHelp.setViewPager(vpHelp);
        Prefs.putBoolean(PREF_HELP_SHOWN, true);
        return view;
    }

    private void initCloseListener() {
        if (closeClickListener == null) {
            closeClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getFragmentManager().popBackStack();
                }
            };
        }
    }


    public void setCloseClickListener(View.OnClickListener closeClickListener) {
        this.closeClickListener = closeClickListener;
    }

    @Override
    public boolean onBackPressed() {
        closeClickListener.onClick(null);
        return false;
    }

    @Override
    public boolean shouldBeAddedToStack() {
        if (isFromSlidingMenu) {
            return true;
        }
        return !Prefs.getBoolean(FragmentHelp.PREF_HELP_SHOWN, true); //don't add to history if first time screen
    }
} public class FragmentMediaItemsGrid extends Fragment implements ICustumziedBackPress {

    private static final int CATEGORIES_FRAGMENT_POSITION = 3;
    public static final String LAST_ITEM_POSITION = "vp_last_postion";

    public static final String TAG;
    private MediaViewpager vpMedia;
    private MediaPagesAdapter mediaPagesAdapter;
    private TabLayout vpMediaTabs;
    private SmallPlayer smallPlayer;
    private MediaItemType mediaItemType;

    private int startItemNumber = 0;

    static {
        long time = Calendar.getInstance().get(Calendar.MILLISECOND);
        TAG = "f_media_grid" + String.valueOf(time);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_media_grid, container, false);
        mediaPagesAdapter = new MediaPagesAdapter(getChildFragmentManager(), mediaItemType);
        vpMedia = (MediaViewpager) view.findViewById(R.id.vpMedia);
        vpMedia.setAdapter(mediaPagesAdapter);
        vpMediaTabs = (TabLayout) view.findViewById(R.id.tlMediaTabs);
        vpMediaTabs.setBackgroundResource(R.color.color_primary);

        Toolbar toolbar = ((IToolbarHolder) getActivity()).getToolbar();
        toolbar.setVisibility(View.VISIBLE);
        toolbar.getMenu().findItem(R.id.action_search).setVisible(true);
        toolbar.getMenu().findItem(R.id.add_podcast).setVisible(true);
        toolbar.getMenu().findItem(R.id.add_radio).setVisible(true);

        if (mediaItemType == MediaItemType.RADIO) {
            vpMediaTabs.setTabMode(TabLayout.MODE_FIXED);
            vpMedia.setPagingEnabled(false);
            toolbar.setTitle(R.string.radio_main);
            ((ISlidingMenuHolder) getActivity()).setSlidingMenuHeader(getString(R.string.radio_main));
            ActivityMain.lastFragmentType = MediaItemType.RADIO.ordinal();
        } else {
            ActivityMain.lastFragmentType = MediaItemType.PODCAST.ordinal();
            toolbar.setTitle(R.string.podcasts);
            ((ISlidingMenuHolder) getActivity()).setSlidingMenuHeader(getString(R.string.podcasts_main));
        }

        //Tabs color
        //tlPodcastsTabs.setTabTextColors(R.color.white_material, R.color.viewPagerNotSelectedWhite);

        // Workaround for Google's bugs
        // See https://code.google.com/p/android/issues/detail?id=180462

        vpMediaTabs.post(new Runnable() {
            @Override
            public void run() {
                vpMediaTabs.setupWithViewPager(vpMedia);
            }
        });

        smallPlayer = new SmallPlayer(view, getActivity());

        vpMedia.setCurrentItem(startItemNumber);

        return view;
    }

    public void setMediaItemType(MediaItemType mediaItemType) {
        this.mediaItemType = mediaItemType;
    }

    public void setStartItemNumber(int startItemNumber) {
        this.startItemNumber = startItemNumber;
    }

    @Override
    public void onDestroy() {
        if (smallPlayer != null) {
            smallPlayer.destroy();
        }
        super.onDestroy();
    }

    @Override
    public void onResume() {
        //Set callback for ProviderProfileManager
        ProfileManager.getInstance().setProfileSavedCallback(new IOperationFinishWithDataCallback() {
            @Override
            public void operationFinished(Object data) {
                if (isAdded() && mediaPagesAdapter != null && data != null) {
                    mediaPagesAdapter.notifyChangesInFragments((ProfileManager.ProfileUpdateEvent) data);
                }
            }
        });
        if (smallPlayer != null) {
            smallPlayer.onResume();
        }
        super.onResume();
    }

    @Override
    public void onPause() {
        if (smallPlayer != null) {
            smallPlayer.onPause();
        }
        ActivityMain.lastChildFragmentNumber = vpMedia.getCurrentItem();
        ProfileManager.getInstance().setProfileSavedCallback(null);
        super.onPause();
    }

    @Override
    public boolean onBackPressed() {
        Fragment fragment = (Fragment) vpMedia.getAdapter().instantiateItem(vpMedia, vpMedia.getCurrentItem());
        if (fragment instanceof ICustumziedBackPress) {
            return ((ICustumziedBackPress) fragment).onBackPressed();
        }
        return true;
    }
} public class FragmentProfile extends Fragment implements IControlStackHistory {

    public static final String TAG = "fragment_profile";
    private static final String FB_PERMISSIONS = "public_profile";
    private static final String VK_SCOPE = "email";

    private LinearLayout lnLoggedInState;
    private LinearLayout lnLoggedOutState;

    private Button btnFacebookLogin;
    private Button btnTwitter;
    private ILoginManager loginManager;
    private ProgressBar progressBar;
    private TwitterAuthClient mTwitterAuthClient;
    private boolean skipAddingToHistory;

    private View rootView;

    private FacebookCallback facebookCallback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            initUIAfterLogin();

        }

        @Override
        public void onCancel() {
            // App code
        }

        @Override
        public void onError(FacebookException exception) {
            Logger.printError("Facebook login error: ", exception.toString());
        }
    };

    private Callback<TwitterSession> tweetCallback = new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            initUIAfterLogin();
        }

        @Override
        public void failure(TwitterException exception) {
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mTwitterAuthClient = new TwitterAuthClient();
        ((IToolbarHolder) getActivity()).getToolbar().setVisibility(View.GONE);

        rootView = inflater.inflate(R.layout.fragment_profile, container, false);
        loginManager = (ILoginManager) getActivity();
        lnLoggedInState = (LinearLayout) rootView.findViewById(R.id.lnLoggedInState);
        lnLoggedOutState = (LinearLayout) rootView.findViewById(R.id.lnLoggedOutState);
        progressBar = (ProgressBar) rootView.findViewById(R.id.pbLoading);

        progressBar.setVisibility(View.GONE);

        rootView.findViewById(R.id.btnVklogin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VKSdk.login(FragmentProfile.this, VK_SCOPE);
            }
        });

        if (LoginMaster.getInstance().isLogedIn()) {
            lnLoggedOutState.setVisibility(View.GONE);
            lnLoggedInState.setVisibility(View.VISIBLE);
            initUserProfileUI();
        } else {
            initLoginUI(rootView);
        }
        return rootView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mTwitterAuthClient.onActivityResult(requestCode, resultCode, data);
        if (!VKSdk.onActivityResult(requestCode, resultCode, data, new VKCallback<VKAccessToken>() {
            @Override
            public void onResult(VKAccessToken token) {
                initUIAfterLogin();
            }

            @Override
            public void onError(VKError error) {
            }
        })) {
            super.onActivityResult(requestCode, resultCode, data);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


    /**
     * Should be called after login, will sync all changes with cloud and update UI after it.
     */
    private void initUIAfterLogin() {
        lnLoggedOutState.setVisibility(View.GONE);
        lnLoggedInState.setVisibility(View.VISIBLE);
        initUserProfileUI();
    }

    private void initUserProfileUI() {
        final ImageView imgAvatar = (ImageView) rootView.findViewById(R.id.imgAvatar);
        LoginMaster.getInstance().initUserProfile(new IOperationFinishWithDataCallback() {
            @Override
            public void operationFinished(Object data) {
                UserProfile userProfile = (UserProfile) data;
                ((TextView) rootView.findViewById(R.id.tvUserName)).setText(((UserProfile) data).getName());
                Glide.with(getActivity()).load(userProfile.getProfileImageUrl()).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgAvatar) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        imgAvatar.setImageDrawable(circularBitmapDrawable);
                    }
                });
                ((ISlidingMenuHolder) getActivity()).getSlidingMenu().updateHeader(userProfile);
            }
        }, true);

        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View lvHeaderView = inflater.inflate(R.layout.profile_item_header, null, false);

        //Foooter
        View lvFooterView = inflater.inflate(R.layout.profile_footer, null, false);
        Button btnSave = (Button) lvFooterView.findViewById(R.id.btnSaveToCloud);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sync(SyncMaster.Task.PUSH);
            }
        });
        Button btnRestore = (Button) lvFooterView.findViewById(R.id.btnRestoreFromCloud);
        btnRestore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sync(SyncMaster.Task.PULL);
            }
        });
        //End footer

        ListView lvProfile = (ListView) rootView.findViewById(R.id.lvProfile);
        if (lvProfile.getHeaderViewsCount() == 0) {
            lvProfile.addHeaderView(lvHeaderView);
        }
        if (lvProfile.getFooterViewsCount() == 0) {
            lvProfile.addFooterView(lvFooterView);
        }

        lvProfile.setHeaderDividersEnabled(false);
        lvProfile.setFooterDividersEnabled(false);
        ProfileItemsAdapter profileItemsAdapter = new ProfileItemsAdapter(getActivity(), R.layout.profile_item);
        profileItemsAdapter.addAll(ProfileItem.fromLoggedinUser(getActivity()));
        lvProfile.setAdapter(profileItemsAdapter);

        rootView.findViewById(R.id.imgProfileArrowLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });

        rootView.findViewById(R.id.imgProfileDots).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((IContextMenuManager) getActivity()).openContextMenu(v, ContextMenuType.PROFILE,
                        null, new IOperationFinishCallback() {
                            @Override
                            public void operationFinished() {
                                FragmentProfile fragmentProfile = new FragmentProfile();
                                fragmentProfile.skipAddingToHistory = true;
                                ((IFragmentsManager) getActivity()).showFragment(R.id.fl_content, fragmentProfile, TAG);
                            }
                        });
            }
        });
    }

    public void initLoginUI(View rootView) {
        lnLoggedOutState.setVisibility(View.VISIBLE);
        lnLoggedInState.setVisibility(View.GONE);
        btnFacebookLogin = (Button) rootView.findViewById(R.id.btnFacebookLogin);
        btnTwitter = (Button) rootView.findViewById(R.id.btnTwitterLogin);
        btnFacebookLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginManager.getInstance().registerCallback(loginManager.getFacebookCallbackManager(), facebookCallback);
                LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
            }
        });
        btnTwitter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTwitterAuthClient.authorize(getActivity(), tweetCallback);
            }
        });
    }

    private void sync(SyncMaster.Task task) {
        final MaterialDialog progressDialog = new MaterialDialog.Builder(getActivity())
                .title(R.string.syncing)
                .content(R.string.please_wait)
                .progress(true, 0)
                .show();
        LoginMaster.getInstance().syncWithCloud(new IOperationFinishCallback() {
            @Override
            public void operationFinished() {
                initUIAfterLogin();
                progressDialog.dismiss();
            }
        }, task);
    }

    @Override
    public boolean shouldBeAddedToStack() {
        return !skipAddingToHistory;
    }

} public class FragmentSettings extends PreferenceFragment {

    public static String TAG = "preference";
    private Toolbar toolbar;

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

        toolbar = ((IToolbarHolder) getActivity()).getToolbar();
        if(toolbar!=null) {
            toolbar.setVisibility(View.VISIBLE);
            toolbar.getMenu().findItem(R.id.action_search).setVisible(false);
            toolbar.getMenu().findItem(R.id.add_podcast).setVisible(false);
            toolbar.getMenu().findItem(R.id.add_radio).setVisible(false);
            toolbar.setTitle(R.string.action_settings);
        }
        ((ISlidingMenuHolder) getActivity()).setSlidingMenuHeader(getString(R.string.action_settings));
        addPreferencesFromResource(R.xml.settings);

        Preference folderPreference = findPreference(getString(R.string.podcasts_default_folder));
        folderPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                Uri selectedUri = Uri.parse(Environment.getExternalStoragePublicDirectory(DownloadMaster.PODCASTS_DOWNLOAD_DIRECTORY).getPath());
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(selectedUri, "*/*");
                startActivity(intent);
                return false;
            }
        });
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        toolbar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPause() {
        SettingsManager.getInstace().initSettingsFromPreferences();
        UpodsApplication.setAlarmManagerTasks();
        super.onPause();
    }

} public class FragmentWellcome extends Fragment implements IControlStackHistory {

    public static final String TAG = "fragment_wellcome";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wellcome, container, false);
        Toolbar toolbar = ((IToolbarHolder) getActivity()).getToolbar();
        toolbar.setVisibility(View.GONE);
        return view;
    }

    @Override
    public boolean shouldBeAddedToStack() {
        return false;
    }
} public interface IFragmentsManager {

    enum FragmentOpenType {REPLACE, OVERLAY}

    enum FragmentAnimationType {DEFAULT, BOTTOM_TOP}


    void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType);

    void showFragment(int id, Fragment fragment, String tag);

    void hideFragment(Fragment fragment);

    void showDialogFragment(DialogFragment dialogFragment);

    boolean hasFragment(String tag);

    String getLatestFragmentTag();
} public interface ISlidingMenuManager {

    void toggle();
} public class SlidingMenuHeader extends SlidingMenuItem {

    private String name;
    private String email;
    private String imgUrl;

    public SlidingMenuHeader() {
        super();
        this.name = UpodsApplication.getContext().getString(R.string.anonymus);
        this.email = UpodsApplication.getContext().getString(R.string.anonymus_email);
        this.imgUrl = UserProfile.EMPTY_AVATAR;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
} public abstract class SlidingMenuItem {
    public boolean hasDevider;

    SlidingMenuItem() {
        this.hasDevider = false;
    }
} public class SlidingMenuRow extends SlidingMenuItem {

    private String title;
    private int mainIconId;
    private int pressedIconId;
    public boolean isSelected;

    public SlidingMenuRow(String title, int mainIconId, int pressedIconId) {
        super();
        this.title = title;
        this.mainIconId = mainIconId;
        this.pressedIconId = pressedIconId;
    }

    public SlidingMenuRow(String title, int mainIconId, int pressedIconId, boolean hasDevider) {
        this(title, mainIconId, pressedIconId);
        this.hasDevider = hasDevider;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getMainIconId() {
        return mainIconId;
    }

    public int getPressedIconId() {
        return pressedIconId;
    }


    public static List<SlidingMenuItem> fromDefaultSlidingMenuSet() {
        Context mContext = UpodsApplication.getContext();
        ArrayList<SlidingMenuItem> allItems = new ArrayList<SlidingMenuItem>();
        allItems.add(new SlidingMenuRow(mContext.getString(R.string.profile_my_profile), R.drawable.ic_account_circle_grey600_24dp, R.drawable.help_circle));
        allItems.add(new SlidingMenuRow(mContext.getString(R.string.radio_main), R.drawable.ic_radio_grey600_24dp, R.drawable.radio));
        allItems.add(new SlidingMenuRow(mContext.getString(R.string.podcasts_main), R.drawable.ic_rss_grey600_24dp, R.drawable.rss, true));
        //allItems.add(new SlidingMenuRow(mContext.getString(R.string.cloud_sync), R.drawable.ic_cloud_upload_grey600_24dp, R.drawable.cloud_upload, true));
        allItems.add(new SlidingMenuRow(mContext.getString(R.string.main_rate_app), R.drawable.ic_heart_grey600_24dp, R.drawable.heart));
        allItems.add(new SlidingMenuRow(mContext.getString(R.string.main_about), R.drawable.ic_android_grey600_24dp, R.drawable.android_pink));
        allItems.add(new SlidingMenuRow(mContext.getString(R.string.main_help), R.drawable.ic_help_circle_grey600_24dp, R.drawable.help_circle, true));
        allItems.add(new SlidingMenuRow(mContext.getString(R.string.main_settings), R.drawable.ic_settings_grey600_24dp, R.drawable.settings));
        return allItems;
    }


} public class Analytics {


    //Sliding menu
    public static final String SLIDING_MENU_SETTINGS_CLICK = "sliding_menu_settings_click";
    public static final String SLIDING_MENU_PODCASTS_CLICK = "sliding_menu_podcasts_click";
    public static final String SLIDING_MENU_RADIO_CLICK = "sliding_menu_radio_click";
    public static final String SLIDING_MENU_PROFILE_CLICK = "sliding_profile_click";
    public static final String SLIDING_MENU_HELP_CLICK = "sliding_menu_help_click";
    public static final String SLIDING_MENU_RATE_CLICK = "sliding_menu_rate_click";
    public static final String SLIDING_MENU_ABOUT_CLICK = "sliding_about_click";

    //Main screen
    public static final String FEATURED_BUTTON_MORE = "featured_btn_more_click";

    //Middle screen
    public static final String MIDDLE_SCREEN_UNSUBSCRIBE = "middle_screen_subscribe";
    public static final String MIDDLE_SCREEN_SUBSCRIBE = "middle_screen_unsubscribe";
    public static final String MIDDLE_SCREEN_PLAY_RADIO = "middle_screen_play_radio";
    public static final String MIDDLE_SCREEN_PLAY_EPISODE = "middle_screen_play_episode";
    public static final String MIDDLE_SCREEN_DOWNLOAD_EPISODE = "middle_screen_download_episode";
    public static final String MIDDLE_SCREEN_CANCELL_DOWNLOAD_EPISODE = "middle_screen_cancel_download";
    public static final String MIDDLE_SCREEN_ABOUT_PODCAST = "middle_screen_about_podcast";
    public static final String MIDDLE_SCREEN_OPEN_ON_DISK = "middle_screen_open_disk";
    public static final String MIDDLE_REMOVE_EPISODE = "middle_screen_remove_episode";
    public static final String MIDDLE_REMOVE_ALL_EPISODES = "middle_screen_rempve_all";

    //Playlist
    public static final String PLAYLIST_TOGGLE = "playlist_toggle";
    public static final String PLAYLIST_ITEM_CLICK = "playlist_item_click";

    //Player
    public static final String PLAYER_STREAM_QUALITY = "player_stream_quality";
    public static final String PLAYER_STREAM_INFO = "player_stream_info";
    public static final String PLAYER_SUBSCRIBE = "player_subscribe";
    public static final String PLAYER_UNSUBSCRIBE = "player_unsubscribe";

    public static String PLAY_PREFIX = "play_";
} public class GlobalUtils {

    public static boolean safeTitleEquals(String title1, String title2) {
        if (title1 == null || title2 == null) {
            return false;
        }
        //replaceAll("[^a-z,A-Z,0-9,.,+,-, ,!,?,_,:,;,=]", "");
        title1 = title1.trim().replace("'","");
        title2 = title2.trim().replace("'","");;
        return title1.equals(title2);
    }

    public static String getCurrentDateTimeUS() {
        DateFormat df = new SimpleDateFormat("d MMM, HH:mm", Locale.US);
        String date = df.format(Calendar.getInstance().getTime());
        Logger.printInfo("Sync date", date);
        return date;
    }

    public static String parserDateToMonth(String date) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z", Locale.US);
            Date inputDate = dateFormat.parse(date);
            dateFormat = new SimpleDateFormat("MMM\ndd", Locale.US);
            date = dateFormat.format(inputDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String getCleanFileName(String str) {
        str = str.toLowerCase();
        return str.replaceAll("[^a-zA-Z0-9]+", "_");
    }

    public static boolean deleteDirectory(File path) {
        if (path.exists()) {
            File[] files = path.listFiles();
            if (files == null) {
                return true;
            }
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                } else {
                    files[i].delete();
                }
            }
        }
        return (path.delete());
    }

    public static boolean isInternetConnected() {
        ConnectivityManager cm = (ConnectivityManager) UpodsApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

    /**
     * Returns a list with all links contained in the input
     */
    public static List<String> extractUrls(String text) {
        String lines[] = text.split("\\s+");
        List<String> containedUrls = new ArrayList<String>();
        String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
        Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);

        for (String line : lines) {
            Matcher urlMatcher = pattern.matcher(line);
            while (urlMatcher.find()) {
                containedUrls.add(line.substring(urlMatcher.start(0), urlMatcher.end(0)));
            }
        }
        return containedUrls;
    }

    public static boolean isUrlReachable(String urlToCheck) {
        try {
            URL url = new URL(urlToCheck);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            int code = connection.getResponseCode();
            if (code == 200) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void rateApp(Context context) {
        Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);

        goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        try {
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName())));
        }
    }

    public static boolean isPackageInstalled(String packagename) {
        PackageManager pm = UpodsApplication.getContext().getPackageManager();
        try {
            pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static String upperCase(String str) {
        StringBuilder rackingSystemSb = new StringBuilder(str.toLowerCase());
        rackingSystemSb.setCharAt(0, Character.toUpperCase(rackingSystemSb.charAt(0)));
        str = rackingSystemSb.toString();
        return str;
    }

} public enum MediaItemType {

    DEFAULT, PODCAST, RADIO, PODCAST_DOWNLOADED, RADIO_SUBSCRIBED, RADIO_RECENT, PODCAST_FAVORITE, RADIO_SEARCH, PODCAST_SEARCH
}
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.chickenkiller.upods2.R;
import com.chickenkiller.upods2.dialogs.DialogFragmentAbout;
import com.chickenkiller.upods2.fragments.FragmentHelp;
import com.chickenkiller.upods2.fragments.FragmentMediaItemsGrid;
import com.chickenkiller.upods2.fragments.FragmentProfile;
import com.chickenkiller.upods2.fragments.FragmentSettings;
import com.chickenkiller.upods2.fragments.FragmentWellcome;
import com.chickenkiller.upods2.interfaces.IFragmentsManager;
import com.chickenkiller.upods2.interfaces.ISlidingMenuManager;
import com.chickenkiller.upods2.models.SlidingMenuHeader;
import com.chickenkiller.upods2.models.SlidingMenuItem;
import com.chickenkiller.upods2.models.SlidingMenuRow;
import com.chickenkiller.upods2.utils.Analytics;
import com.chickenkiller.upods2.utils.GlobalUtils;
import com.chickenkiller.upods2.utils.enums.MediaItemType;
import com.yandex.metrica.YandexMetrica;
import java.util.List;
            if (item instanceof SlidingMenuRow && ((SlidingMenuRow) (item)).getTitle().equals(itemName)) {
                ((SlidingMenuRow) (item)).isSelected = true;
                notifyDataSetChanged();
                return;
            }
        }
    }

    private class ViewHolderHeader extends RecyclerView.ViewHolder {
        public ImageView headerAvater;
        public TextView headerText;
        public TextView headerEmail;

        public ViewHolderHeader(View itemView) {
            super(itemView);
            this.headerAvater = (ImageView) itemView.findViewById(R.id.imgSMHeaderAvatar);
            this.headerText = (TextView) itemView.findViewById(R.id.tvSMHeaderName);
            this.headerEmail = (TextView) itemView.findViewById(R.id.tvSMHeaderEmail);
        }
    }

    public SlidingMenuAdapter(List<SlidingMenuItem> items, int itemLayout, ISlidingMenuManager slidingMenuManager,
                              IFragmentsManager fragmentsManager) {
        this(items, itemLayout, slidingMenuManager);
        this.fragmentsManager = fragmentsManager;
    }

    public SlidingMenuAdapter(List<SlidingMenuItem> items, int itemLayout, ISlidingMenuManager slidingMenuManager) {
        super();
        this.items = items;
        this.itemLayout = itemLayout;
        this.slidingMenuManager = slidingMenuManager;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        View view = null;
        RecyclerView.ViewHolder viewHolder = null;
        if (viewType == ITEM) {
            view = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
            viewHolder = new ViewHolderItem(view);
        } else {
            view = LayoutInflater.from(parent.getContext()).inflate(HEADER_LAYOUT, parent, false);
            viewHolder = new ViewHolderHeader(view);
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        SlidingMenuItem item = items.get(position);
        if (holder instanceof ViewHolderItem) {
            Context mContext = ((ViewHolderItem) holder).text.getContext();
            ((ViewHolderItem) holder).text.setText(((SlidingMenuRow) item).getTitle());
            if (((SlidingMenuRow) item).isSelected) {
                ((ViewHolderItem) holder).text.setTextColor(mContext.getResources().getColor(R.color.pink_A400));
                ((ViewHolderItem) holder).lnSlidingMenuItem.setBackgroundResource(R.drawable.selector_sliding_menu_selected_item);
                ((ViewHolderItem) holder).image.setImageResource(((SlidingMenuRow) item).getPressedIconId());
            } else {
                ((ViewHolderItem) holder).text.setTextColor(mContext.getResources().getColor(R.color.gray_202020));
                ((ViewHolderItem) holder).lnSlidingMenuItem.setBackgroundResource(R.drawable.selector_sliding_menu_item);
                ((ViewHolderItem) holder).image.setImageResource(((SlidingMenuRow) item).getMainIconId());
            }
            setSlidingMenuItemClick((ViewHolderItem) holder, position);
        } else if (holder instanceof ViewHolderHeader) {
            SlidingMenuHeader headerItem = (SlidingMenuHeader) item;
            final ViewHolderHeader viewHolderHeader = (ViewHolderHeader) holder;
            final Context mContext = viewHolderHeader.headerText.getContext();

            viewHolderHeader.headerText.setText(headerItem.getName());
            //viewHolderHeader.headerEmail.setText(headerItem.getEmail());

            Glide.with(mContext).load(headerItem.getImgUrl()).asBitmap().centerCrop().into(new BitmapImageViewTarget(viewHolderHeader.headerAvater) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable =
                            RoundedBitmapDrawableFactory.create(mContext.getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    viewHolderHeader.headerAvater.setImageDrawable(circularBitmapDrawable);
                }
            });
        }
        holder.itemView.setTag(item);
    }

    private void setSlidingMenuItemClick(ViewHolderItem viewHolderItem, final int position) {
        viewHolderItem.setItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (items.get(position) instanceof SlidingMenuRow) {
                    clearRowSelections();
                    SlidingMenuRow clickedMenuItem = (SlidingMenuRow) items.get(position);
                    clickedMenuItem.isSelected = true;
                    Context context = view.getContext();
                    slidingMenuManager.toggle();
                    if (clickedMenuItem.getTitle().equals(context.getString(R.string.main_settings))) {
                        YandexMetrica.reportEvent(Analytics.SLIDING_MENU_SETTINGS_CLICK);
                        FragmentSettings settingsFragment = new FragmentSettings();
                        fragmentsManager.showFragment(R.id.fl_content, settingsFragment, FragmentSettings.TAG);
                    } else if (clickedMenuItem.getTitle().equals(context.getString(R.string.podcasts_main))) {
                        YandexMetrica.reportEvent(Analytics.SLIDING_MENU_PODCASTS_CLICK);
                        FragmentMediaItemsGrid fragmentMediaItemsGrid = new FragmentMediaItemsGrid();
                        fragmentMediaItemsGrid.setMediaItemType(MediaItemType.PODCAST);
                        fragmentsManager.showFragment(R.id.fl_content, fragmentMediaItemsGrid, FragmentMediaItemsGrid.TAG);
                    } else if (clickedMenuItem.getTitle().equals(context.getString(R.string.radio_main))) {
                        YandexMetrica.reportEvent(Analytics.SLIDING_MENU_RADIO_CLICK);
                        FragmentMediaItemsGrid fragmentMediaItemsGrid = new FragmentMediaItemsGrid();
                        fragmentMediaItemsGrid.setMediaItemType(MediaItemType.RADIO);
                        fragmentsManager.showFragment(R.id.fl_content, fragmentMediaItemsGrid, FragmentMediaItemsGrid.TAG);
                    } else if (clickedMenuItem.getTitle().equals(context.getString(R.string.profile_my_profile))) {
                        YandexMetrica.reportEvent(Analytics.SLIDING_MENU_PROFILE_CLICK);
                        FragmentProfile fragmentProfile = new FragmentProfile();
                        fragmentsManager.showFragment(R.id.fl_content, fragmentProfile, FragmentProfile.TAG);
                    } else if (clickedMenuItem.getTitle().equals(context.getString(R.string.main_help))) {
                        YandexMetrica.reportEvent(Analytics.SLIDING_MENU_HELP_CLICK);
                        FragmentHelp fragmentHelp = new FragmentHelp();
                        fragmentHelp.isFromSlidingMenu = true;
                        fragmentsManager.showFragment(R.id.fl_content, fragmentHelp, FragmentHelp.TAG);
                    } else if (clickedMenuItem.getTitle().equals(context.getString(R.string.main_about))) {
                        YandexMetrica.reportEvent(Analytics.SLIDING_MENU_ABOUT_CLICK);
                        DialogFragmentAbout dialogFragmentAbout = new DialogFragmentAbout();