public class RobotoCheckBox extends CheckBox {

    /**
     * Simple constructor to use when creating a widget from code.
     *
     * @param context The Context the widget is running in, through which it can
     *                access the current theme, resources, etc.
     */
    public RobotoCheckBox(Context context) {
        super(context);
        onInitTypeface(context, null, 0);
    }

    /**
     * Constructor that is called when inflating a widget from XML. This is called
     * when a widget is being constructed from an XML file, supplying attributes
     * that were specified in the XML file. This version uses a default style of
     * 0, so the only attribute values applied are those in the Context's Theme
     * and the given AttributeSet.
     * <p/>
     * <p/>
     * The method onFinishInflate() will be called after all children have been
     * added.
     *
     * @param context The Context the widget is running in, through which it can
     *                access the current theme, resources, etc.
     * @param attrs   The attributes of the XML tag that is inflating the widget.
     * @see #RobotoCheckBox(Context, android.util.AttributeSet, int)
     */
    public RobotoCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
        onInitTypeface(context, attrs, 0);
    }

    /**
     * Perform inflation from XML and apply a class-specific base style. This
     * constructor of View allows subclasses to use their own base style when
     * they are inflating.
     *
     * @param context  The Context the widget is running in, through which it can
     *                 access the current theme, resources, etc.
     * @param attrs    The attributes of the XML tag that is inflating the widget.
     * @param defStyle The default style to apply to this widget. If 0, no style
     *                 will be applied (beyond what is included in the theme). This may
     *                 either be an attribute resource, whose value will be retrieved
     *                 from the current theme, or an explicit style resource.
     * @see #RobotoCheckBox(Context, AttributeSet)
     */
    public RobotoCheckBox(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        onInitTypeface(context, attrs, defStyle);
    }

    /**
     * Setup Roboto typeface.
     *
     * @param context  The Context the widget is running in, through which it can
     *                 access the current theme, resources, etc.
     * @param attrs    The attributes of the XML tag that is inflating the widget.
     * @param defStyle The default style to apply to this widget. If 0, no style
     *                 will be applied (beyond what is included in the theme).
     */
    private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
        // Typeface.createFromAsset doesn't work in the layout editor, so skipping.
        if (isInEditMode()) {
            return;
        }

        int typefaceValue = 0;
        if (attrs != null) {
            TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
            typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
            values.recycle();
        }

        Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue);
        setTypeface(robotoTypeface);
    }

} public class RobotoEditText extends EditText {

    /**
     * Simple constructor to use when creating a widget from code.
     *
     * @param context The Context the widget is running in, through which it can
     *                access the current theme, resources, etc.
     */
    public RobotoEditText(Context context) {
        super(context);
        onInitTypeface(context, null, 0);
    }

    /**
     * Constructor that is called when inflating a widget from XML. This is called
     * when a widget is being constructed from an XML file, supplying attributes
     * that were specified in the XML file. This version uses a default style of
     * 0, so the only attribute values applied are those in the Context's Theme
     * and the given AttributeSet.
     * <p/>
     * <p/>
     * The method onFinishInflate() will be called after all children have been
     * added.
     *
     * @param context The Context the widget is running in, through which it can
     *                access the current theme, resources, etc.
     * @param attrs   The attributes of the XML tag that is inflating the widget.
     * @see #RobotoEditText(Context, android.util.AttributeSet, int)
     */
    public RobotoEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        onInitTypeface(context, attrs, 0);
    }

    /**
     * Perform inflation from XML and apply a class-specific base style. This
     * constructor of View allows subclasses to use their own base style when
     * they are inflating.
     *
     * @param context  The Context the widget is running in, through which it can
     *                 access the current theme, resources, etc.
     * @param attrs    The attributes of the XML tag that is inflating the widget.
     * @param defStyle The default style to apply to this widget. If 0, no style
     *                 will be applied (beyond what is included in the theme). This may
     *                 either be an attribute resource, whose value will be retrieved
     *                 from the current theme, or an explicit style resource.
     * @see #RobotoEditText(Context, AttributeSet)
     */
    public RobotoEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        onInitTypeface(context, attrs, defStyle);
    }

    /**
     * Setup Roboto typeface.
     *
     * @param context  The Context the widget is running in, through which it can
     *                 access the current theme, resources, etc.
     * @param attrs    The attributes of the XML tag that is inflating the widget.
     * @param defStyle The default style to apply to this widget. If 0, no style
     *                 will be applied (beyond what is included in the theme).
     */
    private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
        // Typeface.createFromAsset doesn't work in the layout editor, so skipping.
        if (isInEditMode()) {
            return;
        }

        int typefaceValue = 0;
        if (attrs != null) {
            TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
            typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
            values.recycle();
        }

        Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue);
        setTypeface(robotoTypeface);
    }

} public class RobotoTextView extends TextView {

    /**
     * Simple constructor to use when creating a widget from code.
     *
     * @param context The Context the widget is running in, through which it can
     *                access the current theme, resources, etc.
     */
    public RobotoTextView(Context context) {
        super(context);
        onInitTypeface(context, null, 0);
    }

    /**
     * Constructor that is called when inflating a widget from XML. This is called
     * when a widget is being constructed from an XML file, supplying attributes
     * that were specified in the XML file. This version uses a default style of
     * 0, so the only attribute values applied are those in the Context's Theme
     * and the given AttributeSet.
     * <p/>
     * <p/>
     * The method onFinishInflate() will be called after all children have been
     * added.
     *
     * @param context The Context the widget is running in, through which it can
     *                access the current theme, resources, etc.
     * @param attrs   The attributes of the XML tag that is inflating the widget.
     * @see #RobotoTextView(Context, AttributeSet, int)
     */
    public RobotoTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        onInitTypeface(context, attrs, 0);
    }

    /**
     * Perform inflation from XML and apply a class-specific base style. This
     * constructor of View allows subclasses to use their own base style when
     * they are inflating.
     *
     * @param context  The Context the widget is running in, through which it can
     *                 access the current theme, resources, etc.
     * @param attrs    The attributes of the XML tag that is inflating the widget.
     * @param defStyle The default style to apply to this widget. If 0, no style
     *                 will be applied (beyond what is included in the theme). This may
     *                 either be an attribute resource, whose value will be retrieved
     *                 from the current theme, or an explicit style resource.
     * @see #RobotoTextView(Context, AttributeSet)
     */
    public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        onInitTypeface(context, attrs, defStyle);
    }

    /**
     * Setup Roboto typeface.
     *
     * @param context  The Context the widget is running in, through which it can
     *                 access the current theme, resources, etc.
     * @param attrs    The attributes of the XML tag that is inflating the widget.
     * @param defStyle The default style to apply to this widget. If 0, no style
     *                 will be applied (beyond what is included in the theme).
     */
    private void onInitTypeface(Context context, AttributeSet attrs, int defStyle) {
        // Typeface.createFromAsset doesn't work in the layout editor, so skipping.
        if (isInEditMode()) {
            return;
        }

        int typefaceValue = 0;
        if (attrs != null) {
            TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.RobotoTextView, defStyle, 0);
            typefaceValue = values.getInt(R.styleable.RobotoTextView_typeface, 0);
            values.recycle();
        }

        Typeface robotoTypeface = RobotoTypefaceManager.obtaintTypeface(context, typefaceValue);
        setTypeface(robotoTypeface);
    }

} public class Utils {

    private static final String TAG = LogUtils.makeLogTag(Utils.class);
    private static final String KEY_IMAGES = "images";
    private static final String KEY_URL = "movie-urls";
    private static final String KEY_CONTENT_TYPE = "content-type";
    private static final String KEY_STREAM_TYPE = "stream-type";
    private static final String KEY_CUSTOM_DATA = "custom-data";

    /**
     * @return true if API level > 8 (2.2)
     */
    public static boolean hasFroyo() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    /**
     * @return true if API level > 9 (2.2)
     */
    public static boolean hasGingerbread() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
    }

    /**
     * @return true if API level > 11 (3.0)
     */
    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    /**
     * @return true if API level > 12 (3.1)
     */
    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
    }

    /**
     * @return true if API level > 14 (4.0)
     */
    public static boolean hasICS() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
    }

    /**
     * @return true if API level > 16 (4.1)
     */
    public static boolean hasJellyBean() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }

    /**
     * @return true if API level > 18 (4.3)
     */
    public static boolean hasJellyBeanMR2() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
    }

    /**
     * @return true if API level > 19 (4.4)
     */
    public static boolean hasKitKat() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }

    /**
     * Formats time in milliseconds to hh:mm:ss string format.
     *
     * @param millis
     * @return
     */
    public static String formatMillis(int millis) {
        String result = "";
        int hr = millis / 3600000;
        millis %= 3600000;
        int min = millis / 60000;
        millis %= 60000;
        int sec = millis / 1000;
        if (hr > 0) {
            result += hr + ":";
        }
        if (min >= 0) {
            if (min > 9) {
                result += min + ":";
            } else {
                result += "0" + min + ":";
            }
        }
        if (sec > 9) {
            result += sec;
        } else {
            result += "0" + sec;
        }
        return result;
    }

    /**
     * A utility method to show a simple error dialog. The textual content of the dialog is provided
     * through the passed-in resource id.
     *
     * @param context
     * @param resourceId
     */
    public static final void showErrorDialog(Context context, int resourceId) {
        showErrorDialog(context, context.getString(resourceId));
    }

    /**
     * A utility method to show a simple error dialog.
     *
     * @param context
     * @param message The message to be shown in the dialog
     */
    public static final void showErrorDialog(Context context, String message) {
        new AlertDialog.Builder(context).setTitle(R.string.error)
                .setMessage(message)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                })
                .create()
                .show();
    }

    /**
     * Returns the URL of an image for the {@link MediaInformation} at the given level. Level should
     * be a number between 0 and <code>n - 1</code> where <code>n
     * </code> is the number of images for that given item.
     *
     * @param info
     * @param level
     * @return
     */
    public static String getImageUrl(MediaInfo info, int level) {
        MediaMetadata mm = info.getMetadata();
        if (null != mm && mm.getImages().size() > level) {
            return mm.getImages().get(level).getUrl().toString();
        }
        return null;
    }

    /**
     * Saves a string value under the provided key in the preference manager. If <code>value</code>
     * is <code>null</code>, then the provided key will be removed from the preferences.
     *
     * @param context
     * @param key
     * @param value
     */
    public static void saveStringToPreference(Context context, String key, String value) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        if (null == value) {
            // we want to remove
            pref.edit().remove(key).apply();
        } else {
            pref.edit().putString(key, value).apply();
        }
    }

    /**
     * Saves a float value under the provided key in the preference manager. If <code>value</code>
     * is <code>Float.MIN_VALUE</code>, then the provided key will be removed from the preferences.
     *
     * @param context
     * @param key
     * @param value
     */
    public static void saveFloatToPreference(Context context, String key, float value) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        if (Float.MIN_VALUE == value) {
            // we want to remove
            pref.edit().remove(key).apply();
        } else {
            pref.edit().putFloat(key, value).apply();
        }

    }

    /**
     * Retrieves a String value from preference manager. If no such key exists, it will return
     * <code>null</code>.
     *
     * @param context
     * @param key
     * @return
     */
    public static String getStringFromPreference(Context context, String key) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        return pref.getString(key, null);
    }

    /**
     * Retrieves a float value from preference manager. If no such key exists, it will return
     * <code>Float.MIN_VALUE</code>.
     *
     * @param context
     * @param key
     * @return
     */
    public static float getFloatFromPreference(Context context, String key) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        return pref.getFloat(key, Float.MIN_VALUE);
    }

    /**
     * Retrieves a boolean value from preference manager. If no such key exists, it will return the
     * value provided as <code>defaultValue</code>
     *
     * @param context
     * @param key
     * @param defaultValue
     * @return
     */
    public static boolean getBooleanFromPreference(Context context, String key,
                                                   boolean defaultValue) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        return pref.getBoolean(key, defaultValue);
    }

    /**
     * A utility method to validate that the appropriate version of the Google Play Services is
     * available on the device. If not, it will open a dialog to address the issue. The dialog
     * displays a localized message about the error and upon user confirmation (by tapping on
     * dialog) will direct them to the Play Store if Google Play services is out of date or missing,
     * or to system settings if Google Play services is disabled on the device.
     *
     * @param activity
     * @return
     */
    public static boolean checkGooglePlayServices(final Activity activity) {
        final int googlePlayServicesCheck = GooglePlayServicesUtil.isGooglePlayServicesAvailable(
                activity);
        switch (googlePlayServicesCheck) {
            case ConnectionResult.SUCCESS:
                return true;
            default:
                Dialog dialog = GooglePlayServicesUtil.getErrorDialog(googlePlayServicesCheck,
                        activity, 0);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        activity.finish();
                    }
                });
                dialog.show();
        }
        return false;
    }

    /**
     * @deprecated See <code>checkGooglePlayServices</code>
     */
    public static boolean checkGooglePlaySevices(final Activity activity) {
        return checkGooglePlayServices(activity);
    }

    /**
     * Builds and returns a {@link Bundle} which contains a select subset of data in the
     * {@link MediaInfo}. Since {@link MediaInfo} is not {@link Parcelable}, one can use this
     * container bundle to pass around from one activity to another.
     *
     * @param info
     * @return
     * @see <code>toMediaInfo()</code>
     */
    public static Bundle fromMediaInfo(MediaInfo info) {
        if (null == info) {
            return null;
        }

        MediaMetadata md = info.getMetadata();
        Bundle wrapper = new Bundle();
        wrapper.putString(MediaMetadata.KEY_TITLE, md.getString(MediaMetadata.KEY_TITLE));
        wrapper.putString(MediaMetadata.KEY_SUBTITLE, md.getString(MediaMetadata.KEY_SUBTITLE));
        wrapper.putString(KEY_URL, info.getContentId());
        wrapper.putString(MediaMetadata.KEY_STUDIO, md.getString(MediaMetadata.KEY_STUDIO));
        wrapper.putString(KEY_CONTENT_TYPE, info.getContentType());
        wrapper.putInt(KEY_STREAM_TYPE, info.getStreamType());
        if (!md.getImages().isEmpty()) {
            ArrayList<String> urls = new ArrayList<String>();
            for (WebImage img : md.getImages()) {
                urls.add(img.getUrl().toString());
            }
            wrapper.putStringArrayList(KEY_IMAGES, urls);
        }
        JSONObject customData = info.getCustomData();
        if (null != customData) {
            wrapper.putString(KEY_CUSTOM_DATA, customData.toString());
        }

        return wrapper;
    }

    /**
     * Builds and returns a {@link MediaInfo} that was wrapped in a {@link Bundle} by
     * <code>fromMediaInfo</code>.
     *
     * @param wrapper
     * @return
     * @see <code>fromMediaInfo()</code>
     */
    public static MediaInfo toMediaInfo(Bundle wrapper) {
        if (null == wrapper) {
            return null;
        }

        MediaMetadata metaData = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);

        metaData.putString(MediaMetadata.KEY_SUBTITLE,
                wrapper.getString(MediaMetadata.KEY_SUBTITLE));
        metaData.putString(MediaMetadata.KEY_TITLE, wrapper.getString(MediaMetadata.KEY_TITLE));
        metaData.putString(MediaMetadata.KEY_STUDIO, wrapper.getString(MediaMetadata.KEY_STUDIO));
        ArrayList<String> images = wrapper.getStringArrayList(KEY_IMAGES);
        if (null != images && !images.isEmpty()) {
            for (String url : images) {
                Uri uri = Uri.parse(url);
                metaData.addImage(new WebImage(uri));
            }
        }
        String customDataStr = wrapper.getString(KEY_CUSTOM_DATA);
        JSONObject customData = null;
        if (!TextUtils.isEmpty(customDataStr)) {
            try {
                customData = new JSONObject(customDataStr);
            } catch (JSONException e) {
                LOGE(TAG, "Failed to deserialize the custom data string: custom data= " + customDataStr);
            }
        }
        return new MediaInfo.Builder(wrapper.getString(KEY_URL))
                .setStreamType(wrapper.getInt(KEY_STREAM_TYPE))
                .setContentType(wrapper.getString(KEY_CONTENT_TYPE))
                .setMetadata(metaData)
                .setCustomData(customData)
                .build();
    }

    @SuppressLint("NewApi")
    public static void setStatusTint(Activity activity) {
        if (hasKitKat()) {
            Window w = activity.getWindow(); // in Activity's onCreate() for instance
            w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager tintManager = new SystemBarTintManager(activity);
            tintManager.setStatusBarTintColor(Color.parseColor("#33b5e5"));
            tintManager.setStatusBarTintEnabled(true);
        }
    }
} @ReportsCrashes(formKey = "", // we dont need a formkey for email
        mode = ReportingInteractionMode.DIALOG,
        resDialogText = R.string.crash_dialog_text,
        resDialogIcon = R.drawable.ic_launcher,
        resDialogTitle = R.string.crash_dialog_title,
        resDialogCommentPrompt = R.string.crash_dialog_comment_prompt,
        resDialogOkToast = R.string.crash_dialog_ok_toast,
        mailTo = "tvportalbugs@gmail.com"
)


