package com.sharefaith.thesharefaithapp.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.appideas.base.AiSTr;
import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.adapters.SFBibleBookAdapter;
import com.sharefaith.thesharefaithapp.adapters.SFBibleVersionAdapter;
import com.sharefaith.thesharefaithapp.adapters.SFNavMenuAdapter;
import com.sharefaith.thesharefaithapp.base.SFAppData;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFBibleDownloader;
import com.sharefaith.thesharefaithapp.base.SFBibleWebView;
import com.sharefaith.thesharefaithapp.base.SFConfig;
import com.sharefaith.thesharefaithapp.base.SFConstants;
import com.sharefaith.thesharefaithapp.base.SFUtil;
import com.sharefaith.thesharefaithapp.models.SFBibleModel;
import com.sharefaith.thesharefaithapp.models.SFBookModel;

import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.kamranzafar.jtar.TarEntry;
import org.kamranzafar.jtar.TarInputStream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import io.sentry.Sentry;

/**
 * Creates and manages the Bible UI
 */
public class SFBibleActivity extends Activity
{
    private SFApplication mApplication;
    private SFConfig mConfig;
    private SFAppData mAppData;

    private ListView mMainNavList;
    private ImageView mRefreshButton;
    private ImageView mOpenSettingsButton;

    private GestureDetector mDetector;
    private View.OnTouchListener mGestureListener;
    private RelativeLayout mSlideRight;

    private SFBibleWebView mBibleWebView;
    private ImageView mLeftArrow;
    public ImageView mPlayButton;
    private ImageView mRightArrow;
    private RelativeLayout mListenButton;
    private TextView mSettingsButton;
    private TextView mDoneButton;
    private ImageView mSettingsImage;

    private ImageView mTheme1;
    private ImageView mTheme2;
    private ImageView mTheme3;
    private ImageView mTheme4;
    private TextView mFontFamily1;
    private TextView mFontFamily2;
    private TextView mFontFamily3;
    private TextView mTextSmall;
    private TextView mTextMedium;
    private TextView mTextLarge;
    private TextView mTopGradient;
    private TextView mBottomGradient;

    private TextView mCurrentThemeUnderline;
    private TextView mCurrentFontUnderline;
    private TextView mCurrentTextSizeUnderline;

    private int mTheme;
    private int mFontFamily;

    private String mThemeCSS;
    private String mFontFamilyCSS;
    private String mTextSizeCSS;

    private boolean mIsSettingsOpen;

    private Handler mAudioUpdateHandler;
    private Runnable mAudioDelay;

    private static Handler mFooterHandler;
    private static Runnable mHideFooter;

    private ListView mVersionList;
    private ListView mBooksList;
    private SFBibleVersionAdapter mBiblesAdapter;
    private SFBibleBookAdapter mBooksAdapter;
    private boolean mIsBibleVersionsOpen;

    private String mPreviousChapter;
    private String mPreviousVersion;
    private String mPreviousBook;
    private Boolean mArrowButtonLocked = false;

    /**
     * Creates the activity
     * @param savedInstanceState
     */
    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        this.requestWindowFeature( Window.FEATURE_NO_TITLE );
        setContentView( R.layout.sf_bible );

        //if not tablet keep screen from rotating
        if( !SFConfig.isTablet() )
        {
            setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
        }

        mApplication = SFApplication.getInstance();
        mAppData = new SFAppData();
        mIsSettingsOpen = false;

        //gesture detection
        mDetector = new GestureDetector( this, new SFGestureListener() );
        mGestureListener = new View.OnTouchListener()
        {
            public boolean onTouch( View v, MotionEvent event )
            {
                return mDetector.onTouchEvent( event );
            }
        };

        mAudioUpdateHandler = new Handler();
        mFooterHandler = new Handler();

        mIsBibleVersionsOpen = false;

