/*
 * ************************************************************************
 *
 * ADOBE SYSTEMS INCORPORATED
 * Copyright 2013 Adobe Systems Incorporated
 * All Rights Reserved.
 * NOTICE:  Adobe permits you to use, modify, and distribute this file in accordance with the 
 * terms of the Adobe license agreement accompanying it.  If you have received this file from a 
 * source other than Adobe, then your use, modification, or distribution of it requires the prior 
 * written permission of Adobe.
 *
 **************************************************************************
 */

package com.adobe.primetime.reference.ui.catalog;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Toast;
import com.adobe.mediacore.PSDKErrorCode;
import com.adobe.mediacore.MediaPlayerItem;
import com.adobe.mediacore.MediaPlayerItemLoader;
import com.adobe.primetime.reference.PrimetimeReference;
import com.adobe.primetime.reference.R;
import com.adobe.primetime.reference.manager.DrmManager;
import com.adobe.primetime.reference.manager.EntitlementManager;
import com.adobe.primetime.reference.manager.InstantOnManager;
import com.adobe.primetime.reference.manager.ManagerFactory;
import com.adobe.primetime.reference.ui.entitlement.EntitlementDialogFragment;
import com.adobe.primetime.reference.ui.log.LogActivity;
import com.adobe.primetime.reference.ui.player.PlayerActivity;
import com.adobe.primetime.reference.ui.settings.SettingsActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class CatalogActivity extends AppCompatActivity implements
		View.OnClickListener, ActionBar.TabListener, EntitlementDialogFragment.EntitlementDialogListener {
	private final String LOG_TAG = PrimetimeReference.LOG_APP_NAME + "CatalogActivity";

	private final String TAB_LIVE = "live";
	private final String TAB_VOD = "vod";
	private final String TAB_STREAM_INFO = "stream_info";
	private final String SELECTED_TAB_TAG = "selected_tab_tag";
	private SharedPreferences sharedPreferences;
	private String lastLoadedUrl = "";

	private ContentLoadingView contentLoadingView;

	private final ArrayList<VideoItem> liveContentList = new ArrayList<VideoItem>();
	private final ArrayList<VideoItem> vodContentList = new ArrayList<VideoItem>();

	private final ContentRequest contentRequest = new ContentRequest();

	private ProgressDialog loadingDialog;

    // manager for entitlement workflows against the Adobe Primetime PayTV Pass service
    private EntitlementManager entitlementManager;

    // entitlement dialog fragment tag in fragment manager
    private static final String DIALOG_TAG = "entitlement_dialog";

    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_catalog);
		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

		contentLoadingView = (ContentLoadingView) getSupportFragmentManager()
				.findFragmentById(R.id.catalogContentLoadingFragment);

        entitlementManager = ManagerFactory.getEntitlementManager();

        resetActionBar();

	}

	@Override
	protected void onStart() {
		super.onStart();

		retrieveContentCatalog();

        // when activity starts, check authentication status to keep ui elements updated
        // the user's authentication status should be checked when the activity returns from the background
        // so, it should be checked frequently but not too frequently
        entitlementManager.checkAuthentication();
	}

	private void retrieveContentCatalog() {
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		String contentUrl = sharedPreferences.getString(PrimetimeReference.SETTINGS_CONTENT_URL_KEY,
				getString(R.string.contentUrl));

		PrimetimeReference.logger.i(LOG_TAG + "#retrieveContentCatalog",
				"Retrieving catalog content from: " + contentUrl);

		getSupportActionBar().removeAllTabs();

		contentLoadingView.getView().setVisibility(View.VISIBLE);
		contentLoadingView.showLoadInProgress();

		liveContentList.clear();
		vodContentList.clear();

		if (!lastLoadedUrl.equals(contentUrl))
		{
			// clear InstantOn items if loading a new catalog
			InstantOnManager.clear();
		}

		if (URLUtil.isValidUrl(contentUrl))
		{
			// make HTTP request for catalog, will trigger either onComplete or onError listener
			contentRequest.doRequest(contentUrl);

		}
		else {
			String content = readStaticCatalog(contentUrl);
			requestContentCatalogOnCompleteListener.onComplete(content);
		}

		lastLoadedUrl = contentUrl;
	}

	private String readStaticCatalog(String filename) {
		BufferedReader reader = null;
		StringBuilder builder = new StringBuilder();

		try {
			reader = new BufferedReader(
					new InputStreamReader(getAssets().open(filename), "UTF-8"));

			String line;

			while ((line = reader.readLine()) != null)
			{
				builder.append(line);
			}

		}
		catch (IOException e) {
			PrimetimeReference.logger.e(LOG_TAG, "Failed to read static catalog: " + e.getMessage());
		}
		finally {
			if (reader != null)
			{
				try {
					reader.close();
				}
				catch (IOException e)
				{
					PrimetimeReference.logger.e(LOG_TAG, "Error closing file reader: " + e.getMessage());
				}
			}
		}

		return builder.toString();
	}

	private void resetActionBar() {

        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayHomeAsUpEnabled(false);

        ActionBar.Tab vodTab = actionBar
                .newTab()
                .setText(R.string.ActionBarTabVOD)
                .setTag(TabTag.getInstance(TAB_VOD, CatalogView.class.getName()))
                .setTabListener(this);

        ActionBar.Tab liveTab = actionBar
                .newTab()
                .setText(R.string.ActionBarTabLive)
                .setTag(TabTag.getInstance(TAB_LIVE, CatalogView.class.getName()))
                .setTabListener(this);

        ActionBar.Tab streamInfoTab = actionBar
                .newTab()
                .setText(R.string.ActionBarTabStreamInfo)
                .setTag(TabTag.getInstance(TAB_STREAM_INFO, StreamInfoView.class.getName()))
                .setTabListener(this);

		contentLoadingView.getView().setVisibility(View.INVISIBLE);
		actionBar.removeAllTabs();

		String selectedTab = sharedPreferences.getString(SELECTED_TAB_TAG, "");
		actionBar.addTab(vodTab, false);
		actionBar.addTab(liveTab);
		actionBar.addTab(streamInfoTab);

		if (selectedTab.equals(TAB_LIVE)) {
			actionBar.selectTab(liveTab);
		} else if (selectedTab.equals(TAB_STREAM_INFO)) {
			actionBar.selectTab(streamInfoTab);
		} else {
			actionBar.selectTab(vodTab);
		}
	}

	private void installListeners() {
		if (contentLoadingView != null) {
			contentLoadingView
					.addRefreshContentEventListener(refreshContentEventListener);
		}

		if (contentRequest != null) {
			contentRequest
					.addOnCompleteListener(requestContentCatalogOnCompleteListener);
			contentRequest
					.addOnErrorListener(requestContentCatalogOnErrorListener);
		}

        if (entitlementManager != null)
        {
            entitlementManager.addEventListener(entitlementManagerListener);
        }
	}

	private void uninstallListeners() {
		if (contentLoadingView != null) {
			contentLoadingView
					.removeRefreshContentEventListener(refreshContentEventListener);
		}

		if (contentRequest != null) {
			contentRequest
					.removeOnCompleteListener(requestContentCatalogOnCompleteListener);
			contentRequest
					.removeOnErrorListener(requestContentCatalogOnErrorListener);
		}

        if (entitlementManager != null)
        {
            entitlementManager.removeEventListener(entitlementManagerListener);
        }
	}

	@Override
	protected void onResume() {
		super.onResume();
		installListeners();

        // make sure the options menu get updated
        supportInvalidateOptionsMenu();
	}

	@Override
	protected void onPause() {
		uninstallListeners();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
        uninstallListeners();
		contentRequest.shutdown();
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();

		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		boolean showDRMTestTools = sharedPreferences.getBoolean(
				PrimetimeReference.SETTINGS_DRM_TESTING_ENABLE_TEST_TOOLS, false);

		inflater.inflate(R.menu.actionbar_catalog, menu);

		menu.findItem(R.id.ActionBarMetadata).setVisible(showDRMTestTools);
		menu.findItem(R.id.ActionBarLicense).setVisible(showDRMTestTools);
		menu.findItem(R.id.ActionBarAuthentication)
				.setVisible(showDRMTestTools);

        // show/hide entitlement sign in button
        MenuItem item = menu.findItem(R.id.ActionBarEntitlement);
        if (item != null)
        {
            item.setVisible(entitlementManager.isEnabled());
            if (entitlementManager.isAuthenticated())
            {
                item.setIcon(EntitlementManager.ICON_AUTH);
                item.setTitle(R.string.ActionBarEntitlementSignOut);
            }
            else
            {
                item.setIcon(EntitlementManager.ICON_KEY);
                item.setTitle(R.string.ActionBarEntitlementSignIn);
            }
        }

		return true;
	}

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        // show/hide entitlement sign in button
        MenuItem item = menu.findItem(R.id.ActionBarEntitlement);
        if (item != null)
        {
            if (entitlementManager.isAuthenticated())
            {
                item.setIcon(EntitlementManager.ICON_AUTH);
                item.setTitle(R.string.ActionBarEntitlementSignOut);
            }
            else
            {
                item.setIcon(EntitlementManager.ICON_KEY);
                item.setTitle(R.string.ActionBarEntitlementSignIn);
            }
        }

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
            case R.id.ActionBarContentRefresh:
                PrimetimeReference.logger.i(LOG_TAG + "#onOptionsItemSelected",
                        "Refresh content action bar item activated.");
				// clear Instant On items
				InstantOnManager.clear();

                retrieveContentCatalog();
				return true;

            case R.id.ActionBarLogs:
                PrimetimeReference.logger.i(LOG_TAG + "#onOptionsItemSelected",
                        "Logs action bar item activated.");
                intent = new Intent(this, LogActivity.class);
                startActivity(intent);
                return true;

            case R.id.ActionBarSettings:
                PrimetimeReference.logger.i(LOG_TAG + "#onOptionsItemSelected",
                        "Settings action bar item activated.");
                intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                return true;

            case R.id.ActionBarAbout:
                PrimetimeReference.logger.i(LOG_TAG + "#onOptionsItemSelected",
                        "About action bar item activated.");
                PrimetimeReference.showAbout(this);
                return true;

            // start authentication flow to Primetime PayTV Pass system
            case R.id.ActionBarEntitlement:
                PrimetimeReference.logger.i(LOG_TAG + "#onOptionsItemSelected",
                        "Entitlement action bar item activated.");

                entitlementManager.getAuthentication(this);
                return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

    @Override
    public void onClick(View view) {
    }

    /**
     * From ActionBar.TabListener, called when a tab enters the selected state. Attaches the fragment described by
     * the ActionBar.Tab tag object which puts in in view. If the fragment does not exist in the fragment manager,
     * it is first created.
     *
     * @param tab The tab that was selected
     * @param ft A {@link android.support.v4.app.FragmentTransaction} for queuing fragment operations
     *           to execute during a tab switch.
     */
	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
    {
        TabTag tabTag = (TabTag)tab.getTag();

        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tabTag.tag);

        if (fragment == null)
        {
            int viewId;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
            {
                viewId =  android.R.id.content;
            }
            else
            {
                viewId =  R.id.action_bar_activity_content;
            }

            fragment = Fragment.instantiate(this, tabTag.className);
            ft.add(viewId, fragment, tabTag.tag);
        }
        else
        {
            ft.attach(fragment);
        }

        if (TAB_LIVE.equals(tabTag.tag)) {
            ((CatalogView) fragment).updateContentList(liveContentList);
        } else if (TAB_VOD.equals(tabTag.tag)) {
            ((CatalogView) fragment).updateContentList(vodContentList);
        }

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(SELECTED_TAB_TAG, tabTag.tag);
        editor.putInt("selected_tab_index", tab.getPosition());
        editor.commit();

    }

    /**
     * From ActionBar.TabListener, called when a tab exists the selected state. Removes the tab's fragment from view.
     *
     * @param tab The tab that was unselected
     * @param ft A {@link android.support.v4.app.FragmentTransaction} for queuing fragment operations
     *           to execute during a tab switch.
     */
	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
    {
        TabTag tabTag = (TabTag)tab.getTag();
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tabTag.tag);
        if (fragment != null)
        {
            ft.detach(fragment);
        }

    }

    /**
     * From ActionBar.TabListener, called when a tab exists the selected state.
     * Nothing is performed on tab reselection in this context.
     *
     * @param tab The tab that was unselected
     * @param ft A {@link android.support.v4.app.FragmentTransaction} for queuing fragment operations
     *           to execute during a tab switch.
     */
	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
	}

    /**
     * Holds ActionBar.Tab Tag information. Specifically, holds the fragment class name of the tab and
     * the tag name used to reference the fragment in the fragment manager.
     */
    private static final class TabTag
    {
        private final String className;
        private final String tag;

        private TabTag(String tag, String className)
        {
            this.className = className;
            this.tag = tag;
        }

        public static TabTag getInstance(String tag, String className)
        {
            return new TabTag(tag, className);
        }

    }


	private final ContentRequest.OnCompleteListener requestContentCatalogOnCompleteListener = new ContentRequest.OnCompleteListener() {
		@Override
		public void onComplete(String response) {
			try {
				String vcmsType = PrimetimeReference.SETTINGS_VCMS_TYPE;

				if (!vcmsType.isEmpty()) {
					VideoItemParser videoItemParser = new VideoItemParser(
							response, vcmsType);
					liveContentList
							.addAll(videoItemParser.getLiveContentList());
					vodContentList.addAll(videoItemParser.getVodContentList());

					for (VideoItem item : vodContentList)
					{
						if(InstantOnManager.add(item))
						{
							InstantOnManager.addEventListener(item.getId(), instantOnBufferingCompleteListener);
						}
					}


					SharedPreferences sharedPreferences = PreferenceManager
							.getDefaultSharedPreferences(getApplicationContext());
					if (sharedPreferences.getBoolean(
							DrmManager.SETTINGS_DRM_PRE_CACHE, false)) {
						ArrayList<VideoItem> contentList = new ArrayList<VideoItem>();
						contentList
								.addAll(videoItemParser.getLiveContentList());
						contentList.addAll(videoItemParser.getVodContentList());
						/**
						 * This is a bad practice to preload DRM license for
						 * every single item. This is only an example of
						 * preloading DRM license. It is recommended to preload
						 * only the items you need to.
						 */
						for (VideoItem item : contentList) {
							DrmManager.preLoadDrmLicenses(item.getUrl(),
									new MediaPlayerItemLoader.LoaderListener() {

										@Override
										public void onLoadComplete(MediaPlayerItem item) {
											PrimetimeReference.logger
													.i(LOG_TAG + "::DRMPreload#onLoadComplete",
															item.getResource().getUrl());

										}

										@Override
										public void onBufferingBegin() {

										}
										
										@Override
										public void onBufferPrepared() {

										}

										@Override
										public void onError(PSDKErrorCode error, String s) {
											PrimetimeReference.logger.w(LOG_TAG + "::DRMPreload#onError",
													"Error attempting to pre-load DRM licenses (" +
															error + ") " + s);

										}
									}, getApplicationContext());
						}
					}

                    // add content list to entitlement manager for preauthorization resource check
                    ArrayList<VideoItem> contentList = new ArrayList<VideoItem>();
                    contentList.addAll(vodContentList);
                    contentList.addAll(liveContentList);
                    entitlementManager.setCurrentResources(contentList);
				}

			} catch (Exception e) {
				PrimetimeReference.logger
						.e(LOG_TAG
								+ "::ContentRequest.OnCompleteListener#onComplete",
								"Error parsing the catalog content list: "
										+ e.getMessage());
				Toast.makeText(CatalogActivity.this, "Invalid JSON format",
						Toast.LENGTH_SHORT).show();
			}

			PrimetimeReference.logger.i(LOG_TAG
							+ "::ContentRequest.OnCompleteListener#onComplete",
					"Catalog content successfully loaded.");
			resetActionBar();
		}
	};

	private final ContentRequest.OnErrorListener requestContentCatalogOnErrorListener = new ContentRequest.OnErrorListener() {
		@Override
		public void onError(String error) {
			PrimetimeReference.logger.e(LOG_TAG
					+ "::ContentRequest.OnErrorListener#onError",
					"Error retrieving the catalog content list: " + error);
			Toast.makeText(CatalogActivity.this,
					"Failed to load catalog content.", Toast.LENGTH_SHORT)
					.show();
			contentLoadingView.showErrorMessage();
			resetActionBar();
		}
	};

	private final ContentLoadingView.RefreshContentEventListener refreshContentEventListener = new ContentLoadingView.RefreshContentEventListener() {
		@Override
		public void onRefresh() {
			retrieveContentCatalog();
		}
	};


	/**
	 * Shows/hides a loading dialog.
	 * 
	 * @param loading
	 *            Whether to display or hide the dialog.
	 */
	public void setLoading(boolean loading) {
		// Cancel if a dialog is already active.
		if (loadingDialog != null)
			loadingDialog.cancel();

		if (!loading) {
			PrimetimeReference.logger.i(LOG_TAG + "::setLoading()",
					"Hiding the loading dialog.");
			loadingDialog = null;
		} else {
			PrimetimeReference.logger.i(LOG_TAG + "::setLoading()",
					"Displaying the loading dialog.");
			loadingDialog = new ProgressDialog(this,R.style.ProgressBarSpinner);
			loadingDialog.setCancelable(false);
			loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);    
			loadingDialog.setIndeterminate(true);
			loadingDialog.setIndeterminateDrawable(this.getResources().getDrawable(R.drawable.customprogress));
			loadingDialog.show();
		}
	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case (EntitlementManager.MVPD_PICKER_ACTIVITY):
            case (EntitlementManager.MVPD_LOGIN_ACTIVITY):
                entitlementManager.onAuthenticationActivityResult(requestCode, resultCode, data);
            break;
        }
    }

    /**
     * Called from the {@link com.adobe.primetime.reference.ui.entitlement.EntitlementDialogFragment}'s "OK" button
     * to dismiss the dialog or when the user clicks the device BACK button.
     * Dismisses the dialog fragment and returns to previous activity (CatalogActivity).
     *
     * @param status Status code passed to EntitlementDialogFragment on creation.
     */
    @Override
    public void onDialogDismiss(EntitlementManager.Status status)
    {
        PrimetimeReference.logger.d(LOG_TAG + "#onDialogDismiss", "Entitlement Dialog dismissed by user. " + status);

        // dismiss dialog fragment
        DialogFragment dialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(DIALOG_TAG);
        if (dialogFragment != null)
        {
            dialogFragment.dismiss();
        }

    }

    /**
     * Called from the {@link com.adobe.primetime.reference.ui.entitlement.EntitlementDialogFragment}'s "Logout" button
     * to initiate the authentication logout flow.
     *
     * @param status Status code passed to EntitlementDialogFragment on creation
     */
    @Override
    public void onDialogLogout(EntitlementManager.Status status)
    {
        PrimetimeReference.logger.d(LOG_TAG + "#onDialogLogout", "User initialated logout from entitlement dialog.");
        entitlementManager.logout(this);
    }


    /**
     * Display the entitlement dialog.
     *
     * @param status current entitlement flow status used to decorate the dialog window.
     * @param msg text message displayed to the user.
     * @see com.adobe.primetime.reference.ui.entitlement.EntitlementDialogFragment
     */
    private void displayEntitlementDialog(EntitlementManager.Status status, String msg)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();

        // dismiss any previous dialog
        DialogFragment previousDialog = (DialogFragment) fragmentManager.findFragmentByTag(DIALOG_TAG);
        if (previousDialog != null)
        {
            previousDialog.dismiss();
        }

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.disallowAddToBackStack();

        EntitlementDialogFragment dialogFragment = EntitlementDialogFragment.newInstance(status, msg, entitlementManager.getSelectedProvider());
        dialogFragment.show(fragmentTransaction, DIALOG_TAG);
    }

    private final EntitlementManager.EntitlementManagerListener entitlementManagerListener = new EntitlementManager.EntitlementManagerListener() {
        @Override
        public void onProgressStart() {
            setLoading(true);
        }

        @Override
        public void onProgressEnd() {
            setLoading(false);
        }

        @Override
        public void onDisplayNotificationDialog(EntitlementManager.Status status, String message) {
            displayEntitlementDialog(status, message);
        }

        @Override
        public void onAuthenticationStatusChange(boolean isAuthN) {
            // re-create options menu so icons are updated
            supportInvalidateOptionsMenu();
        }

        @Override
        public void onAuthorizationSuccess(String resourceId, VideoItem videoItem) {
            PrimetimeReference.logger.d(LOG_TAG + "#onAuthorizationSuccess", "Authorization success for resource " + resourceId);

            // start PlayerActivity to play content
            Intent intent = new Intent(CatalogActivity.this, PlayerActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra("CONTENT_INFO", videoItem);
            startActivity(intent);
        }

        @Override
        public void onPreauthorizedResourcesUpdate()
        {
            // set the selected tab, if it is a CatalogView, refresh its contents
            String selectedTab = sharedPreferences.getString(SELECTED_TAB_TAG, "");

            if (!"".equals(selectedTab))
            {
                FragmentManager fragmentManager = getSupportFragmentManager();
                Fragment fragment =  fragmentManager.findFragmentByTag(selectedTab);
                if (fragment != null && fragment instanceof CatalogView)
                {
                    ((CatalogView) fragment).refreshDataSet();
                }
            }

        }
    };

	private InstantOnManager.InstantOnItemBufferingCompleteListener instantOnBufferingCompleteListener = new InstantOnManager.InstantOnItemBufferingCompleteListener() {
		@Override
		public void onComplete(String id) {

			// set the selected tab, if it is a CatalogView, refresh its contents
			String selectedTab = sharedPreferences.getString(SELECTED_TAB_TAG, "");

			if (!"".equals(selectedTab))
			{
				FragmentManager fragmentManager = getSupportFragmentManager();
				Fragment fragment =  fragmentManager.findFragmentByTag(selectedTab);
				if (fragment != null && fragment instanceof CatalogView)
				{
					((CatalogView) fragment).refreshDataSet();
					PrimetimeReference.logger.e(LOG_TAG, "InstantOn buffering complete for (" + id + "), refreshing catalog");
				}
			}

		}
	};

}