public class TVPortalApplication extends Application {

    public static String ARG_LAUNCH_COUNT = "launch_count";
    private static Tracker mTracker;

    @Override
    public void onCreate() {
        super.onCreate();
        ACRA.init(this);
        SharedPreferences mPrefs;
        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        mPrefs.edit().putInt(ARG_LAUNCH_COUNT, (mPrefs.getInt(ARG_LAUNCH_COUNT, 0)) + 1).apply();
        //google analytics minimal just amount of install's and sessions
        mTracker = GoogleAnalytics.getInstance(this).getTracker(Config.GA_PROPERTY_ID);
        mTracker.send(MapBuilder.createEvent("UX", "appstart", null, null)
                        .set(Fields.SESSION_CONTROL, "start")
                        .build()
        );
        //Check if the user upgraded via the server:
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                AppUtils.isServerUpgraded(TVPortalApplication.this);
                return null;
            }
        }.execute();

    }


} public class LocalPlayerActivity extends ActionBarActivity {

    private static final String TAG = "LocalPlayerActivity";

    private VideoView mVideoView;
    private TextView mStartText;
    private TextView mEndText;
    private SeekBar mSeekbar;
    private ImageView mPlayPause;
    private ProgressBar mLoading;
    private View mControllers;
    private VideoCastManager mCastManager;
    private Timer mSeekbarTimer;
    private Timer mControllersTimer;
    private PlaybackLocation mLocation;
    private PlaybackState mPlaybackState;
    private final Handler mHandler = new Handler();
    private MediaInfo mLink;
    private boolean mControlersVisible;
    private int mDuration;
    private ActionBar mActionBar;
    protected MediaInfo mRemoteMediaInformation;
    private VideoCastConsumerImpl mCastConsumer;
    private LinearLayout mVidProgress;
    static int mFull = 0;
    private boolean mCastPlugin;
    RelativeLayout layout;

    RevMobBanner banner;
    SystemBarTintManager tintManager;
    View mRootView;

    /*
     * local or a remote playback
     */
    public static enum PlaybackLocation {
        LOCAL, REMOTE
    }

    /*
     * various states that we can be in
     */
    public static enum PlaybackState {
        PLAYING, PAUSED, BUFFERING, IDLE
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.player_activity);
        mRootView = getWindow().getDecorView();

        mCastManager = CastApplication.getCastManager(this);

        if (!mCastManager.isConnected()) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        }
        loadViews();


        RevMob revmob = RevMob.start(this); // RevMob App ID configured in the AndroidManifest.xml file
        banner = revmob.createBanner(this);
        //revmob.setTestingMode(RevMobTestingMode.WITH_ADS); // with this line, RevMob will always deliver a sample ad
        layout = (RelativeLayout) findViewById(R.id.container);


        mActionBar = getSupportActionBar();
        mActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#5A33b5e5")));
        mActionBar.setDisplayHomeAsUpEnabled(true);

        mVidProgress = (LinearLayout) findViewById(R.id.vidProgress);
        mVidProgress.setVisibility(View.VISIBLE);

        if (AppUtils.hasKitKat()) {
            tintManager = new SystemBarTintManager(LocalPlayerActivity.this);
        }
        setupControlsCallbacks();
        setupCastListener();

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            mLink = Utils.toMediaInfo(getIntent().getBundleExtra("media"));
            mVideoView.setVideoURI(Uri.parse(mLink.getContentId()));
            mVideoView.start();
            mPlaybackState = PlaybackState.PAUSED;
            updatePlaybackLocation(PlaybackLocation.LOCAL);
            mCastPlugin = AppUtils.isChromecastPluginInstalled(this);
            if (mCastPlugin) {
                if (mCastManager.isConnected()) {
                    finish();
                    loadRemoteMedia(0, true);
                }
            } else {
                if (mCastManager.isConnected()) {
                    AppUtils.showCastDialog(LocalPlayerActivity.this);
                }
            }

            startControllersTimer();
            togglePlayback();
            mRootView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    if (visibility == View.SYSTEM_UI_FLAG_VISIBLE) {
                        if (!mControlersVisible) {
                            updateControlersVisibility(true);

                        }
                        startControllersTimer();
                        mRootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                        //  mRootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
                    }
                }
            });
        }
    }


    private void setupCastListener() {
        mCastConsumer = new VideoCastConsumerImpl() {
            @Override
            public void onApplicationConnected(ApplicationMetadata appMetadata, String sessionId, boolean wasLaunched) {
                Log.d(TAG, "onApplicationLaunched() is reached");
                if (null != mLink) {
                    if (mPlaybackState == PlaybackState.PLAYING) {
                        mVideoView.pause();
                        try {
                            if (mCastPlugin) {
                                loadRemoteMedia(mSeekbar.getProgress(), true);
                                finish();
                            } else {
                                AppUtils.showCastDialog(LocalPlayerActivity.this);
                            }
                        } catch (Exception ignored) {
                        }
                    } else {
                        updatePlaybackLocation(PlaybackLocation.REMOTE);
                    }
                }
            }

            @Override
            public void onApplicationDisconnected(int errorCode) {
                Log.d(TAG, "onApplicationDisconnected() is reached with errorCode: " + errorCode);
                updatePlaybackLocation(PlaybackLocation.LOCAL);
            }

            @Override
            public void onDisconnected() {
                Log.d(TAG, "onDisconnected() is reached");
                mPlaybackState = PlaybackState.PAUSED;
                mLocation = PlaybackLocation.LOCAL;
            }

            @Override
            public void onRemoteMediaPlayerMetadataUpdated() {
                try {
                    mRemoteMediaInformation = mCastManager.getRemoteMediaInformation();
                } catch (Exception ignored) {
                }
            }

            @Override
            public void onFailed(int resourceId, int statusCode) {

            }

            @Override
            public void onConnectionSuspended(int cause) {
            }

            @Override
            public void onConnectivityRecovered() {
            }

        };
    }

    private void updatePlaybackLocation(PlaybackLocation location) {
        this.mLocation = location;
        if (location == PlaybackLocation.LOCAL) {
            if (mPlaybackState == PlaybackState.PLAYING || mPlaybackState == PlaybackState.BUFFERING) {
                startControllersTimer();
            } else {
                stopControllersTimer();
            }

        } else {
            stopControllersTimer();
            updateControlersVisibility(true);
        }
    }

    private void play(int position) {
        startControllersTimer();
        switch (mLocation) {
            case LOCAL:
                mVideoView.seekTo(position);
                mVideoView.start();
                break;
            case REMOTE:
                mPlaybackState = PlaybackState.BUFFERING;
                updatePlayButton(mPlaybackState);
                try {
                    mCastManager.play(position);
                } catch (Exception ignored) {
                }
                break;
            default:
                break;
        }
        restartTrickplayTimer();
    }

    private void togglePlayback() {
        stopControllersTimer();
        switch (mPlaybackState) {
            case PAUSED:
                switch (mLocation) {
                    case LOCAL:
                        mVideoView.start();
                        mPlaybackState = PlaybackState.PLAYING;
                        startControllersTimer();
                        restartTrickplayTimer();
                        updatePlaybackLocation(PlaybackLocation.LOCAL);
                        layout.removeView(banner);
                        break;
                    case REMOTE:
                        try {
                            mCastManager.checkConnectivity();
                            if (mCastPlugin) {
                                loadRemoteMedia(0, true);
                            }
                            finish();
                        } catch (Exception e) {
                            return;
                        }
                        break;
                    default:
                        break;
                }
                break;

            case PLAYING:
                mPlaybackState = PlaybackState.PAUSED;
                mVideoView.pause();
                if (AppUtils.canShowAds(this)) {
                    layout.addView(banner);
                }
                break;

            case IDLE:
                mVideoView.seekTo(0);
                mVideoView.start();
                mPlaybackState = PlaybackState.PLAYING;
                restartTrickplayTimer();
                break;

            default:
                break;
        }
        updatePlayButton(mPlaybackState);
    }

    private void loadRemoteMedia(int position, boolean autoPlay) {
        if (mCastPlugin) {
            mCastManager.startCastControllerActivity(this, mLink, position, autoPlay);
        }
    }


    private void stopTrickplayTimer() {
        Log.d(TAG, "Stopped TrickPlay Timer");
        if (null != mSeekbarTimer) {
            mSeekbarTimer.cancel();
        }
    }

    private void restartTrickplayTimer() {
        stopTrickplayTimer();
        mSeekbarTimer = new Timer();
        mSeekbarTimer.scheduleAtFixedRate(new UpdateSeekbarTask(), 100, 1000);
        Log.d(TAG, "Restarted TrickPlay Timer");
    }

    private void stopControllersTimer() {
        if (null != mControllersTimer) {
            mControllersTimer.cancel();
        }
    }

    private void startControllersTimer() {
        if (null != mControllersTimer) {
            mControllersTimer.cancel();
        }
        if (mLocation == PlaybackLocation.REMOTE) {
            return;
        }
        mControllersTimer = new Timer();
        mControllersTimer.schedule(new HideControllersTask(), 5000);
    }

    private void updateControlersVisibility(boolean show) {
        if (show) {

            mControllers.setVisibility(View.VISIBLE);
            if (mFull == 1) {
                mActionBar.show();
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                if (AppUtils.hasKitKat()) {
                    getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    tintManager = new SystemBarTintManager(LocalPlayerActivity.this);
                    tintManager.setStatusBarTintColor(Color.parseColor("#5A33b5e5"));
                    tintManager.setStatusBarTintEnabled(true);
                }
                mFull = 0;
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
                //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

            }
            mControllers.setVisibility(View.INVISIBLE);
            if (AppUtils.hasKitKat()) {
                tintManager.setStatusBarTintEnabled(false);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause() was called");
        if (mLocation == PlaybackLocation.LOCAL) {

            if (null != mSeekbarTimer) {
                mSeekbarTimer.cancel();
                mSeekbarTimer = null;
            }
            if (null != mControllersTimer) {
                mControllersTimer.cancel();
            }
            mVideoView.pause();
            mPlaybackState = PlaybackState.PAUSED;
            updatePlayButton(PlaybackState.PAUSED);
        }
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "onStop() was called");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy() is called");
        if (null != mCastManager) {
        }
        stopControllersTimer();
        stopTrickplayTimer();
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        Log.d(TAG, "onStart was called");
        super.onStart();
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "onResume() was called");
        mCastManager = CastApplication.getCastManager(this);
        mCastManager.addVideoCastConsumer(mCastConsumer);
        mCastManager.incrementUiCounter();
        super.onResume();
    }

    private class HideControllersTask extends TimerTask {

        @Override
        public void run() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mFull == 0) {
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                        if (AppUtils.hasKitKat()) {
                            getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                            tintManager.setStatusBarTintEnabled(false);
                        }
                        mActionBar.hide();

                        mFull = 1;
                    }
                    updateControlersVisibility(false);
                    mControlersVisible = false;
                }
            });

        }
    }

    private class UpdateSeekbarTask extends TimerTask {

        @Override
        public void run() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mLocation == PlaybackLocation.LOCAL) {
                        int currentPos = mVideoView.getCurrentPosition();
                        updateSeekbar(currentPos, mDuration);
                    }
                }
            });
        }
    }

    private void setupControlsCallbacks() {
        mVideoView.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mVideoView.stopPlayback();
                mPlaybackState = PlaybackState.IDLE;
                return false;
            }
        });

        mVideoView.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.d(TAG, "onPrepared is reached");
                mVidProgress.setVisibility(View.GONE);
                mDuration = mp.getDuration();
                mEndText.setText(Utils.formatMillis(mDuration));
                mSeekbar.setMax(mDuration);
                restartTrickplayTimer();
            }
        });

        mVideoView.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                stopTrickplayTimer();
                mPlaybackState = PlaybackState.IDLE;
                updatePlayButton(PlaybackState.IDLE);
                finish();
            }
        });

        mVideoView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!mControlersVisible) {
                    updateControlersVisibility(true);

                }
                startControllersTimer();
                return false;
            }
        });

        mSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mPlaybackState == PlaybackState.PLAYING) {
                    play(seekBar.getProgress());
                } else {
                    mVideoView.seekTo(seekBar.getProgress());
                }
                startControllersTimer();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                stopTrickplayTimer();
                mVideoView.pause();
                stopControllersTimer();
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mStartText.setText(Utils.formatMillis(progress));
            }
        });
        mPlayPause.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                togglePlayback();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mLocation == PlaybackLocation.LOCAL) {
            return super.onKeyDown(keyCode, event);
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            onVolumeChange(CastApplication.VOLUME_INCREMENT);
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            onVolumeChange(CastApplication.VOLUME_INCREMENT);
        } else {
            return super.onKeyDown(keyCode, event);
        }
        return true;
    }

    private void onVolumeChange(double volumeIncrement) {
        if (mCastManager == null) {
            return;
        }
        try {
            mCastManager.incrementVolume(volumeIncrement);
        } catch (Exception e) {
            Log.e(TAG, "onVolumeChange() Failed to change volume", e);
        }
    }

    private void updateSeekbar(int position, int duration) {
        mSeekbar.setProgress(position);
        mSeekbar.setMax(duration);
        mStartText.setText(Utils.formatMillis(position));
        mEndText.setText(Utils.formatMillis(duration));
    }

    private void updatePlayButton(PlaybackState state) {
        switch (state) {
            case PLAYING:
                mLoading.setVisibility(View.INVISIBLE);
                mPlayPause.setVisibility(View.VISIBLE);
                mPlayPause.setImageDrawable(
                        getResources().getDrawable(R.drawable.ic_av_pause_dark));
                break;
            case PAUSED:
            case IDLE:
                mLoading.setVisibility(View.INVISIBLE);
                mPlayPause.setVisibility(View.VISIBLE);
                mPlayPause.setImageDrawable(
                        getResources().getDrawable(R.drawable.ic_av_play_dark));
                break;
            case BUFFERING:
                mPlayPause.setVisibility(View.INVISIBLE);
                mLoading.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.player_menu, menu);
        mCastManager.addMediaRouterButton(menu, R.id.media_route_menu_item);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.action_share);
        if (!AppUtils.isPremiumInstalled(this)) {
            Drawable resIcon = getResources().getDrawable(android.R.drawable.ic_menu_share);
            resIcon.mutate().setColorFilter(Color.parseColor("#33b5e5"), PorterDuff.Mode.SRC_IN);
            item.setIcon(resIcon);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        switch (id) {
            case R.id.action_settings: {
                Intent intent = new Intent(LocalPlayerActivity.this, SettingsActivity.class);
                startActivity(intent);
                break;
            }
            case android.R.id.home: {
                finish();
                return true;
            }
            case R.id.action_share: {
                if (!AppUtils.canShowAds(this)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse(mLink.getContentId().toString()), "video/*");
                    startActivity(intent); // any text will be automatically disabled
                } else {
                    AppUtils.showUpgradeDialog(this);
                }

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

    private void loadViews() {
        mVideoView = (VideoView) findViewById(R.id.videoView1);
        mStartText = (TextView) findViewById(R.id.startText);
        mEndText = (TextView) findViewById(R.id.endText);
        mSeekbar = (SeekBar) findViewById(R.id.seekBar1);
        mPlayPause = (ImageView) findViewById(R.id.imageView2);
        mLoading = (ProgressBar) findViewById(R.id.progressBar1);
        mControllers = findViewById(R.id.controllers);
    }
} public class SettingsActivity extends PreferenceActivity {

    public static final String ARG_DEFAULT_PLAYER = "default_player";
    public static final String FTU_SHOWN_KEY = "ftu_shown";
    public static final String VOLUME_SELCTION_KEY = "volume_target";

    private VideoCastManager mCastManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mCastManager = CastApplication.getCastManager(this);

        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.application_preference);

        final Preference clearDefaultPlayer = findPreference("pref_clear_default_player");
        if (clearDefaultPlayer != null) {
            clearDefaultPlayer.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);
                    prefs.edit().remove(ARG_DEFAULT_PLAYER).apply();
                    return true;
                }
            });
        }
    }

    public static boolean isFtuShown(Context ctx) {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
        return sharedPref.getBoolean(FTU_SHOWN_KEY, false);
    }

    public static void setFtuShown(Context ctx) {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
        sharedPref.edit().putBoolean(FTU_SHOWN_KEY, true).commit();
    }

    @Override
    protected void onResume() {
        if (null != mCastManager) {
            mCastManager.incrementUiCounter();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (null != mCastManager) {
            mCastManager.decrementUiCounter();
        }
        super.onPause();
    }
} public class ChooserAdapter extends BaseAdapter {


    /**
     * Instance of {@link android.view.LayoutInflater}
     */
    private final LayoutInflater mInflater;

    private final Context mContext;

    private final String[] mTitles;

    private final TypedArray mIcons;

    /**
     * Constructor for <code>SeasonAdapter</code>
     *
     * @param context The {@link android.content.Context} to use
     */
    public ChooserAdapter(Context context, String[] titles, TypedArray icons) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mTitles = titles;
        mIcons = icons;
    }

    @Override
    public int getCount() {
        return mTitles.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Recycle the ViewHolder
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item_social, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // Bind the data
        holder.mTitle.setText(mTitles[position]);
        holder.mIcon.setImageResource(mIcons.getResourceId(position, -1));

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    /**
     * ViewHolder implementation
     */
    private static final class ViewHolder {

        private final RobotoTextView mTitle;
        private final ImageView mIcon;

        private ViewHolder(View convertView) {
            mTitle = (RobotoTextView) convertView.findViewById(R.id.text1);
            mIcon = (ImageView) convertView.findViewById(R.id.icon1);
        }
    }
} public class SocialAdapter extends BaseAdapter {


    /**
     * Instance of {@link android.view.LayoutInflater}
     */
    private final LayoutInflater mInflater;

    private final Context mContext;

    private final TypedArray mIcons;

    private final String[] mTitles;

    /**
     * Constructor for <code>SeasonAdapter</code>
     *
     * @param context The {@link android.content.Context} to use
     */
    public SocialAdapter(Context context, String[] titles, TypedArray icons) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mTitles = titles;
        mIcons = icons;
    }

    @Override
    public int getCount() {
        return mTitles.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Recycle the ViewHolder
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item_social, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // Bind the data
        holder.mTitle.setText(mTitles[position]);
        holder.mIcon.setImageResource(mIcons.getResourceId(position, -1));

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    /**
     * ViewHolder implementation
     */
    private static final class ViewHolder {

        private final RobotoTextView mTitle;
        private final ImageView mIcon;

        private ViewHolder(View convertView) {
            mTitle = (RobotoTextView) convertView.findViewById(R.id.text1);
            mIcon = (ImageView) convertView.findViewById(R.id.icon1);
        }
    }
} public class AsyncVersionCheck extends AsyncTask<String, Void, String> {

    public static final String TAG = "AsyncVersionCheck";

    private Context mContext;

    private String mVersion;
    private String mVersion_striped;

    private String mOperaVersion = null;
    private String mOperaVersion_striped;

    private int slideme = 0;
    private int tvp = 0;

    private File mOutputFile;

    private Document document;

    public AsyncVersionCheck(Context context, String version) {
        mContext = context;
        mVersion = version;
    }

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

    @Override
    protected String doInBackground(String... params) {
        try {
            Connection.Response response = Jsoup.connect("http://m.apps.opera.com/en_us/tv_portal_stream_tv_and_movies.html").userAgent("Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30").execute();
            int code = response.statusCode();
            if (code == 200) {

                document = Jsoup.connect("http://m.android-4-0-3-plus.apps.opera.com/en_us/tv_portal_stream_tv_and_movies.html").userAgent("Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30").get();
               Document deviceredirect = Jsoup.connect(document.baseUri()).userAgent("Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30").get();
               Elements element = deviceredirect.select(".pd-block").get(1).select("p");

              if (element.toString().contains("Version number:")){
                int Index = element.toString().indexOf("number:");
                int Indexend = element.toString().indexOf("]");
                  mOperaVersion = element.toString().substring(Index + 8, Indexend).toString();
            }
            } else {
                return null;
            }

            //Todo: Billy, why are we stripping this crap? Why can't we check our versionCode against the versioncode stored on our server?
            //Todo: I'm asking because sometimes your 'stripped' strings are returning null, and this seems way more complicated than it needs to be.

            //just remove everything thats not a number
            mVersion_striped = mVersion.replaceAll("[^0-9]", "");
            mOperaVersion_striped = mOperaVersion.replaceAll("[^0-9]", "");

            //check if string is null before transitioning to int
            if(mOperaVersion_striped  != null || mOperaVersion_striped != null){
                slideme = Integer.parseInt(mOperaVersion_striped);
                tvp = Integer.parseInt(mVersion_striped);}



            //Todo: This code is really broken
            //Cleaned up a lot more efficient switched to opera
            if (tvp != 0 || slideme != 0){
            if(slideme > tvp) {  //  Update TV Portal from Slideme

               //Get apk url
                Document doc4 = Jsoup.connect(document.baseUri())
                        .userAgent("Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
                        .get();

                Elements dlbutton = doc4.select(".download_buttons a");
                String hreff = dlbutton.attr("href");


                //Download apk to sd card
                URL url = new URL(hreff);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();

                String PATH = Environment.getExternalStorageDirectory() + "/download/";
                File file = new File(PATH);
                file.mkdirs();
                mOutputFile = new File(file, "Tv-Portal.v"+mOperaVersion+".apk");
                if (mOutputFile.exists()) {
                  mOutputFile.delete();
                }

                FileOutputStream fos = new FileOutputStream(mOutputFile);

                InputStream is = httpURLConnection.getInputStream();

                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, length);
                }
                fos.close();
                is.close();
            }
            }
        } catch (IOException ignored) {
        }
        return null;
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Todo: Still getting null pointer exceptions here
        //Better way to check to make sure were not getting null and that slide me version is larger
       if (tvp != 0 || slideme != 0){
        if(slideme > tvp) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(mContext.getString(R.string.update_available));
            builder.setIcon(R.drawable.ic_launcher);
            builder.setMessage(String.format(mContext.getString(R.string.new_version_available, mVersion, mOperaVersion)));
            builder.setPositiveButton(mContext.getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                   //Install from sdcard
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "Tv-Portal-slideme.v"+mOperaVersion+".apk")), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                }
            });

            builder.setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  //  mOutputFile.delete();
                }
            });
            builder.show();
            }
        }


    }
} public class FavoritesContentProvider extends ContentProvider {

    private FavoritesTable database;

    // Used for the Uri Matcher
    private static final int FAVORITES = 10;

    private static final int FAVORITE_ID = 20;

    private static final String AUTHORITY = "com.mitechlt.tvportal.play.favorites.contentprovider";

    private static final String BASE_PATH = "favorites";

    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);

    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        sURIMatcher.addURI(AUTHORITY, BASE_PATH, FAVORITES);
        sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", FAVORITE_ID);
    }

    @Override
    public boolean onCreate() {
        database = new FavoritesTable(getContext());
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {

        // Using SQLiteQueryBuilder instead of query() method
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        // Check if the caller has requested a column which does not exists
        checkColumns(projection);

        // Set the table
        queryBuilder.setTables(FavoritesTable.TABLE_FAVORITES);

        int uriType = sURIMatcher.match(uri);
        switch (uriType) {
            case FAVORITES:
                break;
            case FAVORITE_ID:
                // Adding the ID to the original query
                queryBuilder.appendWhere(FavoritesTable.COLUMN_ID + "="
                        + uri.getLastPathSegment());
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        SQLiteDatabase db = database.getWritableDatabase();
        Cursor cursor = queryBuilder.query(db, projection, selection,
                selectionArgs, null, null, sortOrder);
        // Make sure that potential listeners are getting notified
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        long id;
        switch (uriType) {
            case FAVORITES:
                id = sqlDB.insert(FavoritesTable.TABLE_FAVORITES, null, values);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return Uri.parse(BASE_PATH + "/" + id);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsDeleted = 0;
        switch (uriType) {
            case FAVORITES:
                rowsDeleted = sqlDB.delete(FavoritesTable.TABLE_FAVORITES, selection,
                        selectionArgs);
                break;
            case FAVORITE_ID:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsDeleted = sqlDB.delete(FavoritesTable.TABLE_FAVORITES,
                            FavoritesTable.COLUMN_ID + "=" + id,
                            null);
                } else {
                    rowsDeleted = sqlDB.delete(FavoritesTable.TABLE_FAVORITES,
                            FavoritesTable.COLUMN_ID + "=" + id
                                    + " and " + selection,
                            selectionArgs
                    );
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {

        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsUpdated = 0;
        switch (uriType) {
            case FAVORITES:
                rowsUpdated = sqlDB.update(FavoritesTable.TABLE_FAVORITES,
                        values,
                        selection,
                        selectionArgs);
                break;
            case FAVORITE_ID:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsUpdated = sqlDB.update(FavoritesTable.TABLE_FAVORITES,
                            values,
                            FavoritesTable.COLUMN_ID + "=" + id,
                            null);
                } else {
                    rowsUpdated = sqlDB.update(FavoritesTable.TABLE_FAVORITES,
                            values,
                            FavoritesTable.COLUMN_ID + "=" + id
                                    + " and "
                                    + selection,
                            selectionArgs
                    );
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

    private void checkColumns(String[] projection) {
        String[] available = {
                FavoritesTable.COLUMN_TITLE,
                FavoritesTable.COLUMN_LINK,
                FavoritesTable.COLUMN_ID,
                FavoritesTable.COLUMN_TYPE,
                FavoritesTable.COLUMN_IMAGE,
                FavoritesTable.COLUMN_RATING};
        if (projection != null) {
            HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
            HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
            // check if all columns which are requested are available
            if (!availableColumns.containsAll(requestedColumns)) {
                throw new IllegalArgumentException("Unknown columns in projection");
            }
        }
    }

} public class FavoritesTable extends SQLiteOpenHelper {

    public static final String TABLE_FAVORITES = "favorites";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_TYPE = "type";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_LINK = "link";
    public static final String COLUMN_IMAGE = "image";
    public static final String COLUMN_RATING = "rating";

    private static final String DATABASE_NAME = "favorites.db";
    private static final int DATABASE_VERSION = 3;

    private static final String DATABASE_CREATE = "create table "
            + TABLE_FAVORITES + "("
            + COLUMN_ID + " integer primary key autoincrement, "
            + COLUMN_TITLE + " text not null, "
            + COLUMN_LINK + " text not null, "
            + COLUMN_IMAGE + " text not null, "
            + COLUMN_TYPE + " text not null, "
            + COLUMN_RATING + " integer);";

    public FavoritesTable(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(FavoritesTable.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data"
        );
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
        onCreate(db);
    }

} public class RecentContentProvider extends ContentProvider {

    private RecentTable database;

    // Used for the Uri Matcher
    private static final int RECENT = 20;

    private static final int RECENT_ID = 30;

    private static final String AUTHORITY = "com.mitechlt.tvportal.play.recent.contentprovider";

    private static final String BASE_PATH = "recent";

    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);

    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        sURIMatcher.addURI(AUTHORITY, BASE_PATH, RECENT);
        sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", RECENT_ID);
    }

    @Override
    public boolean onCreate() {
        database = new RecentTable(getContext());
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {

        // Using SQLiteQueryBuilder instead of query() method
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        // Check if the caller has requested a column which does not exists
        checkColumns(projection);

        // Set the table
        queryBuilder.setTables(RecentTable.TABLE_RECENTS);

        int uriType = sURIMatcher.match(uri);
        switch (uriType) {
            case RECENT:
                break;
            case RECENT_ID:
                // Adding the ID to the original query
                queryBuilder.appendWhere(RecentTable.COLUMN_ID + "="
                        + uri.getLastPathSegment());
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        SQLiteDatabase db = database.getWritableDatabase();
        //Cursor cursor = queryBuilder.query(db, projection, selection,
        //      selectionArgs, null, null, null);
        Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, RecentTable.COLUMN_ID + " DESC");
        // Make sure that potential listeners are getting notified
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        long id;
        switch (uriType) {
            case RECENT:
                id = sqlDB.insert(RecentTable.TABLE_RECENTS, null, values);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return Uri.parse(BASE_PATH + "/" + id);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsDeleted = 0;
        switch (uriType) {
            case RECENT:
                rowsDeleted = sqlDB.delete(RecentTable.TABLE_RECENTS, selection,
                        selectionArgs);
                break;
            case RECENT_ID:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsDeleted = sqlDB.delete(RecentTable.TABLE_RECENTS,
                            FavoritesTable.COLUMN_ID + "=" + id,
                            null);
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;
    }


    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {

        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsUpdated = 0;
        switch (uriType) {
            case RECENT:
                rowsUpdated = sqlDB.update(RecentTable.TABLE_RECENTS,
                        values,
                        selection,
                        selectionArgs);
                break;
            case RECENT_ID:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsUpdated = sqlDB.update(RecentTable.TABLE_RECENTS,
                            values,
                            RecentTable.COLUMN_ID + "=" + id,
                            null);
                } else {
                    rowsUpdated = sqlDB.update(RecentTable.TABLE_RECENTS,
                            values,
                            RecentTable.COLUMN_ID + "=" + id
                                    + " and "
                                    + selection,
                            selectionArgs
                    );
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

    private void checkColumns(String[] projection) {
        String[] available = {
                RecentTable.COLUMN_ID,
                RecentTable.COLUMN_TYPE,
                RecentTable.COLUMN_TITLE,
                RecentTable.COLUMN_LINK,
                RecentTable.COLUMN_SEASON,
                RecentTable.COLUMN_EPISODE,
                RecentTable.COLUMN_IMAGE,
                RecentTable.COLUMN_NUM_SEASONS,
                RecentTable.COLUMN_NUM_EPISODES,
                RecentTable.COLUMN_RATING};
        if (projection != null) {
            HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
            HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
            // check if all columns which are requested are available
            if (!availableColumns.containsAll(requestedColumns)) {
                throw new IllegalArgumentException("Unknown columns in projection");
            }
        }
    }

} public class RecentTable extends SQLiteOpenHelper {

    public static final String TABLE_RECENTS = "recents";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_TYPE = "type";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_LINK = "link";
    public static final String COLUMN_SEASON = "season";
    public static final String COLUMN_EPISODE = "episode";
    public static final String COLUMN_IMAGE = "image";
    public static final String COLUMN_NUM_SEASONS = "num_seasons";
    public static final String COLUMN_NUM_EPISODES = "num_episodes";
    public static final String COLUMN_RATING = "rating";

    private static final String DATABASE_NAME = "recents.db";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE = "create table "
            + TABLE_RECENTS + "("
            + COLUMN_ID + " integer primary key autoincrement, "
            + COLUMN_TITLE + " text not null, "
            + COLUMN_LINK + " text not null, "
            + COLUMN_TYPE + " text not null, "
            + COLUMN_NUM_EPISODES + " text not null, "
            + COLUMN_NUM_SEASONS + " text not null, "
            + COLUMN_EPISODE + " text, "
            + COLUMN_SEASON + " text, "
            + COLUMN_IMAGE + " text not null, "
            + COLUMN_RATING + " integer);";

    public RecentTable(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(RecentTable.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data"
        );
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECENTS);
        onCreate(db);
    }

} public class TrackingContentProvider extends ContentProvider {

    private TrackingTable database;

    // Used for the Uri Matcher
    private static final int TRACKING = 10;

    private static final int TRACKING_ID = 20;

    private static final String AUTHORITY = "com.mitechlt.tvportal.play.tracking.contentprovider";

    private static final String BASE_PATH = "tracking";

    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);

    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        sURIMatcher.addURI(AUTHORITY, BASE_PATH, TRACKING);
        sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", TRACKING_ID);
    }

    @Override
    public boolean onCreate() {
        database = new TrackingTable(getContext());
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {

        // Using SQLiteQueryBuilder instead of query() method
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        // Check if the caller has requested a column which does not exists
        checkColumns(projection);

        // Set the table
        queryBuilder.setTables(TrackingTable.TABLE_TRACKING);

        int uriType = sURIMatcher.match(uri);
        switch (uriType) {
            case TRACKING:
                break;
            case TRACKING_ID:
                // Adding the ID to the original query
                queryBuilder.appendWhere(TrackingTable.COLUMN_ID + "="
                        + uri.getLastPathSegment());
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }

        SQLiteDatabase db = database.getWritableDatabase();
        Cursor cursor = queryBuilder.query(db, projection, selection,
                selectionArgs, null, null, sortOrder);
        // Make sure that potential listeners are getting notified
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        long id;
        switch (uriType) {
            case TRACKING:
                id = sqlDB.insert(TrackingTable.TABLE_TRACKING, null, values);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return Uri.parse(BASE_PATH + "/" + id);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsDeleted = 0;
        switch (uriType) {
            case TRACKING:
                rowsDeleted = sqlDB.delete(TrackingTable.TABLE_TRACKING, selection,
                        selectionArgs);
                break;
            case TRACKING_ID:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsDeleted = sqlDB.delete(TrackingTable.TABLE_TRACKING,
                            TrackingTable.COLUMN_ID + "=" + id,
                            null);
                } else {
                    rowsDeleted = sqlDB.delete(TrackingTable.TABLE_TRACKING,
                            TrackingTable.COLUMN_ID + "=" + id
                                    + " and " + selection,
                            selectionArgs);
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {

        int uriType = sURIMatcher.match(uri);
        SQLiteDatabase sqlDB = database.getWritableDatabase();
        int rowsUpdated = 0;
        switch (uriType) {
            case TRACKING:
                rowsUpdated = sqlDB.update(TrackingTable.TABLE_TRACKING,
                        values,
                        selection,
                        selectionArgs);
                break;
            case TRACKING_ID:
                String id = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsUpdated = sqlDB.update(TrackingTable.TABLE_TRACKING,
                            values,
                            TrackingTable.COLUMN_ID + "=" + id,
                            null);
                } else {
                    rowsUpdated = sqlDB.update(TrackingTable.TABLE_TRACKING,
                            values,
                            TrackingTable.COLUMN_ID + "=" + id
                                    + " and "
                                    + selection,
                            selectionArgs);
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

    private void checkColumns(String[] projection) {
        String[] available = {
                TrackingTable.COLUMN_EPISODE,
                TrackingTable.COLUMN_SEASON,
                TrackingTable.COLUMN_LINK,
                TrackingTable.COLUMN_ID,
                TrackingTable.COLUMN_WATCHED};
        if (projection != null) {
            HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
            HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
            // check if all columns which are requested are available
            if (!availableColumns.containsAll(requestedColumns)) {
                throw new IllegalArgumentException("Unknown columns in projection");
            }
        }
    }

} public class TrackingTable extends SQLiteOpenHelper {

    public static final String TABLE_TRACKING = "tracking";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_EPISODE = "episode";
    public static final String COLUMN_SEASON = "season";
    public static final String COLUMN_LINK = "link";
    public static final String COLUMN_WATCHED = "watched";

    private static final String DATABASE_NAME = "tracking.db";
    private static final int DATABASE_VERSION = 3;

    private static final String DATABASE_CREATE = "create table "
            + TABLE_TRACKING + "("
            + COLUMN_ID + " integer primary key autoincrement, "
            + COLUMN_EPISODE + " text not null, "
            + COLUMN_SEASON + " text not null, "
            + COLUMN_LINK + " text not null, "
            + COLUMN_WATCHED + " integer not null);";

    public TrackingTable(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TrackingTable.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data"
        );
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_TRACKING);
        onCreate(db);
    }

}
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.text.format.Time;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.devspark.robototextview.widget.RobotoCheckBox;
import com.devspark.robototextview.widget.RobotoEditText;
import com.devspark.robototextview.widget.RobotoTextView;
import com.google.android.gms.cast.MediaInfo;
import com.google.sample.castcompanionlibrary.cast.exceptions.CastException;
import com.google.sample.castcompanionlibrary.cast.exceptions.NoConnectionException;
import com.google.sample.castcompanionlibrary.cast.exceptions.TransientNetworkDisconnectionException;
import com.google.sample.castcompanionlibrary.utils.Utils;
import com.mitechlt.tvportal.play.R;
import com.mitechlt.tvportal.play.TVPortalApplication;
import com.mitechlt.tvportal.play.activities.LocalPlayerActivity;
import com.mitechlt.tvportal.play.activities.SettingsActivity;
import com.mitechlt.tvportal.play.adapters.ChooserAdapter;
import com.mitechlt.tvportal.play.adapters.SocialAdapter;
import com.mitechlt.tvportal.play.async.AsyncVersionCheck;
import com.mitechlt.tvportal.play.databases.FavoritesContentProvider;
import com.mitechlt.tvportal.play.databases.FavoritesTable;
import com.mitechlt.tvportal.play.databases.RecentContentProvider;
import com.mitechlt.tvportal.play.databases.RecentTable;
import com.mitechlt.tvportal.play.databases.TrackingContentProvider;
import com.mitechlt.tvportal.play.databases.TrackingTable;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, R.string.easter_egg_wrong_answer, Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    public static void showUpgradeDialog(final Context context) {
        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_share);

        final TextView mCastText = (TextView) dialog.findViewById(R.id.text1);
        mCastText.setText(R.string.pro_purchase);
        Button button = (Button) dialog.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setPackage("com.android.vending");
                    intent.setData(Uri.parse("market://details?id=" + Config.PLAY_STORE_UPGRADE_PACKAGE_NAME));
                    context.startActivity(intent);
                } catch (android.content.ActivityNotFoundException ignored) {
                    context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Config.SLIDEME_UPGRADE_URL)));
                }
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    public static void showCastDialog(final Context context) {

        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_cast);

        Button button = (Button) dialog.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setPackage("com.android.vending");
                    intent.setData(Uri.parse("market://details?id=" + Config.PLAY_STORE_CAST_UPGRADE_PACKAGE_NAME));
                    context.startActivity(intent);
                } catch (android.content.ActivityNotFoundException anfe) {
                    context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Config.SLIDEME_UPGRADE_URL)));
                }
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    public static void showChooserDialog(final Context context, final MediaInfo mediaInfo) {

        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        String[] itemTitles = context.getResources().getStringArray(R.array.playback_choices);
        TypedArray itemIcons = context.getResources().obtainTypedArray(R.array.playback_icons);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.chooser_dialog_title);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.dialog_chooser, null);
        final ChooserAdapter adapter = new ChooserAdapter(context, itemTitles, itemIcons);
        final ListView listView = (ListView) view.findViewById(android.R.id.list);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                listView.setItemChecked(position, true);
                switch (position) {
                    case 0:
                        break;

                    case 1:
                        if (!isPremiumInstalled(context)) {
                            showUpgradeDialog(context);
                        }
                        break;
                }
            }
        });
        builder.setView(view);
        builder.setNegativeButton(R.string.chooser_dialog_always, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                Log.i(TAG, "Selected position: " + listView.getSelectedItemPosition());

                //If the user clicked 'always', and they don't have pro, and they're trying to go to third party,
                // toast that premium is required (they've already been shown an upgrade dialog)
                if (!isPremiumInstalled(context) && listView.getCheckedItemPosition() == 1) {
                    Toast.makeText(context, R.string.pro_purchase, Toast.LENGTH_LONG).show();
                    return;
                }

                switch (listView.getCheckedItemPosition()) {
                    case 0:
                        //Save the selected item
                        prefs.edit().putInt(SettingsActivity.ARG_DEFAULT_PLAYER, DefaultPlayer.LOCAL).apply();

                        Intent intent = new Intent(context, LocalPlayerActivity.class);