        SFUtil.logSiteEvent( "Start Bible" );
    }

    /**
     * sets up activity whenever it is navigated to
     */
    @Override
    protected void onResume()
    {
        super.onResume();

        //Google Analytics tracking
        mApplication.logScreen("bible");

        mApplication.setCurrentActivity( this );
        mApplication.currentViewTag = "bible";
        if(mApplication.currentBiblePosition == -2)
        {
            this.finish();
            return;
        }
        mApplication.currentSectionPosition = mApplication.currentBiblePosition;
        mConfig = new SFConfig();

        try {

            String[] bibleVersions = mAppData.getBibleVersions(mAppData.getContentIdBySectionId(mAppData.getSectionIdByPosition(mApplication.currentBiblePosition)));

            if (bibleVersions.length < 1) {
                //This should be quite rare.
                Sentry.capture("Workaround onResume empty versions.");
                mApplication.forceSyncScreen();
                return;
            }


            mApplication.bibleModels = new SFBibleModel[bibleVersions.length];
            for (int i = 0; i < bibleVersions.length; i++) {
                mApplication.bibleModels[i] = new SFBibleModel(bibleVersions[i]);
            }
            //mApplication.bibleIndex = getCurrentBibleIndex();
            getBiblePosition();
            ArrayList<HashMap<String, String>> mBooksData = mAppData.getBooksData(mApplication.bibleModels[mApplication.bibleIndex].mId);
            mApplication.bookModels = new SFBookModel[mBooksData.size()];
            for (int i = 0; i < mBooksData.size(); i++) {
                mApplication.bookModels[i] = new SFBookModel(mBooksData.get(i));
            }
            setTitleBar();
            loadInterface();
            setupSettings();
            setListenButton();
            setupStyles();
            loadWebView();

            mLeftArrow.setOnClickListener(arrowListener("leftarrow"));
            mPlayButton.setOnClickListener(arrowListener("play"));
            mRightArrow.setOnClickListener(arrowListener("rightarrow"));

            mListenButton.setOnClickListener(footerButtonListener("listen"));
            mSettingsButton.setOnClickListener(footerButtonListener("settings"));

            mDoneButton.setOnClickListener(settingsListener("done"));
            mTheme1.setOnClickListener(settingsListener("theme1"));
            mTheme2.setOnClickListener(settingsListener("theme2"));
            mTheme3.setOnClickListener(settingsListener("theme3"));
            mTheme4.setOnClickListener(settingsListener("theme4"));
            mFontFamily1.setOnClickListener(settingsListener("font1"));
            mFontFamily2.setOnClickListener(settingsListener("font2"));
            mFontFamily3.setOnClickListener(settingsListener("font3"));
            mTextSmall.setOnClickListener(settingsListener("size_small"));
            mTextMedium.setOnClickListener(settingsListener("size_medium"));
            mTextLarge.setOnClickListener(settingsListener("size_large"));
            mBibleWebView.setOnTouchListener(mGestureListener);
            mBibleWebView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return true;
                }
            });

            mHideFooter = new Runnable() {
                @Override
                public void run() {
                    hideMenus();
                }
            };

            resetFooterHandler();
            setAudioControls();
            mApplication.didResume(mConfig);
        }catch (ArrayIndexOutOfBoundsException e){
            Sentry.capture("Workaround for - ArrayIndexOutofBound Exception onResume : "+ e.getMessage());
            mApplication.forceSyncScreen();
            return;
        }
    }

    /**
     * Sets up the UI for the Title Bar
     */
    private void setTitleBar()
    {
        mBiblesAdapter = new SFBibleVersionAdapter( mApplication.bibleModels );
        mVersionList = (ListView) findViewById( R.id.bible_version_listView );
        mVersionList.setAdapter( mBiblesAdapter );
        mVersionList.setOnItemClickListener( mBiblesAdapter.handleTap( this ) );
        mVersionList.setOnItemLongClickListener( mBiblesAdapter.handleLongPress( this ) );

        mBooksAdapter = new SFBibleBookAdapter( mApplication.bookModels );
        mBooksList = (ListView) findViewById( R.id.book_select_listView );
        mBooksList.setAdapter( mBooksAdapter );
    }

    /**
     * Sets up the UI for settings
     */
    private void setupSettings()
    {
        //setup the webview
        mTheme = mAppData.getBibleTheme();
        if(mTheme == 0)
        {
            mTheme = 1;
            mAppData.setBibleTheme( mTheme );
        }
        mFontFamily = mAppData.getBibleFont();
        if(mFontFamily == 0)
        {
            mFontFamily = 1;
            mAppData.setBibleFont( mFontFamily );
        }

        mLeftArrow = (ImageView) findViewById( R.id.left_arrow );
        mPlayButton = (ImageView) findViewById( R.id.play_bible );
        mRightArrow = (ImageView) findViewById( R.id.right_arrow );
        mListenButton = (RelativeLayout) findViewById( R.id.listen_button );
        mSettingsButton = (TextView) findViewById( R.id.settings_textView );
        mSettingsImage = (ImageView) findViewById( R.id.setting_imageView );

        mDoneButton = (TextView) findViewById( R.id.done );
        mTheme1 = (ImageView) findViewById( R.id.theme_image1 );
        mTheme2 = (ImageView) findViewById( R.id.theme_image2 );
        mTheme3 = (ImageView) findViewById( R.id.theme_image3 );
        mTheme4 = (ImageView) findViewById( R.id.theme_image4 );
        mFontFamily1 = (TextView) findViewById( R.id.font_textView1 );
        mFontFamily2 = (TextView) findViewById( R.id.font_textView2 );
        mFontFamily3 = (TextView) findViewById( R.id.font_textView3 );
        mTextSmall = (TextView) findViewById( R.id.size_small );
        mTextMedium = (TextView) findViewById( R.id.size_medium );
        mTextLarge = (TextView) findViewById( R.id.size_large );
        mTopGradient = (TextView) findViewById( R.id.top_gradient );
        mBottomGradient = (TextView) findViewById( R.id.bottom_gradiant );
        mSlideRight = (RelativeLayout) findViewById( R.id.slide_right );

        mBibleWebView = (SFBibleWebView) findViewById( R.id.bible_webview );
        mBibleWebView.setWebViewClient( new WebViewClient()
        {
            public void onPageFinished( WebView view, String url )
            {
                mTopGradient.setVisibility( View.VISIBLE );
                mBottomGradient.setVisibility( View.VISIBLE );
            }
        } );
    }

    /**
     *  opens the Bible menu
     */
    public static void showMenus()
    {
        SFApplication application = SFApplication.getInstance();
        if( !application.isBibleMenuOpen )
        {
            if(application.currentViewTag.equals( "bible" ))
            {
                SFBibleActivity bibleActivity = (SFBibleActivity) application.getCurrentActivity();
                LinearLayout footer = (LinearLayout) bibleActivity.findViewById( R.id.footer );
                RelativeLayout arrows = (RelativeLayout) bibleActivity.findViewById( R.id.arrows_container );
                Animation animationBottom = AnimationUtils.loadAnimation( application, R.anim.sf_menu_expand_up );
                footer.startAnimation( animationBottom );
                arrows.startAnimation( animationBottom );
                footer.setVisibility( View.VISIBLE );
                arrows.setVisibility( View.VISIBLE );
                application.isBibleMenuOpen = true;
            }
        }

        mFooterHandler.removeCallbacks( mHideFooter );

        if(!application.isAtBottomOfChapter)
        {
            mFooterHandler.postDelayed( mHideFooter, 5000 );
        }
    }

    /**
     *  reset hideFooter delay
     */
    public static void resetFooterHandler()
    {
        mFooterHandler.removeCallbacks( mHideFooter );
        mFooterHandler.postDelayed( mHideFooter, 5000 );
    }

    /**
     *  Sets Bible position to were the user was last
     */
    private void getBiblePosition()
    {
        String biblePositionPath = mAppData.getBiblePosition();
        if(biblePositionPath.equals( "" ))
        {
            mApplication.bibleIndex = 0;
            mApplication.bookIndex = 0;
            mApplication.chapterIndex = 0;
        }
        else
        {
            try
            {
                String delims = "[/.]";
                String[] tokens = biblePositionPath.split( delims );

                mApplication.bibleIndex = 0;
                for (int i = 0; i < mApplication.bibleModels.length; i++)
                {
                    if (mApplication.bibleModels[i].mAbreviation.equals( tokens[0] ))
                    {
                        mApplication.bibleIndex = i;
                    }
                }
                mApplication.bookIndex = mAppData.getBookIndex( tokens[1] );

                mApplication.chapterIndex = AiSTr.denullifyInt( tokens[2] ) - 1;
            }
            catch (Exception missingBible)
            {
                mApplication.bibleIndex = 0;
                mApplication.bookIndex = 0;
                mApplication.chapterIndex = 0;
            }
        }
    }

    /**
     *  Closes the Bible menu
     */
    public static void hideMenus()
    {
        SFApplication application = SFApplication.getInstance();
        if( application.isBibleMenuOpen )
        {
            if(application.currentViewTag.equals( "bible" ))
            {
                SFBibleActivity bibleActivity = (SFBibleActivity) application.getCurrentActivity();
                LinearLayout footer = (LinearLayout) bibleActivity.findViewById( R.id.footer );
                RelativeLayout arrows = (RelativeLayout) bibleActivity.findViewById( R.id.arrows_container );
                Animation animationBottom = AnimationUtils.loadAnimation( application, R.anim.sf_menu_collapse_down );
                footer.startAnimation( animationBottom );
                arrows.startAnimation( animationBottom );
                footer.setVisibility( View.GONE );
                arrows.setVisibility( View.GONE );
                application.isBibleMenuOpen = false;
            }
        }
    }

    /**
     *  Opens the Setting Menu
     */
    private void openSettings()
    {
        Animation animation = AnimationUtils.loadAnimation( mApplication, R.anim.sf_menu_expand_up );
        RelativeLayout settings = (RelativeLayout) findViewById( R.id.settings );
        settings.startAnimation( animation );
        settings.setVisibility( View.VISIBLE );
        mIsSettingsOpen = true;
    }

    /**
     *  Closes the Settings Menu
     */
    private void closeSettings()
    {
        Animation animation = AnimationUtils.loadAnimation( mApplication,R.anim.sf_menu_collapse_down );
        RelativeLayout settings = (RelativeLayout) findViewById( R.id.settings );
        settings.startAnimation( animation );
        settings.setVisibility( View.GONE );
        mIsSettingsOpen = false;
    }

    /**
     * toggles the book select menu show/hide
     */
    public void toggleBookSelect()
    {
        if(mApplication.isBookSelectOpen)
        {
            mBooksList.setVisibility( View.GONE );
            mApplication.isBookSelectOpen = false;
        }
        else
        {
            mBooksList.setVisibility( View.VISIBLE );
            mApplication.isBookSelectOpen = true;
        }
    }

    /**
     * Sets up the Listener for the bottom buttons
     * @param action
     * @return
     */
    private View.OnClickListener arrowListener( final String action )
    {

        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {
                        if(!mArrowButtonLocked)
                        {
                            mArrowButtonLocked = true;
                            if (action.equals( "leftarrow" ))
                            {
                                previousChapter();
                                resetFooterHandler();
                            }
                            if (action.equals( "rightarrow" ))
                            {
                                nextChapter();
                                resetFooterHandler();
                            }
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    mArrowButtonLocked = false;
                                }

                            }, 500);
                        }
                    }
                };
    }

    /**
     * Sets up the Listener for the footer menu buttons
     * @param action
     * @return
     */
    private View.OnClickListener footerButtonListener( final String action )
    {
        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {
                        if( action.equals( "settings" ))
                        {
                            openSettings();
                        }
                    }
                };
    }

    /**
     * Sets up Listeners for the Settings menu buttons
     * @param action
     * @return
     */
    private View.OnClickListener settingsListener( final String action )
    {
        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {
                        if( action.equals( "done" ))
                        {
                            SFBibleActivity.showMenus();
                            closeSettings();
                            mAppData.setBibleFont( mFontFamily );
                            mAppData.setBibleTheme( mTheme );
                        }
                        else
                        {
                            mCurrentThemeUnderline.setVisibility( View.INVISIBLE );
                            mCurrentFontUnderline.setVisibility( View.INVISIBLE );
                            mCurrentTextSizeUnderline.setVisibility( View.INVISIBLE );
                            if (action.equals( "theme1" ))
                            {
                                mTopGradient.setVisibility( View.INVISIBLE );
                                mBottomGradient.setVisibility( View.INVISIBLE );
                                mTheme = 1;
                                mThemeCSS = "<LINK href=\"css/theme1.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mTopGradient.setBackgroundResource( R.drawable.sf_border_fade_top_theme1 );
                                mBottomGradient.setBackgroundResource( R.drawable.sf_border_fade_bottom_theme1 );
                                mCurrentThemeUnderline = (TextView) findViewById( R.id.theme_underline1 );
                                mSlideRight.setBackgroundColor( mApplication.getResources().getColor( R.color.sf_theme1 ) );
                            }
                            else if (action.equals( "theme2" ))
                            {
                                mTopGradient.setVisibility( View.INVISIBLE );
                                mBottomGradient.setVisibility( View.INVISIBLE );
                                mTheme = 2;
                                mThemeCSS = "<LINK href=\"css/theme2.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mTopGradient.setBackgroundResource( R.drawable.sf_border_fade_top_theme2 );
                                mBottomGradient.setBackgroundResource( R.drawable.sf_border_fade_bottom_theme2 );
                                mCurrentThemeUnderline = (TextView) findViewById( R.id.theme_underline2 );
                                mSlideRight.setBackgroundColor( mApplication.getResources().getColor( R.color.sf_theme2 ) );
                            }
                            else if (action.equals( "theme3" ))
                            {
                                mTopGradient.setVisibility( View.INVISIBLE );
                                mBottomGradient.setVisibility( View.INVISIBLE );
                                mTheme = 3;
                                mThemeCSS = "<LINK href=\"css/theme3.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mTopGradient.setBackgroundResource( R.drawable.sf_border_fade_top_theme3 );
                                mBottomGradient.setBackgroundResource( R.drawable.sf_border_fade_bottom_theme3 );
                                mCurrentThemeUnderline = (TextView) findViewById( R.id.theme_underline3 );
                                mSlideRight.setBackgroundColor( mApplication.getResources().getColor( R.color.sf_theme3 ) );
                            }
                            else if (action.equals( "theme4" ))
                            {
                                mTopGradient.setVisibility( View.INVISIBLE );
                                mBottomGradient.setVisibility( View.INVISIBLE );
                                mTheme = 4;
                                mThemeCSS = "<LINK href=\"css/theme4.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mTopGradient.setBackgroundResource( R.drawable.sf_border_fade_top_theme4 );
                                mBottomGradient.setBackgroundResource( R.drawable.sf_border_fade_bottom_theme4 );
                                mCurrentThemeUnderline = (TextView) findViewById( R.id.theme_underline4 );
                                mSlideRight.setBackgroundColor( mApplication.getResources().getColor( R.color.sf_theme4 ) );
                            }

                            if (action.equals( "font1" ))
                            {
                                mFontFamily = 1;
                                mFontFamilyCSS = "<LINK href=\"css/font1.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mCurrentFontUnderline = (TextView) findViewById( R.id.fonts_underline1 );
                            }
                            else if (action.equals( "font2" ))
                            {
                                mFontFamily = 2;
                                mFontFamilyCSS = "<LINK href=\"css/font2.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mCurrentFontUnderline = (TextView) findViewById( R.id.fonts_underline2 );
                            }
                            else if (action.equals( "font3" ))
                            {
                                mFontFamily = 3;
                                mFontFamilyCSS = "<LINK href=\"css/font3.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mCurrentFontUnderline = (TextView) findViewById( R.id.fonts_underline3 );
                            }

                            if (action.equals( "size_small" ))
                            {
                                mApplication.setFontSize( "size_small" );
                                mTextSizeCSS = "<LINK href=\"css/size_small.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline1 );
                            }
                            else if (action.equals( "size_medium" ))
                            {
                                mApplication.setFontSize( "size_medium" );
                                mTextSizeCSS = "<LINK href=\"css/size_medium.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline2 );
                            }
                            else if (action.equals( "size_large" ))
                            {
                                mApplication.setFontSize( "size_large" );
                                mTextSizeCSS = "<LINK href=\"css/size_large.css\" type=\"text/css\" rel=\"stylesheet\">";
                                mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline3 );
                            }

                            //mApplication.bibleScrollY = mBibleWebView.getScrollY();
                            mCurrentThemeUnderline.setVisibility( View.VISIBLE );
                            mCurrentFontUnderline.setVisibility( View.VISIBLE );
                            mCurrentTextSizeUnderline.setVisibility( View.VISIBLE );
                            loadWebView();
                        }
                    }
                };
    }

    /**
     * Sets the style setting options
     */
    private void setupStyles()
    {
        if(mTheme == 1)
        {
            mThemeCSS = "<LINK href=\"css/theme1.css\" type=\"text/css\" rel=\"stylesheet\">";
            mTopGradient.setBackgroundResource( R.drawable.sf_border_fade_top_theme1 );
            mBottomGradient.setBackgroundResource( R.drawable.sf_border_fade_bottom_theme1 );
            mCurrentThemeUnderline = (TextView) findViewById( R.id.theme_underline1 );
            mCurrentThemeUnderline.setVisibility( View.VISIBLE );
            mSlideRight.setBackgroundColor( mApplication.getResources().getColor( R.color.sf_theme1 ) );

        }
        else if(mTheme == 2)
        {
            mThemeCSS = "<LINK href=\"css/theme2.css\" type=\"text/css\" rel=\"stylesheet\">";
            mTopGradient.setBackgroundResource( R.drawable.sf_border_fade_top_theme2 );
            mBottomGradient.setBackgroundResource( R.drawable.sf_border_fade_bottom_theme2 );
            mCurrentThemeUnderline = (TextView) findViewById( R.id.theme_underline2 );
            mCurrentThemeUnderline.setVisibility( View.VISIBLE );
            mSlideRight.setBackgroundColor( mApplication.getResources().getColor( R.color.sf_theme2 ) );

        }
        else if(mTheme == 3)
        {
            mThemeCSS = "<LINK href=\"css/theme3.css\" type=\"text/css\" rel=\"stylesheet\">";
            mTopGradient.setBackgroundResource( R.drawable.sf_border_fade_top_theme3 );
            mBottomGradient.setBackgroundResource( R.drawable.sf_border_fade_bottom_theme3 );
            mCurrentThemeUnderline = (TextView) findViewById( R.id.theme_underline3 );
            mCurrentThemeUnderline.setVisibility( View.VISIBLE );
            mSlideRight.setBackgroundColor( mApplication.getResources().getColor( R.color.sf_theme3 ) );
        }
        else if(mTheme == 4)
        {
            mThemeCSS = "<LINK href=\"css/theme4.css\" type=\"text/css\" rel=\"stylesheet\">";
            mTopGradient.setBackgroundResource( R.drawable.sf_border_fade_top_theme4 );
            mBottomGradient.setBackgroundResource( R.drawable.sf_border_fade_bottom_theme4 );
            mCurrentThemeUnderline = (TextView) findViewById( R.id.theme_underline4 );
            mCurrentThemeUnderline.setVisibility( View.VISIBLE );
            mSlideRight.setBackgroundColor( mApplication.getResources().getColor( R.color.sf_theme4 ) );
        }

        if(mFontFamily == 1 )
        {
            mFontFamilyCSS= "<LINK href=\"css/font1.css\" type=\"text/css\" rel=\"stylesheet\">";
            mCurrentFontUnderline = (TextView) findViewById( R.id.fonts_underline1 );
            mCurrentFontUnderline.setVisibility( View.VISIBLE );
        }
        else if(mFontFamily == 2 )
        {
            mFontFamilyCSS = "<LINK href=\"css/font2.css\" type=\"text/css\" rel=\"stylesheet\">";
            mCurrentFontUnderline = (TextView) findViewById( R.id.fonts_underline2 );
            mCurrentFontUnderline.setVisibility( View.VISIBLE );
        }
        else if(mFontFamily == 3)
        {
            mFontFamilyCSS = "<LINK href=\"css/font3.css\" type=\"text/css\" rel=\"stylesheet\">";
            mCurrentFontUnderline = (TextView) findViewById( R.id.fonts_underline3 );
            mCurrentFontUnderline.setVisibility( View.VISIBLE );
        }

        if(mApplication.getFontSize().equals( "size_small" ))
        {
            mTextSizeCSS = "<LINK href=\"css/size_small.css\" type=\"text/css\" rel=\"stylesheet\">";
            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline1 );
            mCurrentTextSizeUnderline.setVisibility( View.VISIBLE );
        }
        else if(mApplication.getFontSize().equals( "size_medium" ))
        {
            mTextSizeCSS = "<LINK href=\"css/size_medium.css\" type=\"text/css\" rel=\"stylesheet\">";
            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline2 );
            mCurrentTextSizeUnderline.setVisibility( View.VISIBLE );
        }
        else if(mApplication.getFontSize().equals( "size_large" ))
        {
            mTextSizeCSS = "<LINK href=\"css/size_large.css\" type=\"text/css\" rel=\"stylesheet\">";
            mCurrentTextSizeUnderline = (TextView) findViewById( R.id.size_underline3 );
            mCurrentTextSizeUnderline.setVisibility( View.VISIBLE );
        }
    }

    /**
     *  Sets visibility of the listen button based on if the bible version has audio
     */
    public void setListenButton()
    {
        //ESV was the only one that did and it is no longer there.
        mListenButton.setVisibility( View.GONE );
        /*if(mApplication.bibleModels[mApplication.bibleIndex].mHasAudio)
        {
            mListenButton.setVisibility( View.VISIBLE );
        }
        else
        {
            mListenButton.setVisibility( View.GONE );
        }*/
    }

    /**
     * Sets the state of the State of the play audio button
     */
    private void setAudioControls()
    {
        if(!mApplication.isBibleMenuOpen)
        {
            showMenus();
        }
        //No audio Bible
        mApplication.isListeningBible = false;
        mPlayButton.setVisibility( View.GONE );
    }

    /**
     *  refreshes the view
     */
    public void refreshView()
    {
        loadWebView();
        setListenButton();
    }

    public void loadWebView()
    {
        loadWebView( 0 );
    }

    /**
     *  Loads the Bible text into a webview
     */
    public void loadWebView(int count)
    {
        mApplication.isAtBottomOfChapter = false;
        try{
            //SFBibleModel bibleModel = mApplication.getSfCurrentBible();
            File file = new File( mApplication.getFilesDir() + "/" + mApplication.getString( R.string.sf_bibles_path ) +
                    mApplication.bibleModels[mApplication.bibleIndex].mAbreviation + "/" + mApplication.getCurrentBook().mAbbreviation + "/" +
                    Integer.toString( mApplication.chapterIndex+1 ) + ".html" );
            if(!file.exists())
            {
                SFBibleDownloader downloader = new SFBibleDownloader();
                downloader.downloadChapter( mApplication.getString( R.string.sf_appbible_url ) +
                        SFConstants.UAID_KEY + "/chapter/" + mApplication.getSfCurrentBible().mAbreviation +
                        "/" + mApplication.getCurrentBook().mAbbreviation + (mApplication.chapterIndex+1) ,mApplication.bookIndex,
                        mApplication.chapterIndex+1);
                prepNextWebviews();
                prepPrevWebviews();
            }

            FileInputStream fis = new FileInputStream( file );
            int streamSize = fis.available();
            byte[] buffer = new byte[streamSize];
            fis.read(buffer);
            fis.close();
            String html = new String(buffer);
            String tail = "<div><p class='copyright'> " + mApplication.getSfCurrentBible().mCopyright + "</p></div>";
            String device = "";
            if(SFConfig.isTablet())
            {
                device = "<LINK href=\"css/tablet.css\" type=\"text/css\" rel=\"stylesheet\">";
            }
            else
            {
                device = "<LINK href=\"css/phone.css\" type=\"text/css\" rel=\"stylesheet\">";
            }
            html = device + mThemeCSS + mFontFamilyCSS + mTextSizeCSS + html + tail;

            mBibleWebView.loadDataWithBaseURL( "file:///android_asset/", html, "text/html", "utf-8", null );
            setBookChapterText();
            mAppData.setBiblePosition();

            //get changes for Analytic logging
            if( mPreviousVersion == null )
            {
                mPreviousVersion = mApplication.getSfCurrentBible().mAbreviation;
                mApplication.logEvent( "bible_nav","version",mPreviousVersion );

                mPreviousBook = mApplication.getCurrentBook().mAbbreviation;
                mApplication.logEvent( "bible_nav","book", mPreviousBook );
            }
            else
            {
                if(!mPreviousVersion.equals( mApplication.getSfCurrentBible().mAbreviation ))
                {
                    mPreviousVersion = mApplication.getSfCurrentBible().mAbreviation;
                    mApplication.logEvent( "bible_nav","version",mPreviousVersion );
                }
                if(!mPreviousBook.equals( mApplication.getCurrentBook().mAbbreviation ))
                {
                    mPreviousBook = mApplication.getCurrentBook().mAbbreviation;
                    mApplication.logEvent( "bible_nav","book", mPreviousBook );
                }
            }
            mApplication.logEvent( "bible_nav","chapter",Integer.toString( mApplication.chapterIndex+1 ) );

        }
        catch (Exception e)
        {
            e.printStackTrace();
            //If there is network error or something, try a bit later:
            if(count<5)
            {
                count++;
                final int mycount = count;
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadWebView( mycount);
                    }
                }, count * 1000);

            }
        }
        if(mApplication.isBibleMenuOpen)
        {
            resetFooterHandler();
        }
        else
        {
            showMenus();
            mApplication.isBibleMenuOpen = true;
        }
        SFUtil.logSiteEvent( "Loaded Chapter");

        //mAudioUpdateHandler.removeCallbacks( mAudioDelay );
        //mAudioUpdateHandler.postDelayed( mAudioDelay, 500 );
    }

    /**
     * prepares the next chapter Webview
     */
    public void prepNextWebviews()
    {
        if(mApplication.bookIndex+1==mApplication.getBooks().length &&
                mApplication.chapterIndex+1==mApplication.getCurrentBook().mNumChapters)
        {
            return;
        }
        Thread t = new Thread(
                new Runnable()
                {
                    public void run()
                    {
                        int nextChapter;
                        SFBookModel book;
                        if(mApplication.chapterIndex+1!=mApplication.getCurrentBook().mNumChapters)
                        {
                            nextChapter = mApplication.chapterIndex + 2;
                            book = mApplication.getCurrentBook();
                        }
                        else
                        {
                            nextChapter =  1;
                            book = mApplication.getBook( mApplication.bookIndex+1);
                        }
                        try{
                            //int nextChapter = mApplication.chapterIndex + 2;
                            File file = new File( mApplication.getFilesDir() + "/" + mApplication.getString( R.string.sf_bibles_path ) +
                                    mApplication.getSfCurrentBible().mAbreviation + "/" + book.mAbbreviation +
                                    "/" + Integer.toString( nextChapter ) + ".html" );
                            if(!file.exists())
                            {
                                SFBibleDownloader downloader = new SFBibleDownloader();
                                downloader.downloadChapter( mApplication.getString( R.string.sf_appbible_url ) +
                                        SFConstants.UAID_KEY + "/chapter/" + mApplication.getSfCurrentBible().mAbreviation +
                                        "/" + book.mAbbreviation + nextChapter,book.mPriority-1,nextChapter );
                            }
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                }

        );
        t.start();
    }

    /**
     * prepares the previous chapters Webview
     */
    public void prepPrevWebviews()
    {
        if(mApplication.bookIndex==0 && mApplication.chapterIndex==0)
        {
            return;
        }
        Thread t = new Thread(
                new Runnable()
                {
                    public void run()
                    {
                        int prevChapter;
                        SFBookModel book;
                        if(mApplication.chapterIndex!=0)
                        {
                            book = mApplication.getCurrentBook();
                            prevChapter = mApplication.chapterIndex;
                        }
                        else
                        {
                            book = mApplication.getBook( mApplication.bookIndex-1);
                            prevChapter = book.mNumChapters ;
                        }
                        try{
                            int previousChapter = mApplication.chapterIndex;
                            File file = new File( mApplication.getFilesDir() + "/" + mApplication.getString( R.string.sf_bibles_path ) +
                                    mApplication.getSfCurrentBible().mAbreviation + "/" + book.mAbbreviation +
                                    "/" + Integer.toString( prevChapter ) + ".html" );
                            if(!file.exists())
                            {
                                SFBibleDownloader downloader = new SFBibleDownloader();
                                downloader.downloadChapter( mApplication.getString( R.string.sf_appbible_url ) +
                                        SFConstants.UAID_KEY + "/chapter/" + mApplication.getSfCurrentBible().mAbreviation +
                                        "/" + book.mAbbreviation + prevChapter,book.mPriority-1,prevChapter );
                            }
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }

                    }
                }

        );
        t.start();
    }

    /**
     * loads the next chapter
     */
    public void nextChapter()
    {
        if(mApplication.bookIndex+1==mApplication.getBooks().length &&
                mApplication.chapterIndex+1==mApplication.getCurrentBook().mNumChapters)
        {
            return;
        }
        if(mApplication.getCurrentBook().mNumChapters>mApplication.chapterIndex+1)
        {
            mApplication.chapterIndex++;
        }
        else
        {
            mApplication.bookIndex++;
            mApplication.chapterIndex = 0;
        }
        Animation animation1 = AnimationUtils.loadAnimation( mApplication, R.anim.sf_fade_out );
        animation1.setAnimationListener( new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart( Animation animation )
            {
            }

            @Override
            public void onAnimationEnd( Animation animation )
            {
                //setBookChapterText();
                loadWebView();
                Animation animation2 = AnimationUtils.loadAnimation( mApplication, R.anim.sf_activity_slidein_right );
                mBibleWebView.startAnimation( animation2 );
                prepNextWebviews();
            }

            @Override
            public void onAnimationRepeat( Animation animation ) {}
        } );
        mBibleWebView.startAnimation( animation1 );
        if(mApplication.getSfMediaPlayer().isPlaying() || mApplication.isBibleAudioPaused)
        {
            mApplication.releaseMediaPlayer();
            mPlayButton.setImageResource( R.drawable.audio_play );
            mPlayButton.setPadding( mApplication.getDP( 20 ), mApplication.getDP( 18 ), mApplication.getDP( 16 ), mApplication.getDP( 18 ) );
        }

    }

    /**
     * loads the previous chapter
     */
    public void previousChapter()
    {
        if(mApplication.bookIndex==0 && mApplication.chapterIndex==0)
        {
            return;
        }
        if(mApplication.chapterIndex!=0)
        {
            mApplication.chapterIndex--;
        }
        else
        {
            mApplication.bookIndex--;
            mApplication.chapterIndex = mApplication.getCurrentBook().mNumChapters-1;
        }
        Animation animation1 = AnimationUtils.loadAnimation( mApplication, R.anim.sf_fade_out );
        animation1.setAnimationListener( new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart( Animation animation )
            {
            }

            @Override
            public void onAnimationEnd( Animation animation )
            {
                //setBookChapterText();
                loadWebView();
                Animation animation2 = AnimationUtils.loadAnimation( mApplication, R.anim.sf_activity_slidein_left );
                mBibleWebView.startAnimation( animation2 );
                prepPrevWebviews();
            }

            @Override
            public void onAnimationRepeat( Animation animation )
            {
            }
        } );
        mBibleWebView.startAnimation( animation1 );
        if(mApplication.getSfMediaPlayer().isPlaying() || mApplication.isBibleAudioPaused)
        {
            mApplication.releaseMediaPlayer();
            mPlayButton.setImageResource( R.drawable.audio_play );
            mPlayButton.setPadding( mApplication.getDP( 20 ), mApplication.getDP( 18 ), mApplication.getDP( 16 ), mApplication.getDP( 18 ) );
        }

    }

    /**
     * toggles the bible version controls
     */
    public void toggleBibleVersion()
    {
        if(mIsBibleVersionsOpen)
        {
            mVersionList.setVisibility( View.GONE );
            mIsBibleVersionsOpen = false;
        }
        else
        {
            mVersionList.setVisibility( View.VISIBLE );
            mIsBibleVersionsOpen = true;
        }
    }

    /**
     * unzips the bible after downloading
     */
    public static void unzipBible()
    {
        Thread t = new Thread(
                new Runnable()
                {
                    public void run()
                    {
                        try
                        {
                            SFApplication application = SFApplication.getInstance();
                            File file = null;
                            //unbz2
                            try
                            {
                                String source = application.getFilesDir()+"/"+application.getString( R.string.sf_bibles_path );
                                file = new File( source+application.getSfCurrentBible().mAbreviation+".tar.bz2" );
                                //AssetFileDescriptor fileDescriptor = application.getFilesDir().openFd(application.getString( R.string.sf_bibles_path ) + application.version+".tar.bz2" );
                                FileInputStream in = new FileInputStream( file ); //application.openFileInput( application.getString( R.string.sf_bibles_path ) + application.version+".tar.bz2" ); //fileDescriptor.createInputStream();
                                FileOutputStream out = new FileOutputStream(application.getFilesDir()+"/" +application.getResources().getString( R.string.sf_bibles_path )+
                                        application.getSfCurrentBible().mAbreviation+".tar");
                                BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
                                final byte[] buffer = new byte[2048];
                                int n = 0;

                                while (-1 != (n = bzIn.read(buffer))) {
                                    out.write(buffer, 0, n);
                                }
                                out.close();
                                bzIn.close();
                            } catch (IOException e)
                            {
                                e.printStackTrace();
                            }

                            String tarFile = application.getFilesDir()+"/"+application.getString( R.string.sf_bibles_path )+application.getSfCurrentBible().mAbreviation+".tar";
                            String destFolder = application.getFilesDir()+"/"+application.getString( R.string.sf_bibles_path );

                            //delete data in bible dir
                            File bibleDir = new File(destFolder+application.getSfCurrentBible().mAbreviation);
                            deleteBibleDir( bibleDir );

                            //untar
                            try
                            {
                                // Create a TarInputStream
                                TarInputStream tis = new TarInputStream(new BufferedInputStream(new FileInputStream(tarFile)));
                                TarEntry entry;

                                while((entry = tis.getNextEntry()) != null) {
                                    int count;
                                    byte data[] = new byte[2048];
                                    if (entry.isDirectory()) {
                                        new File(destFolder + "/" + entry.getName()).mkdirs();
                                        continue;
                                    } else {
                                        int di = entry.getName().lastIndexOf('/');
                                        if (di != -1) {
                                            new File(destFolder + "/" + entry.getName().substring(0, di)).mkdirs();
                                        }
                                    }
                                    FileOutputStream fos = new FileOutputStream(destFolder + "/" + entry.getName());
                                    BufferedOutputStream dest = new BufferedOutputStream(fos);

                                    while((count = tis.read(data)) != -1) {
                                        dest.write(data, 0, count);
                                    }

                                    dest.flush();
                                    dest.close();
                                }
                                tis.close();
                            } catch (IOException e)
                            {
                                e.printStackTrace();
                            }
                            if(file != null)
                            {
                                if(file.exists())
                                {
                                    file.delete();
                                }
                            }
                            file = new File(tarFile);
                            if(file.exists())
                            {
                                file.delete();
                            }
                        } catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        SFApplication.getInstance().isDownloadingBible = false;
                    }
                }

        );
        t.start();


    }

    public void deleteBibleOverlay( final File file, final int pos )
    {
        final AlertDialog.Builder builder = new AlertDialog.Builder( mApplication.getCurrentActivity() );
        final SFAppData appData = new SFAppData();

        builder.setMessage( mApplication.getString( R.string.alert_confirm_delete_bible_version ) );
        builder.setNegativeButton( mApplication.getString( R.string.alert_no ), null );
        builder.setPositiveButton( mApplication.getString( R.string.alert_yes ), new DialogInterface.OnClickListener()
        {
            public void onClick( DialogInterface dialog, int id )
            {
                SFBibleActivity.deleteBibleDir( file );
                toggleIsDownloaded( pos );
                appData.setDataForVersionDelete(mApplication.bibleModels[pos].mAbreviation);
                mBiblesAdapter.notifyDataSetChanged();

            }
        });
        builder.show();
    }

    public static void deleteBibleDir( File dir )
    {

        if (dir.isDirectory())
        {
            for (File child: dir.listFiles())
            {
                deleteBibleDir( child );
            }
        }
        //Log.d( "mTag", "deleting " + dir );
        dir.delete();
    }

    public void toggleIsDownloaded(int position)
    {
        SFBibleModel bibleModel = mApplication.bibleModels[position];
        if( bibleModel.mIsDownloaded )
        {
            bibleModel.mIsDownloaded = false;
        }
        else
        {
            bibleModel.mIsDownloaded = true;
        }

    }



    @Override
    public void onBackPressed()
    {
        if(mApplication.isDoingFullSync)
        {
            mApplication.makeToast( mApplication.getString( R.string.alert_wait_for_download ) );
            return;
        }
        boolean finish = true;
        if (mApplication.isNavOpen)
        {
            SFSharedUIMethods.closeMenu();
            finish = false;
        }

        if(mIsSettingsOpen)
        {
            closeSettings();
            finish = false;
        }

        if(mIsBibleVersionsOpen)
        {
            toggleBibleVersion();
            finish = false;
        }

        if(mApplication.isBookSelectOpen)
        {
            toggleBookSelect();
            finish = false;
        }

        if(finish)
        {
            this.finish();
            overridePendingTransition( R.anim.sf_activity_slidein_left, R.anim.sf_activity_slideout_right );
        }
    }

    @Override
    public void onPause()
    {

        if (mApplication.isNavOpen)
        {
            SFSharedUIMethods.closeMenu();
        }

        if(mIsSettingsOpen)
        {
            closeSettings();
        }

        if(mIsBibleVersionsOpen)
        {
            toggleBibleVersion();
        }

        if(mApplication.isBookSelectOpen)
        {
            toggleBookSelect();
        }
        super.onPause();
    }

    /**
     * OnClickListener for the navigation bar
     * @param action
     * @return
     */
    private View.OnClickListener navItemListener( final String action )
    {
        return
                new View.OnClickListener()
                {
                    public void onClick( View v )
                    {
                        if( action.equals( "opennav" ) )
                        {
                            if( !mApplication.isNavOpen )
                            {
                                SFSharedUIMethods.openMenu();
                            }
                            else
                            {
                                SFSharedUIMethods.closeMenu();
                            }

                        } // if( action.equals( "opennav" ) )
                        if( action.equals( "chapternav" ))
                        {
                            if( mApplication.isNavOpen )
                            {
                                SFSharedUIMethods.closeMenu();
                            }

                            toggleBookSelect();
                        }
                        if( action.equals( "listennav" ) )
                        {

                            if( mApplication.isNavOpen )
                            {
                                SFSharedUIMethods.closeMenu();
                            }
                            toggleBibleVersion();
                        } // if( action.equals( "opennav" ) )
                    }
                };
    }

    /**
     * Load the UI elements
     */
    private void loadInterface()
    {
        SFConfig config = new SFConfig();
        // Get the basic layout components going
        LinearLayout titleBarLayout = (LinearLayout) findViewById( R.id.navMenuContainer );
        titleBarLayout.setBackgroundColor( Color.parseColor( "#" + config.mNavColor ) );

        // Set the title bar properties
        TextView titleBarView = (TextView) findViewById( R.id.navMenuTitle );
        titleBarView.setText( (mApplication.getCurrentBook().mFullname+" "+(mApplication.chapterIndex+1)) );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        {
            titleBarView.setBackground( this.mApplication.getResources().getDrawable( R.drawable.borderbox_rounded_holo ) );
        }
        titleBarView.setOnClickListener( this.navItemListener( "chapternav" ) );

        ImageButton openNav = (ImageButton) findViewById( R.id.openMenuImageButton );
        openNav.setOnClickListener( this.navItemListener( "opennav" ) );
        openNav.setBackgroundResource( R.drawable.openmenu );

        ImageButton listenNav = (ImageButton) findViewById( R.id.openListenImageButton );
        listenNav.setVisibility( View.GONE );

        TextView bibleVersion = (TextView) findViewById( R.id.bible_version );
        bibleVersion.setText( mApplication.getSfCurrentBible().mAbreviation.toUpperCase() );
        bibleVersion.setVisibility( View.VISIBLE );
        bibleVersion.setOnClickListener( this.navItemListener( "listennav" ) );

        // create the main navigation menu items
        this.mMainNavList = (ListView) findViewById( R.id.mainNavListView );
        SFNavMenuAdapter navMenuAdapter = SFApplication.getInstance().getSfNavMenuAdapter();
        this.mMainNavList.setOnItemClickListener( navMenuAdapter.handleTap( this ) );
        this.mMainNavList.setAdapter( mApplication.getSfNavMenuAdapter() );

        mRefreshButton = (ImageView) findViewById( R.id.refreshArrows );
        int iconColor = Color.parseColor( "#" + this.mConfig.customFontColorForNavColor() );
        mRefreshButton.setColorFilter( iconColor, PorterDuff.Mode.MULTIPLY  );
        this.mRefreshButton.setOnTouchListener(new View.OnTouchListener() {
            long then = 0;
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if(event.getAction() == MotionEvent.ACTION_DOWN)
                {
                    this.then = System.currentTimeMillis();
                    return true;
                }
                else if(event.getAction() == MotionEvent.ACTION_UP)
                {
                    if((System.currentTimeMillis() - this.then) > 5000)
                    {
                        SFSharedUIMethods.fullrefresh();
                    }
                    else
                    {
                        SFSharedUIMethods.refresh();
                    }
                }
                return false;
            }
        });

        //Setup the settings button on menu footer
        mOpenSettingsButton = (ImageView) findViewById( R.id.openSettingsButton );
        mOpenSettingsButton.setColorFilter( iconColor, PorterDuff.Mode.MULTIPLY );
        mOpenSettingsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick( View v )
            {
                SFSharedUIMethods.closeMenu();
                Intent intent = new Intent( mApplication, SFSettingsActivity.class );
                startActivity( intent );
                overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
            }
        });

        if(mApplication.isSyncing)
        {
            SFSharedUIMethods.animateRefresh();
        }
    }

    /**
     * Sets the Version text
     */
    public void setVersionText()
    {
        TextView bibleVersion = (TextView) findViewById( R.id.bible_version );
        bibleVersion.setText( mApplication.getSfCurrentBible().mAbreviation.toUpperCase() );
    }

    /**
     * sets the book chapter text
     */
    public void setBookChapterText()
    {
        TextView bibleLoc = (TextView) findViewById( R.id.navMenuTitle );
        //int chapter = mApplication.getSfCurrentBible().getCurrentBook().getCurrentChapter() + 1;
        bibleLoc.setText( mApplication.getCurrentBook().mFullname + " "
                + (mApplication.chapterIndex + 1 ) );
    }

    /**
     * sets up a listener for gestures
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent( MotionEvent event )
    {
        this.mDetector.onTouchEvent( event );
        return super.onTouchEvent( event );
    }

    @Override
    public void onLowMemory()
    {
        super.onLowMemory();
        this.clearCache();
    }
    @Override
    public void onTrimMemory(int level)
    {
        super.onTrimMemory( level );
        this.clearCache();
    }

    public void clearCache()
    {
    }

    /**
     * capture Touch event and do nothing if doing a full sync
     * @param e
     * @return
     */
    @Override
    public boolean dispatchTouchEvent( MotionEvent e )
    {
        if(mApplication.isDoingFullSync)
        {
            return true;
        }
        else
        {
            super.dispatchTouchEvent( e );
        }
        return false;
    }
}
