package jp.agentec.abook.abv.ui.viewer.activity;
/**
 * ContentViewActivity.java
 * @author jang
 */

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.foxit.sdk.PDFException;

import org.json.adf.JSONArray;
import org.json.adf.JSONException;
import org.json.adf.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import jp.agentec.abook.abv.bl.acms.client.json.DownloadedContentInfoJSON;
import jp.agentec.abook.abv.bl.acms.client.json.MarkingJson;
import jp.agentec.abook.abv.bl.acms.client.json.content.ActionInfoJSON;
import jp.agentec.abook.abv.bl.acms.client.json.content.ContentJSON;
import jp.agentec.abook.abv.bl.acms.client.json.content.LocationJSON;
import jp.agentec.abook.abv.bl.acms.client.json.content.MediaInfoJSON;
import jp.agentec.abook.abv.bl.acms.client.json.content.PDFLinkJSON;
import jp.agentec.abook.abv.bl.acms.client.json.content.PageInfoJSON;
import jp.agentec.abook.abv.bl.acms.client.json.content.PageInfoJSON.PageInfoJSONData;
import jp.agentec.abook.abv.bl.acms.client.json.content.PageObjectJSON;
import jp.agentec.abook.abv.bl.acms.client.json.content.TaskHotspotJSON;
import jp.agentec.abook.abv.bl.acms.type.OperationType;
import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.CommonExecutor;
import jp.agentec.abook.abv.bl.common.Constant;
import jp.agentec.abook.abv.bl.common.constant.ABookKeys;
import jp.agentec.abook.abv.bl.common.exception.ExceptionHandler;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.common.util.ContentFileUtil;
import jp.agentec.abook.abv.bl.common.util.JsonUtil;
import jp.agentec.abook.abv.bl.data.ABVDataCache;
import jp.agentec.abook.abv.bl.data.dao.AbstractDao;
import jp.agentec.abook.abv.bl.data.dao.ContentDao;
import jp.agentec.abook.abv.bl.data.dao.ContentPageDao;
import jp.agentec.abook.abv.bl.download.ContentFileExtractor;
import jp.agentec.abook.abv.bl.dto.ContentBookmarkDto;
import jp.agentec.abook.abv.bl.dto.ContentDto;
import jp.agentec.abook.abv.bl.dto.OperationTaskDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.ContentReadingLogLogic;
import jp.agentec.abook.abv.bl.logic.ContractLogic;
import jp.agentec.abook.abv.bl.logic.EnqueteLogic;
import jp.agentec.abook.abv.bl.websocket.MeetingManager;
import jp.agentec.abook.abv.cl.environment.DeviceInfo;
import jp.agentec.abook.abv.cl.helper.ContentMarkingFileHelper;
import jp.agentec.abook.abv.cl.util.BitmapUtil;
import jp.agentec.abook.abv.cl.util.ContentLogUtil;
import jp.agentec.abook.abv.cl.util.PreferenceUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.launcher.android.R.id;
import jp.agentec.abook.abv.ui.Interface.MovePageInterface;
import jp.agentec.abook.abv.ui.Interface.UnAuthorizedContentListener;
import jp.agentec.abook.abv.ui.common.activity.ABVContentViewActivity;
import jp.agentec.abook.abv.ui.common.appinfo.AppColor;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType.DefPrefKey;
import jp.agentec.abook.abv.ui.common.appinfo.options.Options;
import jp.agentec.abook.abv.ui.common.constant.ErrorCode;
import jp.agentec.abook.abv.ui.common.constant.ErrorMessage;
import jp.agentec.abook.abv.ui.common.constant.IFPDFConst;
import jp.agentec.abook.abv.ui.common.dialog.ABookAlertDialog;
import jp.agentec.abook.abv.ui.common.helper.ABVViewUnbindHelper;
import jp.agentec.abook.abv.ui.common.util.ABVToastUtil;
import jp.agentec.abook.abv.ui.common.util.AlertDialogUtil;
import jp.agentec.abook.abv.ui.common.util.ClipboardUtil;
import jp.agentec.abook.abv.ui.common.util.PatternStringUtil;
import jp.agentec.abook.abv.ui.common.view.ABVEditText;
import jp.agentec.abook.abv.ui.common.view.ABVPopupListWindow;
import jp.agentec.abook.abv.ui.common.vo.Size;
import jp.agentec.abook.abv.ui.home.helper.ABookCheckWebViewHelper;
import jp.agentec.abook.abv.ui.home.helper.ActivityHandlingHelper;
import jp.agentec.abook.abv.ui.viewer.adapter.ContentBookmarkAdapter;
import jp.agentec.abook.abv.ui.viewer.adapter.ContentSearchPageAdapter;
import jp.agentec.abook.abv.ui.viewer.adapter.PDFIndexDialog;
import jp.agentec.abook.abv.ui.viewer.adapter.PDFIndexInfoJSON;
import jp.agentec.abook.abv.ui.viewer.foxitPdf.FoxitPdfCore;
import jp.agentec.abook.abv.ui.viewer.foxitPdf.PDFPageView;
import jp.agentec.abook.abv.ui.viewer.foxitPdf.PdfImageProvider;
import jp.agentec.abook.abv.ui.viewer.foxitPdf.PdfThumbnailProvider;
import jp.agentec.abook.abv.ui.viewer.view.ABVMediaPlayer;
import jp.agentec.abook.abv.ui.viewer.view.Action3DImageView;
import jp.agentec.abook.abv.ui.viewer.view.ActionButton;
import jp.agentec.abook.abv.ui.viewer.view.ActionImageView;
import jp.agentec.abook.abv.ui.viewer.view.ActionOperationTaskCode;
import jp.agentec.abook.abv.ui.viewer.view.ActionOperationTaskPin;
import jp.agentec.abook.abv.ui.viewer.view.EnqueteLayout;
import jp.agentec.abook.abv.ui.viewer.view.EnqueteWebView;
import jp.agentec.abook.abv.ui.viewer.view.FullVideoView;
import jp.agentec.abook.abv.ui.viewer.view.MarkingLayout;
import jp.agentec.abook.abv.ui.viewer.view.MarkingView;
import jp.agentec.abook.abv.ui.viewer.view.OperationTaskLayout;
import jp.agentec.abook.abv.ui.viewer.view.PageScrollView;
import jp.agentec.abook.abv.ui.viewer.view.PageView;
import jp.agentec.abook.abv.ui.viewer.view.ThumbnailSeekBarLayout;
import jp.agentec.abook.abv.ui.viewer.view.ZoomRelativeLayout;
import jp.agentec.abook.abv.ui.viewer.view.ZoomRelativeLayout.ViewMargin;
import jp.agentec.abook.abv.ui.viewer.view.action.ImageChangeAction;
import jp.agentec.abook.abv.ui.viewer.view.action.PageActionList;
import jp.agentec.abook.abv.ui.viewer.view.action.RichTextHtmlAction;
import jp.agentec.abook.abv.ui.viewer.view.action.TapMediaPlayer;
import jp.agentec.abook.abv.ui.viewer.view.action.VideoMountAction;
import jp.agentec.adf.net.http.HttpDownloadSimpleNotification;
import jp.agentec.adf.net.http.HttpDownloadState;
import jp.agentec.adf.util.FileUtil;
import jp.agentec.adf.util.StringUtil;

public class ContentViewActivity extends ABVContentViewActivity {
	private static final String TAG = "ContentViewActivity";

	private ContentPageDao contentPageDao = AbstractDao.getDao(ContentPageDao.class);

	/**
	 * mMainLayout > mPageScrollView > mContentWrapLayout
	 */
	private MmainLayout mMainLayout; // メインレイアウト
	private PageScrollView mPageScrollView; // ページスクロールのためのカスタマイズスクロールビュー
	private RelativeLayout mContentWrapLayout; // 各ページを保持しているViewGroup
	private MarkingLayout mMarkingLayout; // マーキングレイアウト

	/**
	 * mMainLayout > mMarkingLayout
	 * 		-mToolBar
	 * 		-mPageScrollView
	 * 		-mPageNumberLayout
	 * 		-mLargeImageView
	 * 		-mSeekBarLayout
	 */
	private View mToolBar; // ツールバー
	private RelativeLayout mPageNumberLayout; // ページ番号
	private ImageView mLargeImageView;
	private ThumbnailSeekBarLayout mSeekBarLayout; // ページスライスバー
	private int mLThumViewSize;
	public static final int THUMB_STICK_SIZE = 10;


	private ContentJSON mContentJSON; // コンテンツのJSONデータ
	private PDFIndexInfoJSON mPDFIndexInfoJSON; // PDFインデックスのJSONデータ
	private PDFLinkJSON mPDFLinkJSON; // PDFリンクのJSONデータ
	private PageInfoJSON mPageInfoJSON; // オーサリング画面の各ページサイズのJSONデータ
	private Size mBaseFileSize;
	private ContentDto mContentDto;

	private float mMinDistance;// Scroll移動距離チェック時の最小移動距離値
	private float mScrollDistance; // 実際にスクロールかけた移動距離
	private int mAllPageCount = 1; // 全ページ数

	private Dialog mSearchDialog; // 検索ボックス

	private GestureDetector mActivityGestureDetector; // フリックやスクロールジェスチャーを感知する。通常のScrollViewはページ遷移できないため。
	private ScrollStatus mScrollStatus = ScrollStatus.NONE;

	private long mFromOverEventPointTime = System.currentTimeMillis(); // 前回スクロール（フリック）した時間（連続フリックを制する為）

	/** Audio関連 **/
	private ABVMediaPlayer contentBGMPlayer;
	private ABVMediaPlayer pageBGMPlayer;
	private TapMediaPlayer tapPlayer;
	private SparseArray<String> pageBGMPathList;
	private ArrayList<PageActionList> mPageActionList;

	private ToggleButton tbtnMarking;

	private boolean isSeeking = false;
	private boolean isMarking = false;
	private boolean isVideoMax = false;

	private boolean isLandscapeView;

	private static final int VIDEOVIEW = 100;
	private static final int WEBVIEW = 200;
	private static final int PREVIEW = 300;

	private List<MarkingView> mMarkingViewList;
	private boolean isAnotherViewOpenFlg = false;

	private String mSearchWord;
	private static final int HIGHLIGHT_COLOR = 0x80FF00FF; // 検索結果のテキストハイライト
	private Bitmap baseBitmap = null; // ハイライト用元Bitmap

	private int intervalAddOrRemovePage = 200;

	private ToggleButton slide ;

	private boolean contentLinkStatus = false; //콘텐츠 링크의 상태 Flg.

	//앙케이트 모드
	private EnqueteLayout enqueteLayout;

	private boolean isEnquete = false;
	private boolean isEnqueteLeft = false;
	private boolean isEnqueteFullScreen;
	private boolean isDisallowMovePage  = false;

    // 作業指示、作業報告
    private OperationTaskLayout operationTaskLayout;
    private LinearLayout mScaleZoomLayout;
    private boolean isOpenedOperationTask = false;
    private TaskHotspotJSON mTaskHotspotJSON;
    // 移動・タップモードの切り替えボタン
	protected ImageButton btnMoveOrClickToggleIcon;
    // ピンと作業コードの切り換えボタン
    protected ImageButton btnPinToggleIcon;
    // 作業非表示のボタン
    protected ImageButton btnHideTaskDirectBtn;
    protected ImageButton btnScaleZoomPlus;
    protected ImageButton btnScaleZoom03;
    protected ImageButton btnScaleZoom02;
    protected ImageButton btnScaleZoom01;
    protected ImageButton btnScaleZoomMinus;

	//앙케이트 공통화 설문일때 직전 EnqueteLayout을 저장
	//ym.chae
	private boolean touchFlg = false;

	//ym.chae
	public static HashMap<Long, EnqueteLayout> enqueteMap = new HashMap<>();

	//프리뷰 상태일때 Flag 값
	private boolean preViewFlg;

	//플레이 탭사운드 Flag 값
	private boolean playTapSoundFlg = false;
	private String preSoundFilePath;

	//좌우 버튼 값 Flg
	private boolean moveBtnFlg = false;
	private boolean mEndFlg=false;

	private boolean pageBgmFlg =false;
	private boolean contentsBgmFlg = false;
	private String contentsBgmFilePath=null;

    private FoxitPdfCore mFoxitPdfCore = null; // PDFレンダリング
    private PdfImageProvider mPdfImageProvider = null;

	private boolean hasMultiPages;

	private RelativeLayout overlapLayout;
	private View subscriberToolBar;
	private ImageButton mExitBtn;
	private ImageButton mLinkOriginalBackBtn;
	private ImageButton mHistoryBtn;
	private ImageButton mBtnMeetingRoomSetting;
	private ImageButton mBtnRemoteStart;
	private ConcurrentHashMap<Long, View> objectIdButtonMap = new ConcurrentHashMap<>();
	private SharedPreferences pref;

	private FullVideoView fullVideoView;

	private long availableImageBytePerPage;
	private boolean onCreateFinish = false; // カーソル連動に使用

	private SparseArray<ZoomRelativeLayout> mShowPageLayout = new SparseArray<>();
	private boolean testMode = false; // 単体TEST用
//	private Matrix mZoomMatrix = null;

	private boolean isEnqueteOpening = false;

    private ProgressBar m_progress;
    public ValueCallback<Uri[]> mUploadMessage;
	// ピン・作業コード表示フラグ
	public boolean mShowPinFlg = true;
	// 移動・タップモードのフラグ
	public boolean mMoveTaskFlg = false;
	
	/**
	 * スクロールステータス
	 */
	enum ScrollStatus {
		NONE,
		SCROLL,
		FLING
	}

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		Logger.i(TAG, "[onCreate]:contentId=" + getContentId());
		super.onCreate(savedInstanceState);

		// 全画面表示
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// 初期値設定
		pageBGMPathList = new SparseArray<>();
		mPageActionList = new ArrayList<>();
		mMarkingViewList = new ArrayList<>();
		mActivityGestureDetector = new GestureDetector(getApplicationContext(), mGestureListener);
		pref = PreferenceManager.getDefaultSharedPreferences(ContentViewActivity.this);

		//앙케이트 공통화 설문
		enqueteMap.clear();

		// 全体アクション情報などコンテンツ情報を保持するJSONデータ
		try {
			mContentJSON = contentLogic.getContentInfoJson(mContentDir, contentId);
		} catch (IOException e) {
			Logger.e(TAG,  "getContentInfoJson failed. contentDir=" + mContentDir, e);
		} catch (JSONException e) {
			Logger.e(TAG,  "getContentInfoJson failed. contentDir=" + mContentDir, e);
		}
		if (mContentJSON == null) {
			Logger.e(TAG,  "Content JSON Data is Null.contentDir=" + mContentDir);
			initError();
			return;
		}

		if (mContentJSON.isPdf()) { // 一般PDFコンテンツの場合
			// PDFのIndex情報を取得
			try {
				// 指定コンテンツIDのPDFIndexJSON情報を取得
				mPDFIndexInfoJSON = new PDFIndexInfoJSON(FileUtil.readTextFile(mContentDir + "/outline.json"));
				// 指定コンテンツIDのPDFLinkJSON情報を取得
				mPDFLinkJSON =  new PDFLinkJSON(FileUtil.readTextFile(mContentDir + "/link.json"));
				// 指定コンテンツIDのpage info情報を取得
				mPageInfoJSON = new PageInfoJSON(FileUtil.readTextFile(mContentDir + "/pageInfo.json"));

				if(isOperationPdf()) {
                    getTaskHotspotJSON();
                }
			} catch (IOException e) {
				Logger.e(TAG, "read json failed.", e);
				initError();
				return;
			} catch (OutOfMemoryError e) {
				ABVToastUtil.showMakeText(getApplicationContext(), R.string.OUT_OF_MEMORY, Toast.LENGTH_SHORT);
				Logger.e(TAG, "[OutOfMemoryError]", e);
				initError();
				return;
			} catch (JSONException e) {
				Logger.e(TAG, "read json failed.", e);
				initError();
				return;
			}

			String fileName = mContentJSON.getPdfFileName();
			if (Logger.isDebugEnabled()) {
				Logger.d(TAG, "[onCreate]:fileName=%s, lastIndex=%s", fileName, fileName.lastIndexOf("."));
			}


			try {
				//mFoxitPdfCore インスタンスを作成
				mFoxitPdfCore = initPdf(fileName);
			} catch (Exception e) {
				Logger.e(TAG, "initPdf error.", e);
			}
			if (mFoxitPdfCore == null) {
				// PDF読み込み失敗
				initError();
				return;
			}

			try {
				boolean isExistPassWord = mFoxitPdfCore.loadPDFDoc(null);
				if(isExistPassWord) {
					// PDFパスワードあり
					DownloadedContentInfoJSON json = ContentFileUtil.getDownloadedContentInfoJSON(contentId);
					if (json.pdfPassword == null) {
						// エラー
						Logger.e(TAG, "pdfPassword is null. contentId=" + contentId);
						initError();
						return;
					} else {
						// PDF読み込み
						mFoxitPdfCore.loadPDFDoc(json.pdfPassword.getBytes());
					}
				}
			} catch (PDFException e) {
				Logger.e(TAG, "FoxitPdfCore load failed.", e);
				initError();
				return;
			} catch (Exception e) {
				Logger.e(TAG, "read json failed.", e);
				initError();
				return;
			}

			try {
				mAllPageCount = mFoxitPdfCore.countPages();
				mBaseFileSize = new Size(mFoxitPdfCore.getPageSize(0));
			} catch (PDFException e) {
				Logger.e(TAG, "FoxitPdfCore getPageSize failed.", e);
				initError();
				return;
			}
			if (mAllPageCount != mContentJSON.getPageCount()) {
				// ERROR ??
				Logger.w(TAG, "PDF page count is not equal Json Page Count");
			}
		} else { // ベースなし
			int width = mContentJSON.getWidth();
			int height = mContentJSON.getHeight();
			mBaseFileSize = new Size(width, height);
			mAllPageCount = mContentJSON.getTotalPageNum();
		}

		isLandscapeView = mBaseFileSize.width > mBaseFileSize.height;

		// 利用可能メモリ設定
		long maxMemory = Runtime.getRuntime().maxMemory();
		Logger.i(TAG, "maxMemory=" + maxMemory);
		availableImageBytePerPage = (long) (maxMemory * 0.8 / 3); // １ページあたりオーサリング・イメージに使用できるメモリ量（0.2は他のオブジェクトでの使用想定。3は3ページ分キャッシュするため） TODO: later ページごとに最適化

		// contentDtoをセット
		mContentDto = AbstractDao.getDao(ContentDao.class).getContent(contentId);
		// UI生成
		try {
			onCreateUIProcess(false);
		} catch (Exception e) {
			Logger.e(TAG, "onCreateUIProcess error.", e);
			initError();
			return;
		}

		if (!PreferenceUtil.get(this, DefPrefKey.DISPLAY_MARKING, true)) {
			tbtnMarking.setChecked(false);
		}

		onCreateFinish = true;

		ContentReadingLogLogic logic = AbstractLogic.getLogic(ContentReadingLogLogic.class);
		logic.prepareContentReadLog(contentId);
	}

	@Override
	protected void onResume() {
		Logger.i(TAG, "onResume");
		super.onResume();
		
		// コンテンツリンクから戻ってきた場合に参加者がコンテンツを開くためにonCreateからこちらに移動
		if (meetingManager.isSendable()) {
			meetingManager.sendWs(MeetingManager.CMD_OPEN, contentId, mCurrentPageNumber, null, null);
		}

		playPageBGMSound(mCurrentPageNumber);

		// ページ別ログ
		ContentLogUtil.getInstance().startContentPageReadLog(contentId, readingLogId, mCurrentPageNumber);

		// onCreateでviewが作成されている場合、readingLogIdが-1になってしまうので更新
		for (PageActionList pageActionList : mPageActionList) {
			for (VideoMountAction videoMountAction : pageActionList.arrayVideoMount) {
				videoMountAction.readingLogId = readingLogId;
			}
			for (VideoMountAction videoMountAction : pageActionList.arrayVideoChange) {
				videoMountAction.readingLogId = readingLogId;
			}
			for (Action3DImageView action3dImageView : pageActionList.array3DImage) {
				action3dImageView.readingLogId = readingLogId;
			}
		}

	}

	@Override
	public void finish() {
		Logger.i(TAG, "finish");

//		Timestamp ts = DateTimeUtil.getCurrentTimestamp();
		contentDao.updateLastViewedPage(getContentId(), mCurrentPageNumber);
		// 携帯の場合、横コンテンツからTOPに戻るとSimpleSlideDrawerライブラリからエラーで落ちてしまうので、戻る前に縦向きに戻しておく
        setPortraitIfNormal();
        // 遠隔連動中に保存したマーキングファイルを削除
		ContentMarkingFileHelper contentMarkingFileHelper = new ContentMarkingFileHelper();
		contentMarkingFileHelper.deleteRemoteMarkingFile(contentId);
		super.finish();
	}

	protected void exitActivity() {
		Logger.d(TAG, "exitActivity");
		releaseInit();
		finish();

		if (isLinkedContent) {
			ActivityHandlingHelper.getInstance().finishAllLinkContentViewActivity();
		} else {
			ActivityHandlingHelper.getInstance().finishAllContentViewActivity();
		}
	}

	/**　
	 *　横、縦の設定
	 * @since 1.0.0
	 */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    	onCreateFinish = false;
    	if (mShowedPopupWindow != null && mShowedPopupWindow.isShowing()) {
			mShowedPopupWindow.dismiss();
		}

    	if (!mActivityFinishFlg) {// isRotatableはチェックしない
    		Logger.d(TAG, "[onConfigurationChanged]:newConfig=" + newConfig);
    		mShowPageLayout.clear();

			//noinspection VariableNotUsedInsideIf
			if (mContentWrapLayout != null) {
    			removeViews();
            }
            if (mPageScrollView != null) {
            	mPageScrollView.removeAllViews();
            }
            removeLargeThumView();

            if (mMainLayout != null) {
            	mMainLayout.removeAllViews();
            }
            mPageActionList.clear();

    		onCreateUIProcess(true);
//    		if (mZoomMatrix != null) {
//    			Logger.d(TAG, "[onConfigurationChanged]:" + mZoomMatrix.toString());
//    			ZoomRelativeLayout zoomLayout = mShowPageLayout.get(mCurrentPageNumber);
//    			zoomLayout.setZoomMatrix(mZoomMatrix);
//    		}

		}

    	if (isEnquete && enqueteLayout != null) { // アンケート入力値は維持する（回転固定するようにしたのでこの処理は意味がなくなった）
    		EnqueteWebView webView = enqueteLayout.getWebView();
    		ActionInfoJSON json = enqueteLayout.getActionInfoJSON(); // JSONException catch不要：すでにアンケートを表示しているので、throwされることは基本的にはない
    		enqueteLayout.removeAllViews();
    		showEnqueteLayout(webView, json);
    	}
    	else {
    		isEnquete = false;
    	}
    	onCreateFinish = true;
	}


	private void onCreateUIProcess(boolean configChangedFlg) {
		Logger.i(TAG, "mCurrentPageNumber=" +  mCurrentPageNumber);

		configureSize();

		mMainLayout = new MmainLayout(this);

		// ダミーのSurfaceViewを追加する。これを行わないとコンテンツの２ページ目に埋め込み動画がある場合は画面が一瞬真っ黒になる。
    	// SurfaceViewをLayoutにaddViewするタイミングで起きるが、大きさ0のSurfaceViewをここでセットすることで避けられる。
		mMainLayout.addView(new SurfaceView(this), new ViewGroup.LayoutParams(0, 0));
		mMainLayout.setFitsSystemWindows(true);
		mContentWrapLayout = new RelativeLayout(this);

		mPageScrollView = new PageScrollView(this);
		mPageScrollView.setHorizontalScrollBarEnabled(false); // ScrollBarを非表示
		mPageScrollView.addView(mContentWrapLayout, new ViewGroup.LayoutParams(mAllPageCount * mDisplaySize.width, FP));

		RelativeLayout.LayoutParams param0 = createParam(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        param0.addRule(RelativeLayout.CENTER_IN_PARENT);
        mMainLayout.addView(mPageScrollView, param0);

        // ツールバー生成
        createToolBar();

		hasMultiPages = mAllPageCount > 1;
        if (hasMultiPages) { // サムネイルバーとページ番号表示
    		mPageNumberLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.page_number, null);

        	int height = (int) ((isNormalSize()? ThumbnailSeekBarLayout.NORMAL_HEIGHT: ThumbnailSeekBarLayout.LARGE_HEIGHT) * getResources().getDisplayMetrics().density); // サムネイルバーの高さ
        	mLThumViewSize = (int) (200 * (float)height / ThumbnailSeekBarLayout.LARGE_HEIGHT); // 大サムネイル表示領域の設定
            mSeekBarLayout = new ThumbnailSeekBarLayout(this, mFoxitPdfCore, getContentId(), mAllPageCount, isLandscapeView, mDisplaySize.width, mDisplaySize.height, isNormalSize(), mPageNumberLayout);
			mSeekBarLayout.setId(id.seekbar_layout_id); // 番号は適当
            mSeekBarLayout.setVisibility(View.INVISIBLE);
    		mSeekBarLayout.setFitsSystemWindows(true);
        	RelativeLayout.LayoutParams param2 = createParam(ViewGroup.LayoutParams.MATCH_PARENT, height);
        	param2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        	mMainLayout.addView(mSeekBarLayout, param2);
    		mMainLayout.setFitsSystemWindows(true);

    		mPageNumberLayout.setVisibility(View.INVISIBLE);
        	RelativeLayout.LayoutParams param = createParam(ViewGroup.LayoutParams.MATCH_PARENT, (int)(convertDensitySize(50) + 0.5f));
        	param.setMargins(0, 0, 0, 10);
        	param.addRule(RelativeLayout.ABOVE, mSeekBarLayout.getId());
        	mMainLayout.addView(mPageNumberLayout, param);
        }

        if (isOperationPdf()) {
            createScaleZoomBar();
        }

        setContentView(mMainLayout);

        // 最初に表示するページ+αをセットする
        addFirstPages(configChangedFlg);

		// 遠隔連動設定
		initRemoteLayout();
		if (isCursorModeEnable()) {
			slide.setChecked(true); // 初期状態ではカーソルオフにする。
		}
		configureRemote();

		// マーキング引継ぎ
		if (isMarking) {
			isMarking = false;
			showMarkingLayout();
		}

        //playPageBGMSound(0); // 1ページ目にペーいBGMがあった場合


        //북마크 또는 콘텐츠 링크로 페이지 이동시 1페이지의 ContentBGM 체크
//        if (getIntent().getBooleanExtra("moveContentBGM", false)) {// ↓　履歴などあちこちから来るので一律チェックする
        	try {
        		moveCheckContentBGM();
			} catch (JSONException e) {
				Logger.e(TAG, "moveCheckContentBGM error.", e);
				handleErrorMessageToast(String.format(getString(R.string.C_E_CONTENT_2001), "bgm"));
			}
        	if (pageBgmFlg) {
        		playPageBGMSound(mCurrentPageNumber);
        	}
//        }

        if (mPdfImageProvider != null) {
        	mPdfImageProvider.setPauseTask(false);
        }

        if (isOperationPdf()) {
            createCheckToolbar();
            commonConfigureRemote();
            isOpenedOperationTask = operationTaskLayout.getVisibility() == View.VISIBLE;
        }
	}

	private void configureSize() {
		// 画面のサイズを指定
		setDisplaySize();

		// 画面スワイプ時の移動判定サイズ
		mMinDistance = mDisplaySize.width / 3;
	}

	/**
	 * ベースファイルなし用に背景を作成する
	 * @param size:Bitmapのサイズ
	 */
	private Bitmap createBackgroundForNoFile(Size size) {
		Bitmap bitmap = Bitmap.createBitmap(size.width, size.height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		Paint paint = new Paint();
		if (mContentJSON.getBackgroundColor() != null && mContentJSON.getBackgroundColor().length() == 6) {
			int r = Integer.parseInt(mContentJSON.getBackgroundColor().substring(0, 2), 16);
			int g = Integer.parseInt(mContentJSON.getBackgroundColor().substring(2, 4), 16);
			int b = Integer.parseInt(mContentJSON.getBackgroundColor().substring(4, 6), 16);
			paint.setARGB(mContentJSON.getBackgroundAlpha(), r, g, b);
		}
		else {
			paint.setColor(Color.WHITE);
		}
		canvas.drawRect(new RectF(0, 0, size.width, size.height), paint);
		return bitmap;
	}

	/**
	 * 遠隔連動の状態に応じて、ツールバーや機能制限等の設定を行う
	 *
	 */
	@Override
	public void configureRemote() {
        configureCursorMode(); // いったん一律設定する
		if (meetingManager.isConnected()) {
			if (meetingManager.isSubscribed()) { // 参加者
				if (meetingManager.isPaused()) { // 休止中
					unlimitViewer();
					mPageScrollView.setFixFlag(false); // スワイプ可能にする
					mMainLayout.setRemoteDraw(false);
				} else {
					limitViewer();
					slide.setVisibility(View.INVISIBLE); // 受信者の時はカーソル設定を表示しない
					mPageScrollView.setFixFlag(true);
				}
				mBtnRemoteStart.setVisibility(View.VISIBLE);
				mExitBtn.setVisibility(View.INVISIBLE);
				mHistoryBtn.setVisibility(View.GONE); // 履歴は表示しない
			} else { // 司会者
				unlimitViewer();
				if (isCursorModeEnable()) { // 初期状態では司会者はカーソルオフにする
					slide.setChecked(true);
				}
				switchMeetingExitButton();
				mPageScrollView.setFixFlag(false);
			}
		} else { // 会議室に参加していない場合
			unlimitViewer();
		}
	}

	private void configureCursorMode() {
		if (isCursorModeEnable()) {
			slide.setVisibility(View.VISIBLE);
			mPageScrollView.setFixFlag(!slide.isChecked());
		}
		else {
			slide.setVisibility(View.GONE);
		}
	}

	private void limitViewer() {
		mToolBar.setVisibility(View.INVISIBLE);
		overlapLayout.setVisibility(View.VISIBLE);
		if (mSeekBarLayout != null) {
			mSeekBarLayout.setVisibility(View.INVISIBLE);
		}
	}

	private void unlimitViewer() {
		overlapLayout.setVisibility(View.GONE);
		mBtnRemoteStart.setVisibility(View.GONE);

		if (meetingManager.isSubscribed() || meetingManager.isSendable()) {
			mBtnMeetingRoomSetting.setVisibility(View.GONE);
		}

		if (!isOperationPdf()) {
			mExitBtn.setVisibility(View.VISIBLE);
		}
	}

	private void initRemoteLayout() {
		overlapLayout = new RelativeLayout(this);
		RelativeLayout.LayoutParams param = createParam(FP, FP);

		subscriberToolBar = getLayoutInflater().inflate(R.layout.content_view_remote_toolbar, null);
		subscriberToolBar.setVisibility(View.GONE);
		overlapLayout.addView(subscriberToolBar, createParam(FP, WC));

		overlapLayout.setOnTouchListener(new OnTouchListener() {
			private long prevTime;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Logger.v(TAG, "overlap onTouch");
				if (System.currentTimeMillis() - prevTime < 300) {
					return true;
				}
				prevTime = System.currentTimeMillis();

				TranslateAnimation toolBarAnimation;
				if (subscriberToolBar.getVisibility() == View.GONE) {
					subscriberToolBar.setVisibility(View.VISIBLE);
					toolBarAnimation = new TranslateAnimation(0, 0, -subscriberToolBar.getHeight(), 0);
					Logger.d(TAG, "[singleTapMotion]:[subscriberToolBar]:VISIBLE");
					if (!meetingManager.isSubscribed() && (hasMultiPages && mPageNumberLayout != null)) {
						mPageNumberLayout.setVisibility(View.VISIBLE);
					}
				} else {
					subscriberToolBar.setVisibility(View.GONE);
					Logger.d(TAG, "[singleTapMotion]:[subscriberToolBar]:GONE");
					toolBarAnimation = new TranslateAnimation(0, 0, 0, -subscriberToolBar.getHeight());
					if (mSeekBarLayout != null) {
						mSeekBarLayout.setVisibility(View.INVISIBLE);
					}
					if (mPageNumberLayout != null) {
						mPageNumberLayout.setVisibility(View.INVISIBLE);
					}
				}
				toolBarAnimation.setDuration(500);
				return true;
			}
		});
		mMainLayout.addView(overlapLayout, param);

		TextView titleTxt = (TextView) subscriberToolBar.findViewById(R.id.txt_content_title);
		titleTxt.setText(mContentDto.contentName);

		ImageButton exitBtn = (ImageButton) subscriberToolBar.findViewById(R.id.btn_exit);
		exitBtn.setOnClickListener(new View.OnClickListener() {
			@Override
            public void onClick(View v) {
				Logger.v(TAG, "exit onClick");
				showMeetingExitDialog();
			}
		});

		// 会議室設定(参加者)
		ImageButton meetingRoomSettingBtn = (ImageButton) subscriberToolBar.findViewById(R.id.btn_meetingroom_setting);
		meetingRoomSettingBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Logger.v(TAG, "meetingRoomSettingBtn onClick");

				mShowedPopupWindow = new ABVPopupListWindow(ContentViewActivity.this, R.layout.popup_meetingroom_setting);
				mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_xlarge));

				// リソースパターンを適用
				TextView meetingRoomSettingTitle = (TextView) mShowedPopupWindow.findViewById(R.id.meetingroom_setting_title);
				meetingRoomSettingTitle.setText(PatternStringUtil.patternToInt(getApplicationContext(),
											R.string.meetingroom_setting,
											getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));

				TextView markignShareSettingTitle = (TextView) mShowedPopupWindow.findViewById(R.id.marking_share_setting_title);
				markignShareSettingTitle.setText(PatternStringUtil.patternToInt(getApplicationContext(),
												R.string.marking_share_setting,
												getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));

				// 司会者マーキング共有設定(参加者モード場合は非表示)
				CheckedTextView markingShareCheck = (CheckedTextView) mShowedPopupWindow.findViewById(R.id.checkedMarkingShare);
				markingShareCheck.setVisibility(View.GONE);

				// 会議室マーキング自動保存
				CheckedTextView markingAutoSaveCheck = (CheckedTextView) mShowedPopupWindow.findViewById(R.id.checkedMarkingAutoSave);

				boolean meetingMarkingAutoSaveFlag = PreferenceUtil.get(ContentViewActivity.this, AppDefType.UserPrefKey.MEETING_MARKING_AUTO_SAVE, false);
				markingAutoSaveCheck.setChecked(meetingMarkingAutoSaveFlag);
				markingAutoSaveCheck.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						CheckedTextView checkedTV = (CheckedTextView) v;
						boolean checkFlag = !checkedTV.isChecked();// 反対の値をセット
						checkedTV.setChecked(checkFlag);
						put(AppDefType.UserPrefKey.MEETING_MARKING_AUTO_SAVE, checkFlag);
					}
				});

				// 設定ポップアップ表示
				mShowedPopupWindow.showAsDropDown(v);
			}
		});

		meetingRoomSettingBtn.setVisibility(View.GONE);

		ImageButton promoteBtn = (ImageButton) subscriberToolBar.findViewById(R.id.btn_promote);
		promoteBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Logger.v(TAG, "promote onClick");
				sendPromoteRequest();
				subscriberToolBar.setVisibility(View.GONE);
			}
		});

		final ImageButton pauseBtn = (ImageButton) subscriberToolBar.findViewById(R.id.btn_remote_pause);
		pauseBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Logger.v(TAG, "remoteOnOff onClick");
				meetingManager.setPaused(true);
				configureRemote();

				if (isMarking) {
					closeMarkingLayout();
				} else {
					for (MarkingView markingView : mMarkingViewList) {
						markingView.reLoad();
					}
				}
			}
		});


		// 司会者用のexitボタン
		exitMeetingBtn = (ImageButton) mToolBar.findViewById(R.id.btn_exitMeeting);
		exitMeetingBtn.setOnClickListener(new View.OnClickListener() {
			@Override
            public void onClick(View v) {
				Logger.v(TAG, "exit onClick");
				showMeetingExitDialog();
			}
		});
	}

	private boolean addPageViewFinish;
	private boolean smoothScrollToFinish;

	private void addFirstPages(boolean configChangedFlg) {
		// 最初の2ページをレンダリングする
		touchFlg = true;
		addPageViewFinish = false;
		smoothScrollToFinish = false;

		Intent it = getIntent();
		int jumpPage = it.getIntExtra("page", -1);
		it.removeExtra("page");

        if (mCurrentPageNumber != 0) {
        	jumpPage = mCurrentPageNumber;
        }
        else if (jumpPage >= mAllPageCount) { // jumpPageが最終ページを超える場合、最終ページにする。
        	jumpPage = mAllPageCount - 1;
        }
        else if (jumpPage < 0) {
        	jumpPage = 0;
        }

		if (mContentJSON.isPdf() && getResources().getBoolean(R.bool.pdf_image_output)) { // ページイメージ作成Task実行
			if (mPdfImageProvider == null) {
				mPdfImageProvider = new PdfImageProvider(mFoxitPdfCore);
			}
			else {
				mPdfImageProvider.cancelAll(false); // 回転した場合いったんキャンセルする
			}

			if (hasMultiPages) {
				mSeekBarLayout.setPdfImageProvider(mPdfImageProvider);
			}
			mPdfImageProvider.setPauseTask(true);
			Size displaySize = mDisplaySize;
			mPdfImageProvider.createImage(contentId, jumpPage, displaySize);
		}

		Logger.d(TAG, "jumpPage=" + jumpPage);
		mCurrentPageNumber = jumpPage;
		addPageView(mCurrentPageNumber, configChangedFlg);
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				if (mAllPageCount > mCurrentPageNumber + 1) {
					addPageView(mCurrentPageNumber + 1);
				}
				if (mCurrentPageNumber > 0) {
					addPageView(mCurrentPageNumber - 1);
				}

				addPageViewFinish = true;
				if (smoothScrollToFinish) {
					touchFlg = false;
				}
			}
		}, 500);
		mPageScrollView.post(new Runnable() {
			@Override
			public void run() {
				mPageScrollView.smoothScrollTo(mCurrentPageNumber*mDisplaySize.width, 0);

				smoothScrollToFinish = true;
				if (addPageViewFinish) {
					touchFlg = false;
				}
			}
		});
	}

	private void put(String key, boolean val) {
		pref.edit().putBoolean(key, val).commit();
	}

	/**
	 * ツールバーを生成する
	 */
	private void createToolBar() {
		mToolBar = getLayoutInflater().inflate(R.layout.content_view_toolbar, null);
		mToolBar.setVisibility(View.GONE);
		mExitBtn = (ImageButton) mToolBar.findViewById(R.id.btn_exit);
		mExitBtn.setOnClickListener(new View.OnClickListener() {
			@Override
            public void onClick(View v) {
				Logger.d(TAG, "[exit] click!!");
				exitActivity();
			}
		});

		if (isOperationPdf()) {
			mExitBtn.setVisibility(View.GONE);
		}

		mLinkOriginalBackBtn = (ImageButton) mToolBar.findViewById(id.btn_link_original_back);
		mLinkOriginalBackBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Logger.d(TAG, "[btn_link_original_back] click!!");
                goToBack();
			}
		});

		mHistoryBtn = (ImageButton) mToolBar.findViewById(R.id.btn_history_list);
		mHistoryBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showHistoryList(v);
			}
		});
		mHistoryBtn.setVisibility(View.GONE);

		ImageButton indexBtn = (ImageButton) mToolBar.findViewById(R.id.btn_index_list);

		if (!isOperationPdf()) {
			indexBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mShowedPopupWindow = new ABVPopupListWindow(ContentViewActivity.this);
					if (isNormalSize()) {
						mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_normal));
					} else {
						mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_large));
					}

					final ArrayList<String> menuNameList = new ArrayList<>();
					menuNameList.add(getRString(R.string.bookmark));
					if (mContentJSON.isPdf()) {
						menuNameList.add(getRString(R.string.index));
					}

					mShowedPopupWindow.setRepresentNames(menuNameList);
					mShowedPopupWindow.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							if (menuNameList.get(position).equals(getRString(R.string.bookmark))) {
								// ブックマーク
								showBookmarkDialog();
							} else if (menuNameList.get(position).equals(getRString(R.string.index))) {
								// インデックス
								try {
									showPDFIndexkDialog();
								} catch (JSONException e) {
									Logger.e(TAG, "PDFIndexDialog error.", e);
									handleErrorMessageToast(String.format(getString(R.string.C_E_CONTENT_2001), "idx"));
								}
							}
							mShowedPopupWindow.dismiss();
						}
					});

					mShowedPopupWindow.showAsDropDown(v);
				}
			});
		} else {
			indexBtn.setVisibility(View.GONE);
		}

		// 会議室設定
		mBtnMeetingRoomSetting = (ImageButton) mToolBar.findViewById(R.id.btn_meetingroom_setting);
		if (meetingManager.isConnected() && Options.getInstance(this).getViewerMenuMarking() == 1 && !(isOperationPdf())) {
			mBtnMeetingRoomSetting.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Logger.v(TAG, "mBtnMeetingRoomSetting onClick");

					mShowedPopupWindow = new ABVPopupListWindow(ContentViewActivity.this, R.layout.popup_meetingroom_setting);
					mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_xlarge));

					// 司会者マーキング共有設定
					CheckedTextView markingShareCheck = (CheckedTextView) mShowedPopupWindow.findViewById(R.id.checkedMarkingShare);
					boolean chairmanMarkingShareFlag = PreferenceUtil.get(ContentViewActivity.this, AppDefType.UserPrefKey.CHAIRMAN_MARKING_SHARE, false);
					markingShareCheck.setChecked(chairmanMarkingShareFlag);

					// リソースパターンを適用
					markingShareCheck.setText(PatternStringUtil.patternToInt(getApplicationContext(),
												R.string.chairman_marking_share,
												getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));

					markingShareCheck.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							CheckedTextView checkedTV = (CheckedTextView) v;
							boolean checkFlag = !checkedTV.isChecked();// 反対の値をセット
							checkedTV.setChecked(checkFlag);
							put(AppDefType.UserPrefKey.CHAIRMAN_MARKING_SHARE, checkFlag);
						}
					});

					// 会議室マーキング自動保存
					CheckedTextView markingAutoSaveCheck = (CheckedTextView) mShowedPopupWindow.findViewById(R.id.checkedMarkingAutoSave);
					boolean meetingMarkingAutoSaveFlag = PreferenceUtil.get(ContentViewActivity.this, AppDefType.UserPrefKey.MEETING_MARKING_AUTO_SAVE, false);
					markingAutoSaveCheck.setChecked(meetingMarkingAutoSaveFlag);

					// リソースパターンを適用
					markingShareCheck.setText(PatternStringUtil.patternToInt(getApplicationContext(),
												R.string.marking_share_auto_save,
												getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));

					markingAutoSaveCheck.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							CheckedTextView checkedTV = (CheckedTextView) v;
							boolean checkFlag = !checkedTV.isChecked();// 反対の値をセット
							checkedTV.setChecked(checkFlag);
							put(AppDefType.UserPrefKey.MEETING_MARKING_AUTO_SAVE, checkFlag);
						}
					});

					// 設定ポップアップ表示
					mShowedPopupWindow.showAsDropDown(v);
				}
			});
		}

		mBtnMeetingRoomSetting.setVisibility(View.GONE);

		// 検索
		ImageButton search = (ImageButton) mToolBar.findViewById(R.id.btn_search);
		if (!isOperationPdf()) {
			search.setOnClickListener(new View.OnClickListener() {
				@Override
                public void onClick(View v) {
					showSearchListDialog(null);
				}
			});
		} else {
			search.setVisibility(View.GONE);
		}

		ImageButton marking = (ImageButton) mToolBar.findViewById(R.id.btn_marking);
		// 機能off または サービスオプション化されていてサービスオプションがfalseの場合非表示
		if (Options.getInstance(this).getViewerMenuMarking() == 0 || isOperationPdf()) {
			marking.setVisibility(View.GONE);
		} else {
			marking.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					//앙케이트 중 마킹 메뉴를 눌렀을때
					if (isEnquete) {
						showEnqueteMessageDialog();
					} else {
						showMarkingLayout();
					}
				}
			});
		}

        TextView tvContentTitle = (TextView)mToolBar.findViewById(R.id.txt_content_title);
        tvContentTitle.setText(mContentDto.contentName);

        final long bookContentId = getContentId();

        final ImageButton bookmark = (ImageButton) mToolBar.findViewById(R.id.btn_bookmark);
		if (!isOperationPdf()) {
			bookmark.setOnClickListener(new View.OnClickListener() {
				@Override
                public void onClick(View v) {
					Logger.d(TAG, "mCurrentPageNumber=" + mCurrentPageNumber);
					//権限のないコンテンツはしおり使用させない
					if (mContentDto.isUnAuthorizedContent) {
						showUnAuthorizedContentWarningDialog(getString(R.string.bookmark_unusabke));
						return;
					}

					if (isExistBookmark(mCurrentPageNumber)) {
						Logger.d(TAG, "ic_bookmark_off");
						bookmarkLogic.deleteContentBookmark(bookContentId, mCurrentPageNumber);
						bookmark.setBackgroundResource(R.drawable.ic_bookmark_off);
					} else {
						Logger.d(TAG, "ic_bookmark_on");
						CommonExecutor.execute(new Runnable() { // サムネイルを生成しておく
							@Override
							public void run() {
								PdfThumbnailProvider pdfThumbnailProvider = new PdfThumbnailProvider(getApplicationContext(), mFoxitPdfCore, getContentId(), isNormalSize());
								pdfThumbnailProvider.setPdfImageProvider(mPdfImageProvider);
								pdfThumbnailProvider.setIsLandscape(isLandscapeView);
								try {
									Bitmap bmSmall = pdfThumbnailProvider.getThumbnail(mCurrentPageNumber, true); // 小サムネイル
									Bitmap bmLarge = pdfThumbnailProvider.getThumbnail(mCurrentPageNumber, false); // 大サムネイル
									bmSmall.recycle();
									bmLarge.recycle();
								} catch (Exception e) {
									Logger.e(TAG, "PdfThumbnailProvider", e);
									handler.post(new Runnable() {
										@Override
										public void run() {
											ErrorMessage.showErrorMessageToast(getApplicationContext(), ErrorCode.E107);
										}
									});
								}
							}
						});
						ContentBookmarkDto dto = new ContentBookmarkDto();
						dto.contentId = bookContentId;
						dto.pageNum = mCurrentPageNumber;
						bookmarkLogic.insertContentBookmark(dto);
						bookmark.setBackgroundResource(R.drawable.ic_bookmark_on);
						Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.content_view_down);
						bookmark.startAnimation(animation);
					}
				}
			});
		} else {
			bookmark.setVisibility(View.GONE);
		}

        subMenuBtn = (ImageButton) mToolBar.findViewById(R.id.btn_sub_menu);
		if(!(isOperationPdf())) {
            if (mContentJSON.isPdf()) {
                subMenuBtn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        mShowedPopupWindow = new ABVPopupListWindow(ContentViewActivity.this);
                        if (isNormalSize()) {
                            mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_normal));
                        } else {
                            mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_large));
                        }

                        final int textCopyIndex;
                        final int cursorIndex;
						int index = 0;
                        ArrayList<String> menuNameList = new ArrayList<>();

                        // テキストコピーが有効な場合のみ
                        if (Options.getInstance(ContentViewActivity.this).getViewerMenuTextcopy() == 1 && mContentJSON.isPdf()) {
                            menuNameList.add(getRString(R.string.text_copy));
                            textCopyIndex = index++;
                        } else {
                            textCopyIndex = -1;//表示しない
                        }

                        // カーソル機能
                        String addText = isCursorModeEnable() ? "OFF" : "ON";
                        menuNameList.add(getRString(R.string.cursor) + addText);
                        cursorIndex = index++;

						mShowedPopupWindow.setRepresentNames(menuNameList);
						mShowedPopupWindow.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

								if (position == textCopyIndex) {
									// テキストコピー
									showTextDialog(mCurrentPageNumber);
								} else if (position == cursorIndex) {
									// カーソルON・OFF
									boolean cursorFlag = PreferenceUtil.get(ContentViewActivity.this, DefPrefKey.CURSOR_ENABLE, false);
									PreferenceUtil.put(ContentViewActivity.this, DefPrefKey.CURSOR_ENABLE, !cursorFlag);
									if (cursorFlag) {
										// スライド制御を元に戻す
										slide.setChecked(true);
									}
									configureCursorMode();
								}
								mShowedPopupWindow.dismiss();
							}
						});

						mShowedPopupWindow.showAsDropDown(subMenuBtn);
					}
				});
			} else {
				ViewGroup.LayoutParams params = subMenuBtn.getLayoutParams();
				params.width = 0;
			}
		} else {
			subMenuBtn.setVisibility(View.GONE);
		}

		slide = (ToggleButton) mToolBar.findViewById(R.id.tbtn_slide);
		tbtnMarking = (ToggleButton) mToolBar.findViewById(R.id.tbtn_marking);
		mBtnRemoteStart = (ImageButton) mToolBar.findViewById(R.id.btn_remote_start);

		if (isOperationPdf()) {
			slide.setVisibility(View.GONE);
			tbtnMarking.setVisibility(View.GONE);
			mBtnRemoteStart.setVisibility(View.GONE);
		} else {
			slide.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton compoundbutton, boolean isChecked) {
					mPageScrollView.setFixFlag(!isChecked);
					if (meetingManager.isSendable()) {
						JSONObject json = new JSONObject();
						json.put(MeetingManager.IS_CURSOR_MODE, !isChecked);
						meetingManager.sendWs(MeetingManager.CMD_CURSORMODE, getContentId(), mCurrentPageNumber, null, json);
					}
				}
			});

			tbtnMarking.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton compoundbutton, boolean isChecked) {
					PreferenceUtil.put(ContentViewActivity.this, DefPrefKey.DISPLAY_MARKING, isChecked);
					setMarkingViewVisibility(isChecked);
				}
			});

			mBtnRemoteStart.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					meetingManager.setPaused(false);
					mPageNumberLayout.setVisibility(View.INVISIBLE);
					configureRemote();
					for (MarkingView markingView : mMarkingViewList) {
						markingView.reLoad();
					}
				}
			});
		}

        //RelativeLayout.LayoutParams param1 = createParam(ViewGroup.LayoutParams.MATCH_PARENT, (int)(48 * tmpDensity + 0.5f));
        RelativeLayout.LayoutParams param1 = createParam(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        param1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        mMainLayout.addView(mToolBar, param1);

        if (!mContentJSON.isPdf()) { // PDF以外の場合お気に入り（カーソル、マーキング）のみの表示にする。（本来はボタンの生成自体が不要であるが）
        	search.setVisibility(View.GONE);
        }

        if (isOperationPdf()) {
            m_progress = (ProgressBar) mToolBar.findViewById(R.id.refresh_prog);
        }

		if(isLinkedContent) {
			ContentDto contentDto = AbstractDao.getDao(ContentDao.class).getContent(contentId);

			if (ContentJSON.KEY_PDF_TYPE.equals(contentDto.contentType) || ContentJSON.KEY_NONE_TYPE.equals(contentDto.contentType)
					|| ContentJSON.KEY_OTHER_TYPE.equals(contentDto.contentType)) {
				mExitBtn.setBackgroundResource(R.drawable.btn_first_back);
				mLinkOriginalBackBtn.setVisibility(View.VISIBLE);
				mHistoryBtn.setVisibility(View.GONE);
				indexBtn.setVisibility(View.GONE);
				mBtnMeetingRoomSetting.setVisibility(View.GONE);
				search.setVisibility(View.GONE);
				marking.setVisibility(View.GONE);
				tvContentTitle.setVisibility(View.GONE);
				bookmark.setVisibility(View.GONE);
				subMenuBtn.setVisibility(View.GONE);
				tbtnMarking.setVisibility(View.GONE);
				mBtnRemoteStart.setVisibility(View.GONE);
			}
		}
	}

	private void setMarkingViewVisibility(boolean visible){
		for (MarkingView markingView : mMarkingViewList) {
			if (visible) {
				markingView.setVisibility(View.VISIBLE);
			} else {
				markingView.setVisibility(View.GONE);
			}
		}

		if (meetingManager.isSendable()) {
			JSONObject json = new JSONObject();
			if (visible) {
				json.put(MeetingManager.MARKING_ACTION, MeetingManager.MARKING_ACTION_VISIBLE);
			} else {
				json.put(MeetingManager.MARKING_ACTION, MeetingManager.MARKING_ACTION_INVISIBLE);
			}

			meetingManager.sendWs(MeetingManager.CMD_MARKING, contentId, mCurrentPageNumber, null, json);
		}
	}

	/**
	 * ThumbnailSeekBarから表示する大サムネイルを生成する
	 *  枠と突起物の描画のキャッシュ（BitmapとCanvas）
	 *
	 * @param page
	 * @param left
	 * @param top
	 * @param stickCenter 突起物x座標
	 * @param pageNumHSize ページ番号表示用height
	 * @param thumb サムネイルデータ
	 */
	public void createLargeThumView(int page, int left, int top, int stickCenter, int pageNumHSize, Drawable thumb) {
		// 枠を生成する。
		Bitmap bitmap = Bitmap.createBitmap(mLThumViewSize, mLThumViewSize + pageNumHSize + THUMB_STICK_SIZE, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		Paint paint = new Paint();
		int LARGE_HIGHLIGHT_COLOR = 0xD025120C;
		paint.setColor(LARGE_HIGHLIGHT_COLOR);
		paint.setAntiAlias(true);
		canvas.drawRoundRect(new RectF(0, 0, mLThumViewSize, mLThumViewSize + pageNumHSize), 10, 10, paint);

		// 突起物を表示する
		Path drawPath = new Path();
		drawPath.moveTo(stickCenter - THUMB_STICK_SIZE, mLThumViewSize + pageNumHSize);
		drawPath.lineTo(stickCenter, mLThumViewSize + pageNumHSize + THUMB_STICK_SIZE);
		drawPath.lineTo(stickCenter + THUMB_STICK_SIZE, mLThumViewSize + pageNumHSize);
		drawPath.close();
		canvas.drawPath(drawPath,paint);

		// ページ番号の表示
		Paint paintText = new Paint();
		paintText.setColor(Color.WHITE);
		paintText.setTextSize(15f);
		String pageText = "Page " + (page + 1);
		canvas.drawText(pageText, mLThumViewSize / 2 - pageText.length() * 4, mLThumViewSize + pageNumHSize / 2 - (isLandscapeView?13:0), paintText);

		// サムネイルの描画
        thumb.draw(canvas);

        mLargeImageView = new ImageView(this);
        mLargeImageView.setImageBitmap(bitmap);

		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mLThumViewSize, mLThumViewSize + pageNumHSize + THUMB_STICK_SIZE);
		params.setMargins(left, top, 0, 0);

        mMainLayout.addView(mLargeImageView, params);
	}

	public void removeLargeThumView() {
		if (mLargeImageView != null) {
            mLargeImageView.setImageDrawable(null);
			mMainLayout.removeView(mLargeImageView);
            mLargeImageView = null;
		}
	}

	private void allReset() {
		stopSound();
		stopVideo();
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	private RelativeLayout.LayoutParams createParam(int w, int h) {
        return new RelativeLayout.LayoutParams(w, h);
    }

	/**
	 * SimpleOnGestureListener
	 **/
	private SimpleOnGestureListener mGestureListener = new SimpleOnGestureListener() {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			if (System.currentTimeMillis() - mFromOverEventPointTime < 700) { // 0.7秒
				return false;
			}

			if (mSeekBarLayout != null && mSeekBarLayout.isSeeking()) {
				return false;
			}

			if (mPageScrollView.isZooming() == false && !isEnqueteOpening) {
				stopVideo();
			}

			if (isEnquete && isEnqueteFullScreen) {
				return false;
			} else if (isDisallowMovePage) {
				isDisallowMovePage = true;
			} else if (isSeeking == false) {
				Logger.v(TAG, "[SimpleOnGestureListener]:[onFling]");
				if (e1 != null && e2 != null) {
					scrollToPage(e1.getX(), e2.getX());
				}
				mScrollStatus = ScrollStatus.FLING;
				mFromOverEventPointTime = System.currentTimeMillis();
				return true;
			} else {
				isSeeking = false;
			}
			return false;
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

			if (mSeekBarLayout != null && mSeekBarLayout.isSeeking()) {
				return false;
			}

			if (isEnquete && isEnqueteFullScreen) {
				return false;
			} else if (isDisallowMovePage) {
				isDisallowMovePage = false;
			} else if (isSeeking) {
				isSeeking = false;
			} else{
				if (mPageScrollView.isZooming() == false && !isEnqueteOpening) {
					stopVideo();
				}

				if (e1 != null && e2 != null) {
                    mScrollDistance = e1.getX() - e2.getX();
				}
				mScrollStatus = ScrollStatus.SCROLL;
				Logger.d(TAG, "[SimpleOnGestureListener]:[onScroll]:mScrollDistance=" + mScrollDistance);
				// ページ遷移の判定はdispatchTouchEventで行う
			}
			return super.onScroll(e1, e2, distanceX, distanceY);
		}
	};

	//2012 12 17 Contents link by jeonghun
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Logger.d(TAG, "KeyEvent.KEYCODE_BACK");

			if (isVideoMax) {
				videoMaxToDefault();
			} else if (isMarking) {
				mMarkingLayout.showSaveDialog();
			} else if (isEnquete) {
				enqueteLayout.showEnqueteDialog(); //앙케이트 중 뒤로가기 버튼을 누를시 Alert 표시
			} else if (fullVideoView != null) {
				fullVideoView.close();
				fullVideoView = null;
			} else {
				if (meetingManager.isSubscribed()) { // 参加者の場合pause状態にする。
					showMeetingExitDialog();
					return false;
				}

				allReset();

				mActivityFinishFlg = true;
				if(isLinkedContent) {
					goToBack();
				} else {
					if (mOperationId <= 0) { //通常PDFコンテンツのみ戻る機能有効
						moveToBack();
					}
				}
			}
			return false;
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected void onStop() {
		Logger.d(TAG, "onStop");
		// ページ別ログ
		if (!DeviceInfo.isForegrdound(getApplicationContext())) {
			ContentLogUtil.getInstance().pauseContentPageReadLog(contentId, mCurrentPageNumber, readingLogId);
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Logger.d(TAG, "onDestroy");
		stopSound();
		stopVideo();

		if (fullVideoView != null) {
			fullVideoView.close();
			fullVideoView = null;
		}
		objectIdButtonMap.clear();
		objectIdPopupMap.clear();

		// ページ別ログ
		ContentLogUtil.getInstance().endContentPageReadLog(contentId, mCurrentPageNumber, readingLogId);


		super.onDestroy();
		removeViews();

    	ABVViewUnbindHelper.unbindReferences(mMainLayout);
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		if (mPdfImageProvider != null) {
			mPdfImageProvider.cancelAll(true);
		}
	}

	private void removeViews() {
		try{
			if (mContentWrapLayout != null) {
				int childCount = mContentWrapLayout.getChildCount();
				for (int i=childCount-1; i>= 0; i--) {
					View child = mContentWrapLayout.getChildAt(i);
					if (child instanceof RelativeLayout) {
						RelativeLayout pageLayout = (RelativeLayout) child;
						Logger.v(TAG, "memory:[removePage]:pageNumber=%s, instance=%s", pageLayout.getId(), pageLayout);
						for (int j=0; j < pageLayout.getChildCount(); j++) {
							if (pageLayout.getChildAt(j) instanceof PDFPageView) {
								PDFPageView ppv =(PDFPageView) pageLayout.getChildAt(j);
								ppv.releaseResources();
								break;
							}
						}
						pageLayout.removeAllViews();
						mContentWrapLayout.removeView(pageLayout);
					}
				}
			}
		}catch(Exception e) {
			Logger.e(TAG, "removeViews failed.", e);
			ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
		}

		if (mSeekBarLayout != null) {
			mSeekBarLayout.destroy();
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		try {
			if (touchFlg) {
				return false;
			}
			Logger.d(TAG, "[dispatchTouchEvent]:start");

			if (mPdfImageProvider != null) {
				mPdfImageProvider.setPauseTask(true);
			}

			Logger.d(TAG, "isVideoMax" + isVideoMax);
			mMainLayout.drawCursor(ev.getAction(), ev.getX(), ev.getY());

			try {
                // この処理は要る？？
				super.dispatchTouchEvent(ev);
			} catch (IllegalArgumentException e) {
				if (e.getMessage() != null && e.getMessage().contains("pointerIndex out of range")) {
					Logger.w(TAG, "[dispatchTouchEvent] event" + ev.toString() + " Exception=" + e.toString()); // 無視する
				}
				else {
					throw e;
				}
			}

			if (isMarking || isVideoMax) {
				return true;
			}

			int action = ev.getAction() & MotionEvent.ACTION_MASK;
			if (action == MotionEvent.ACTION_POINTER_UP) {
				Logger.d(TAG, "[dispatchTouchEvent]:action=" + action);
				mFromOverEventPointTime = System.currentTimeMillis();
			}
			boolean result = mActivityGestureDetector.onTouchEvent(ev);

	//		Logger.d(TAG, "[dispatchTouchEvent]:action=" + action + ", count=" + ev.getPointerCount());
			if (action == MotionEvent.ACTION_UP && mScrollStatus == ScrollStatus.SCROLL && mPageScrollView.isScrollable()) {
				// Scroll時のページ遷移の判定を行う
				if (Math.abs(mScrollDistance) > mMinDistance) {
					Logger.d(TAG, "mScrollDistance=%s, mMinDistance=%s", mScrollDistance, mMinDistance);
					scrollToPage((int)mScrollDistance);
				} else {
					// back current position
					Logger.d(TAG, "smoothScrollTo");
					mPageScrollView.smoothScrollTo(mCurrentPageNumber*mDisplaySize.width, 0);
				}
			}
			Logger.d(TAG, "[dispatchTouchEvent]:end:result=" + result);
			return result;
		} catch (Exception e) {
			// Point Error 対応
			Logger.e(TAG, "[dispatchTouchEvent]:e=" + e.getMessage(), e);
			ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
			return false;
		}
		finally {
			if (mPdfImageProvider != null) {
				mPdfImageProvider.setPauseTask(false);
			}
		}
	}

	/**
	 * TODO: later ツールバーに限らないので名前変更
	 *
	 * @param isVisible true:View.VISIBLE, false:View.GONE
	 */
	public void setToolbarVisable(boolean isVisible) {
		Logger.d(TAG, "[setToolbarVisable]:isVisable=" + isVisible);

		if (!meetingManager.isSubscribed() || meetingManager.isPaused()) {
			setBarVisible(isVisible);
		}

		TextView tvContentTitle = (TextView)mToolBar.findViewById(R.id.txt_content_title);
        tvContentTitle.requestFocus();

		if (isVisible) {
			if (hasMultiPages) {
				mSeekBarLayout.createThumbnail();
				mSeekBarLayout.showMidThum(mCurrentPageNumber);
			}

			ImageButton bookmark = (ImageButton) mToolBar.findViewById(R.id.btn_bookmark);
			if (isExistBookmark(mCurrentPageNumber)) {
				Logger.d(TAG, "ic_bookmark_on");
				bookmark.setBackgroundResource(R.drawable.ic_bookmark_on);
			} else {
				Logger.d(TAG, "ic_bookmark_off");
				bookmark.setBackgroundResource(R.drawable.ic_bookmark_off);
			}

			// マーキングが存在しない場合、アイコンを表示しない
			for (MarkingView markingView : mMarkingViewList) {
				if (markingView.getPageNum() == mCurrentPageNumber) {
					if (markingView.isMarkingExist()) {
						tbtnMarking.setVisibility(View.VISIBLE);
					} else {
						tbtnMarking.setVisibility(View.GONE);
					}
				}
			}
			if (hasMultiPages) {
				// ページ番号を表示する
				setCurrentPageNumber();
			}
		}
		else {
			if (hasMultiPages) {
				// サムネイルバーの大・中イメージを削除する
				removeLargeThumView();
				mSeekBarLayout.clearImageView();
			}
		}

		setMeetingParticipantCount(isVisible, mToolBar);
	}

	/**
	 * ツールバー・サムネイルバー・ページ番号の表示切替
	 *
	 * @param isVisable
	 */
	public void setBarVisible(boolean isVisable) {
		int visibility = isVisable ? View.VISIBLE : View.GONE;
		mToolBar.setVisibility(visibility);
		if (hasMultiPages) {
			visibility = isVisable ? View.VISIBLE : View.INVISIBLE;
			mSeekBarLayout.setVisibility(visibility);
			mPageNumberLayout.setVisibility(visibility);
		}
	}

    /**
     * 作業指示・報告・一覧画面ではヘルプボタンだけ表示
     * @param isVisable
     */
    public void setToolbarVisableForTask(boolean isVisable) {
        int visability = isVisable ? View.VISIBLE : View.GONE;

        if (isVisable) {
            operationHomeButton.setVisibility(View.INVISIBLE);
            taskListButton.setVisibility(View.INVISIBLE);
			helpButton.setVisibility(View.INVISIBLE);
            if (exitMeetingBtn != null && exitMeetingBtn.getVisibility() == View.VISIBLE) {
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WC, WC);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                params.addRule(RelativeLayout.CENTER_VERTICAL);
                params.rightMargin = (int) (getResources().getDisplayMetrics().density * 5);
                helpButton.setLayoutParams(params);

                exitMeetingBtn.setVisibility(View.GONE);
            }

            if (!isNormalSize()) {
                mToolBar.bringToFront();
            }
        } else {
            operationHomeButton.setVisibility(View.VISIBLE);
            taskListButton.setVisibility(View.VISIBLE);
			helpButton.setVisibility(View.VISIBLE);
            if (exitMeetingBtn != null && meetingManager.isSendable()) {
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WC, WC);
                params.addRule(RelativeLayout.LEFT_OF, R.id.btn_exitMeeting);
                params.addRule(RelativeLayout.CENTER_VERTICAL);
                params.rightMargin = (int) (getResources().getDisplayMetrics().density * 5);
                helpButton.setLayoutParams(params);

                exitMeetingBtn.setVisibility(View.VISIBLE);
            }
        }
        mToolBar.setVisibility(visability);
    }

	private void setCurrentPageNumber() {
		if (mPageNumberLayout != null) {
			TextView pageNumberTextView = (TextView)mPageNumberLayout.findViewById(id.txt_page_number);
			//noinspection deprecation(API16から非推奨になった。無視)
			pageNumberTextView.setBackgroundDrawable(getRDrawable(R.drawable.rounded_edittext));
			pageNumberTextView.setText((mCurrentPageNumber + 1) + " / " + mAllPageCount);
		}
	}

	/**
	 * called from ZoomRelativeLayout
	 */
	public void singleTapMotion() {
	    if (isOpenedOperationTask) {
            return;
        } else if (isEnquete) {
			return;
		}

		Logger.d(TAG, "[singleTapMotion]:isOnClick=false");
		if (mPageScrollView.isZooming()) {
			if (!isOperationPdf) {
				ZoomRelativeLayout zoomRelativeLayout = mShowPageLayout.get(mCurrentPageNumber);
				if (zoomRelativeLayout == null) {
					Logger.e(TAG, "zoomRelativeLayout is null");
					return;
				}
				// 拡大中は拡大率を表示
				int scale = (int) (mShowPageLayout.get(mCurrentPageNumber).getScaleFactor() * 100f);
				Toast.makeText(getApplicationContext(), String.format("%d%%", scale), Toast.LENGTH_SHORT).show();
			}
		} else {
			TranslateAnimation toolBarAnimation;
			if (mToolBar.getVisibility() == View.GONE) {
				setToolbarVisable(true);
				toolBarAnimation = new TranslateAnimation(0, 0, -mToolBar.getHeight(), 0);
				Logger.d(TAG, "[singleTapMotion]:[mToolBar]:VISIBLE");
			} else {
				setToolbarVisable(false);
				Logger.d(TAG, "[singleTapMotion]:[mToolBar]:GONE");
				toolBarAnimation = new TranslateAnimation(0, 0, 0, -mToolBar.getHeight());
			}
			toolBarAnimation.setDuration(500);

			if (hasMultiPages) {
				TranslateAnimation seekBarAnimation;
				if (mToolBar.getVisibility() == View.GONE) {
					seekBarAnimation = new TranslateAnimation(0, mDisplaySize.height, mDisplaySize.height - mSeekBarLayout.getHeight(), 0);
				} else {
					seekBarAnimation = new TranslateAnimation(0, mDisplaySize.height - mSeekBarLayout.getHeight(), mDisplaySize.height, 0);
				}
				seekBarAnimation.setDuration(500);
			}
		}
	}

	// #################################################################################################### //
	// ---------------------------------------------------------------------------------------------------- //
	// ---------------------------------------------------------------------------------------------------- //
	// ---------------------------------------------------------------------------------------------------- //
	// ---------------------------------------------------------------------------------------------------- //
	// ---------------------------------------------------------------------------------------------------- //
	// #################################################################################################### //


	// #################################################################################################### //
	// page controll
	// #################################################################################################### //

    /**
     * ページを追加する
     * @param pageNumber
     */
    private void addPageView(int pageNumber) {
        addPageView(pageNumber, false);
    }

	/**
	 * ページを追加する
	 * @param pageNumber
     * @param configChangedFlg
	 */
	private void addPageView(int pageNumber, boolean configChangedFlg) {

		if (pageNumber < 0 || pageNumber >= mAllPageCount) {
			return;
		}

		Logger.v(TAG, "[addPageView]start:page=%s", pageNumber);

		long totalBitmapSize = calcImageSize(pageNumber) + mDisplaySize.width * mDisplaySize.height * 4 * 2; // イメージボタンとPDFの合計サイズ
		boolean canDrawOrgSize = (totalBitmapSize < availableImageBytePerPage); // イメージをオリジナルサイズで描画してよいか

		RelativeLayout pageLayout = new RelativeLayout(this) {
			@Override
			public void removeView(View view) {
				if (view instanceof PDFPageView) {
					Logger.v(TAG, "pageLayout.removeView");
				}
				super.removeView(view);
			}
		};

		final int pageNum = pageNumber;
		mPageActionList.add(new PageActionList(pageNumber));

		pageLayout.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {

			@Override
            public void onChildViewRemoved(View parent, View child) {
				if (child instanceof PDFPageView) {
					Logger.v(TAG, "pageLayout.onChildViewRemoved:PDFPageView:%s", pageNum);
					((PDFPageView) child).releaseResources();
				} else if (child instanceof ViewGroup) {
					Logger.v(TAG, "pageLayout.onChildViewRemoved:ViewGroup:%s", pageNum);
					((ViewGroup) child).removeAllViews();
				}
			}

			@Override
            public void onChildViewAdded(View parent, View child) {
			}
		});

		pageLayout.setId(pageNumber);
		RelativeLayout.LayoutParams point = new RelativeLayout.LayoutParams(mDisplaySize.width, R_FP);
		point.setMargins(pageNumber * mDisplaySize.width, 0, 0, 0);
		mContentWrapLayout.addView(pageLayout, point);

		Size pageSize = null;
		PageView pageView;
		if (mContentJSON.isPdf()) {
			try {
				pageSize = new Size(mFoxitPdfCore.getPageSize(pageNumber));
			} catch (PDFException e) {
				//TODO エラーの場合、画面制御必要
				Logger.e(TAG, "getPageSize fail", e);
			}
			if(pageSize == null) {
				return;
			}
			pageView = new PDFPageView(this, mFoxitPdfCore, mPdfImageProvider, pageSize, pageNumber, mDisplaySize, pageLayout, contentId, isOperationPdf);
			((PDFPageView) pageView).setPage();
        }
		else { // none Type
			pageSize = mBaseFileSize;
			pageView = new PageView(this, pageSize, pageNumber, mDisplaySize.width, mDisplaySize.height, pageLayout, false);
			pageView.setImageBitmap(createBackgroundForNoFile(pageView.getInitSize())); // 各ページごとに同じイメージを作るがこれをやらないとズレる
		}

		// Android6でMATCH_PARENTをしてもViewが広がらないので直接サイズを指定するやり方に変更
//		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mDisplaySize.width, mDisplaySize.height);
//		params.addRule(RelativeLayout.CENTER_IN_PARENT);
//		pageView.setBackgroundColor(0xFFFF0000);
//		pageView.setLayoutParams(params);
		pageLayout.addView(pageView, mDisplaySize.width, mDisplaySize.height);

		final ZoomRelativeLayout zoomLayout = new ZoomRelativeLayout(this, isOperationPdf());
		zoomLayout.setPageSize(pageSize);
		zoomLayout.setPageNumber(pageNumber);
		zoomLayout.setContentDto(mContentDto);
		zoomLayout.setPageMargin(mDisplaySize.width, mDisplaySize.height);
		zoomLayout.setPageScrollView(mPageScrollView);
		PDFAuthoringSize authoringSize = new PDFAuthoringSize(pageSize);
		zoomLayout.setAuthoringScale(Math.min((float) mDisplaySize.width / authoringSize.width, (float) mDisplaySize.height / authoringSize.height));
		zoomLayout.setUnAuthorizedContentListener(unAuthorizedContentListener);

		if (mPageInfoJSON != null) {
			final PageInfoJSONData data = mPageInfoJSON.getPageData(pageNumber);
			zoomLayout.setAuthoringPageSize(data.pageWidth, data.pageHeight);
		} else {
			// PDFなしバージョン
			zoomLayout.setAuthoringPageSize(mBaseFileSize.width, mBaseFileSize.height);
		}

		addPDFLinkActionInfo(zoomLayout, pageNumber);

		//해당하는 액션 정보 버튼 추가
		addActionInfo(zoomLayout, pageNumber, canDrawOrgSize);

		if (isOperationPdf()) {
            createOperationTaskLayout(zoomLayout, pageNumber, configChangedFlg);
        }

		addMarkingView(zoomLayout, pageNumber);
		addSearchResult(zoomLayout, pageNumber);

		if (mContentJSON.isPdf()) {
			zoomLayout.setVisibility(View.GONE);
		}

		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mDisplaySize.width, mDisplaySize.height);
		params.addRule(RelativeLayout.CENTER_IN_PARENT);
		pageLayout.addView(zoomLayout, params);
		mShowPageLayout.put(pageNum, zoomLayout);
		Logger.v(TAG, "[addPageView]end:page=%s", pageNumber);
	}

	private long calcImageSize(int pageNumber) {
		JSONArray objects = mContentJSON.getPageObject(pageNumber);
		if (objects == null) {
			return 0;
		}

		ArrayList<String> pathList = new ArrayList<>();
		for (int i = 0; i < objects.length(); i++) {
			JSONObject pageObject = objects.getJSONObject(i);
			try {
				pathList.add(mContentDir + "/" + pageObject.getJSONObject("mediaInfo").getString("fileName"));
			} catch (JSONException e) {
				// ignore
			}
		}

		return BitmapUtil.getTotalBitmapSize(pathList, Config.ARGB_8888);

	}

	/**
	 * ページスクロールを行う
	 * @param direct 0より大き：右へ、0より小さい：左へ
	 */
	private void scrollToPage(int direct) {
		Logger.v(TAG, "[scrollToPage]:direct=%s isScrollable=%s", direct, mPageScrollView.isScrollable());
		if (mPageScrollView.isScrollable()) {
			stopVideo();
			setToolbarVisable(false);
			if (direct < 0) {
				// move left
				moveTo(-1);
				Logger.v(TAG, "[scrollToPage]:left=%s", mCurrentPageNumber);
			} else {
				// move right
				moveTo(1);
				Logger.v(TAG, "[scrollToPage]:right=%s", mCurrentPageNumber);
			}
			playPageBGMSound(mCurrentPageNumber);
		}
	}

	/**
	 * ページをスクロールさせる
	 * @param x1 Start Point
	 * @param x2 End Point
	 */
	private void scrollToPage(float x1, float x2) {
		scrollToPage((int)(x1 - x2));
	}

	/**
	 * 左/右側へ移動しながらページの追加、削除を行う
	 */
	private void moveTo(final int count) {

		Logger.d(TAG, "mCurrentPageNumber" + mCurrentPageNumber);

		final int currentPageNumber = mCurrentPageNumber;
		final int nextPageNumber = mCurrentPageNumber + count;
		if (nextPageNumber >= 0 && nextPageNumber < mAllPageCount) {
			mCurrentPageNumber = nextPageNumber;

			 // ページ別ログ
			ContentLogUtil.getInstance().contentPageMove(contentId, readingLogId, currentPageNumber, nextPageNumber);

			if (contentsBgmFlg && !StringUtil.isNullOrEmpty(contentsBgmFilePath) && !contentBGMPlayer.isPlaying()) {
				//contentsBgmFilePath
				contentBGMPlayer = new ABVMediaPlayer(true);
				try {
					Logger.v(TAG, "[addMusic]:MediaPlayer Content BGM");
					contentBGMPlayer.setDataSource(contentsBgmFilePath);
					contentBGMPlayer.prepare();
					contentBGMPlayer.start();
				} catch (IOException e) {
					Logger.e(TAG, "Can't play content BGM",e);
					ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
				}
			}

			//リモート機能
	        if (meetingManager.isSendable()) { // TODO: later 止まったタイミングで送るように要修正
				// マーキングモード終了を通知
				JSONObject json = new JSONObject();
				json.put(MeetingManager.MARKING_ACTION, MeetingManager.MARKING_ACTION_END);
				meetingManager.sendWs(MeetingManager.CMD_MARKING, getContentId(), currentPageNumber, null, json);

				// ページ移動
	        	meetingManager.sendWs(MeetingManager.CMD_MOVEPAGE, getContentId(), nextPageNumber, null, null);
	        }

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					removePage(currentPageNumber - count);// 前のページを削除
				}
			}, intervalAddOrRemovePage);

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					addPageView(nextPageNumber + count); // 先のページを追加
				}
			}, intervalAddOrRemovePage);

			mPageScrollView.post(new Runnable() {
				@Override
				public void run() {
					mPageScrollView.smoothScrollTo(nextPageNumber * mDisplaySize.width, 0);
				}
			});

			//jeonghun SeekBar Bug Fixed
	        setCurrentPageNumber();
			//jeonghun moveTo playPageBGM Bug Fixed
			playPageBGMSound(nextPageNumber);

			//탭사운드 플레이 Bug
			playTapSoundFlg = false;

			//좌우 버튼 이동시 툴바 갱신 버그 수정
			if (moveBtnFlg) {
				stopVideo();
				setToolbarVisable(true);
				setToolbarVisable(false);
				moveBtnFlg = false;
			}

			Logger.d(TAG, "[moveTo]:show page=" + nextPageNumber);
		} else {
			Logger.d(TAG, "### pass move to");
		}
	}


	/**
	 * 指定番号のページを削除する
	 * @param pageNumber 0から始まるページ番号
	 */
	private void removePage(int pageNumber) {
		Logger.i(TAG, "removePage: " + pageNumber);
		if (pageNumber < 0 || pageNumber >= mAllPageCount) {
			return;
		}

		int pcaIndex = getPageContentArrayIndex(pageNumber);
		if (pcaIndex >= 0) {
			if (mPageActionList.get(pcaIndex).arrayVideoMount != null) {
				for (int i = 0; i < mPageActionList.get(pcaIndex).arrayVideoMount.size(); i++) {
					mPageActionList.get(pcaIndex).arrayVideoMount.get(i).stopVideo();
				}
			}
			if (mPageActionList.get(pcaIndex).arrayVideoChange != null) {
				for (int i = 0; i < mPageActionList.get(pcaIndex).arrayVideoChange.size(); i++) {
					mPageActionList.get(pcaIndex).arrayVideoChange.get(i).stopVideo();
				}
			}
			mPageActionList.get(pcaIndex).clear();
			mPageActionList.remove(pcaIndex);
		}

		for (int i = 0; i < mMarkingViewList.size(); i++) {
			if (mMarkingViewList.get(i).getPageNum() == pageNumber) {
				mMarkingViewList.remove(i);
				break;
			}
		}

		for (int i = 0; i < mContentWrapLayout.getChildCount(); i++) {
			if (mContentWrapLayout.getChildAt(i) instanceof RelativeLayout) {
				RelativeLayout child = (RelativeLayout) mContentWrapLayout.getChildAt(i);
				if (child.getId() == pageNumber) {
					Logger.v(TAG, "memory:[removePage]:pageNumber=%s, instance=%s", child.getId(), child);
					RelativeLayout pageLayout = child;

					for (int j=0; j < pageLayout.getChildCount(); j++) {
						if (pageLayout.getChildAt(j) instanceof PDFPageView) {
							PDFPageView ppv =(PDFPageView) pageLayout.getChildAt(j);
							ppv.releaseResources();
						}
					}

					pageLayout.removeAllViews();
					mContentWrapLayout.removeView(child);
					break;
				}
			}
		}

		mShowPageLayout.remove(pageNumber);

	}

	// #################################################################################################### //
	// text search result
	// #################################################################################################### //

	/**
	 * 検索結果をハイライトする
	 *
	 * @param zoomLayout
	 * @param pageNumber
	 */
	private void addSearchResult(ZoomRelativeLayout zoomLayout, int pageNumber) {
		if (mSearchWord != null && mSearchWord.length() > 0) {
			Logger.v(TAG, "[addSearchResult]:page=%s mSearchWord=%s", pageNumber, mSearchWord);
			List<com.foxit.sdk.common.fxcrt.RectF> mSearchBoxes = mFoxitPdfCore.searchPage(pageNumber, mSearchWord);
			if(mSearchBoxes != null) {
				int searchBoxSize = mSearchBoxes.size();
				for(int i = 0; i < searchBoxSize; i++) {
					setSearchResult(zoomLayout, mSearchBoxes.get(i));
				}
			}
		}
	}

	private void setSearchResult(ZoomRelativeLayout zoomLayout, com.foxit.sdk.common.fxcrt.RectF rectF) {
		Logger.v(TAG, "[setSearchResult]:=%s", rectF);
		float pdfScale = zoomLayout.getPDFPageScale();

		int width = (int)(rectF.width() * pdfScale);
		int height = (int) (rectF.height() * pdfScale);
		int left = (int) (rectF.getLeft() * pdfScale);
		int top = mDisplaySize.height - (int) (rectF.getTop() * pdfScale);
		if (baseBitmap == null) {
			baseBitmap = Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(baseBitmap);
			Paint paint = new Paint();
			paint.setColor(HIGHLIGHT_COLOR);
			canvas.drawRect(0, 0, 10, 10, paint);
		}
		Bitmap bitmap = Bitmap.createScaledBitmap(baseBitmap, width, height, false);
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(bitmap);
		iv.setScaleType(ImageView.ScaleType.MATRIX);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
		params.setMargins(zoomLayout.getContentPageMargin().left + left, top - zoomLayout.getContentPageMargin().top, 0, 0);
		Logger.v(TAG, "[setSearchResult]:=%s", params);
		zoomLayout.addView(iv, params);
	}


	// #################################################################################################### //
	// page action info
	// #################################################################################################### //

	/**
	 * ページへPDFLinkアクション情報を追加する
	 * @param contentPageView ページ情報を持つViewLayout
	 * @param pageNumber
	 */
	private void addPDFLinkActionInfo(ZoomRelativeLayout contentPageView, final int pageNumber) {
		Logger.d(TAG, "[addPDFLinkActionInfo]:page=" + pageNumber);
		if (mPDFLinkJSON == null) {
			return;
		}
		JSONArray linkList = mPDFLinkJSON.getPageObject(pageNumber + 1);
		if (linkList == null) {
			return;
		}

		ViewMargin margin = contentPageView.getContentPageMargin();
		for (int i = 0; i < linkList.length(); i++) {
			try {
				ActionButton imgBtn = new ActionButton(getApplicationContext());
				//ym.chae
				//PDF 링크 걸린 색 변경 코드
				ContractLogic cs = AbstractLogic.getLogic(ContractLogic.class);
				if (cs.getPdfLinkDisp()) {
					imgBtn.setBackgroundColor(Color.parseColor("#304ABFD3"));
				} else {
					imgBtn.setBackgroundColor(Color.TRANSPARENT);
				}

				JSONObject obj = linkList.getJSONObject(i);
				RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(contentPageView.getResizedForDisplayScale(obj.getInt("linkLocationWidth")), contentPageView.getResizedForDisplayScale(obj.getInt("linkLocationHeight")));
				param.setMargins(margin.left + contentPageView.getResizedForDisplayScale(obj.getInt("linkLocationX")), margin.top + contentPageView.getResizedForDisplayScale(obj.getInt("linkLocationY")), 0, 0);
				imgBtn.setLayoutParams(param);
				contentPageView.addView(imgBtn);

				final int destPageNumber = obj.getInt("destPageNumber") - 1;
				final String destURI = obj.getString("destURI");
				switch (obj.getInt("linkKind")) {
				case 0:   //PageJump
					imgBtn.setOnClickListener(new View.OnClickListener() {
						@Override
                        public void onClick(View v) {
							jumpToPage(destPageNumber);
						}
					});
					break;
				case 1:   //URL, mail
					String strMail = "mailto:";
					if (destURI.length() > strMail.length() && strMail.equals(destURI.substring(0, strMail.length()))) {
						final String mailAddress = destURI.substring(strMail.length(), destURI.length());
						imgBtn.setOnClickListener(new View.OnClickListener() {
							@Override
                            public void onClick(View v) {
								sendEmail("", mailAddress);
							}
						});
					} else {
						imgBtn.setOnClickListener(new View.OnClickListener() {
							@Override
                            public void onClick(View v) {
								showWebView(destURI,"0", pageNumber, 0, -1);
						        if (meetingManager.isSendable()) {
						        	JSONObject json = new JSONObject();
									json.put(MeetingManager.URL, destURI);
									json.put(MeetingManager.BROWSER, destURI.startsWith("https"));
						        	meetingManager.sendWs(MeetingManager.CMD_LINKURLACTION, getContentId(), pageNumber, null, json);
						        }
							}
						});
					}
					break;
				}
			} catch (JSONException e) {
				Logger.e(TAG, "addPDFLinkActionInfo error. pageNumber=" + pageNumber + " i=" + i, e);
				handleErrorMessageToast(String.format(getString(R.string.C_E_CONTENT_2001), pageNumber + ":" + i));
			} catch (Exception e) {
				Logger.e(TAG, "error", e);
				ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
			}
		}
	}

	/**
	 * ページへアクション情報を追加する
	 * @param rootLayout ページ情報を持つViewLayout
	 * @param pageNumber
	 * @param canDrawOrgSize
	 */
	private void addActionInfo(ZoomRelativeLayout rootLayout, int pageNumber, boolean canDrawOrgSize) {
		Logger.d(TAG, "[addActionInfo]:page=" + pageNumber);

		JSONArray objects = mContentJSON.getPageObject(pageNumber);
		if (objects != null) {
			ArrayList<PageObjectJSON> triggerList = new ArrayList<>();
			for (int i = 0; i < objects.length(); i++) {
				try {
					PageObjectJSON pageObject = new PageObjectJSON(objects.getJSONObject(i));
					pageObject.setPageNumber(pageNumber);
					switch (pageObject.getMediaType()) {
					case MediaInfoJSON.BUTTON_TYPE:
						Logger.v(TAG, "BUTTON_TYPE");
						if (isShowable(pageObject)) {
							addButton(rootLayout, pageObject, canDrawOrgSize, i);
						}
						break;
					case MediaInfoJSON.VIDEO_TYPE:
						Logger.v(TAG, "VIDEO_TYPE");
						addVideo(rootLayout, pageObject);
						break;
					case MediaInfoJSON.MUSIC_TYPE:
						Logger.v(TAG, "MUSIC_TYPE");
						addMusic(rootLayout, pageObject);
						break;
					case MediaInfoJSON.CHANGE_IMAGE_TYPE:
						Logger.v(TAG, "CHANGE_IMAGE_TYPE");
						addChangeImage(rootLayout, pageObject);
						break;
					case MediaInfoJSON.CHANGE_VIDEO_TYPE:
						Logger.v(TAG, "CHANGE_VIDEO_TYPE");
						addChangeVideo(rootLayout, pageObject);
						break;
					case MediaInfoJSON.TRIGGER_TYPE:
						Logger.v(TAG, "TRIGGER_TYPE");
						triggerList.add(pageObject);
						break;
					case MediaInfoJSON.RICH_TEXT_TYPE:
						Logger.v(TAG, "RICH_TEXT_TYPE");
						addRichText(rootLayout, pageObject);
						break;
					case MediaInfoJSON.VIEW3D_TYPE:
						Logger.v(TAG, "VIEW3D_TYPE");
						addView3D(rootLayout, pageObject);
						break;
					case MediaInfoJSON.ENQUETE_TYPE:
						Logger.v(TAG, "ENQUETE_TYPE");
						if (ABVDataCache.getInstance().serviceOption.isEnquete()) {
							addButton(rootLayout, pageObject, canDrawOrgSize, i);
						}
						break;
					case MediaInfoJSON.EXAM_TYPE:
						Logger.v(TAG, "EXAM_TYPE");
						if (ABVDataCache.getInstance().serviceOption.isExam()) {
							addButton(rootLayout, pageObject, canDrawOrgSize, i);
						}
						break;
					case MediaInfoJSON.QUIZ_TYPE:
						Logger.v(TAG, "QUIZ_TYPE");
						if (ABVDataCache.getInstance().serviceOption.isQuiz()) {
							addButton(rootLayout, pageObject, canDrawOrgSize, i);
						}
						break;
					case MediaInfoJSON.HTML_TYPE:
						Logger.v(TAG, "HTML_TYPE");
						addButton(rootLayout, pageObject, canDrawOrgSize, i);
						break;
					default:
						break;
					}
				} catch (JSONException e) {
					Logger.e(TAG, "addActionInfo error. pageNumber=" + pageNumber + " i=" + i, e);
					handleErrorMessageToast(String.format(getString(R.string.C_E_CONTENT_2001), pageNumber + ":" + i));
				}
			}
			for (int j = 0; j < triggerList.size(); j++) {
				try {
					addTigger(rootLayout, triggerList.get(j));
				} catch (Exception e) {
					Logger.e(TAG, "addActionInfo error. pageNumber=" + pageNumber + " j=" + j, e);
					handleErrorMessageToast(String.format(getString(R.string.C_E_CONTENT_2001), pageNumber + ":" + j));
				}
			}
		}
		rootLayout.addMemo();
	}

	private boolean isShowable(PageObjectJSON pageObject) {
		switch (pageObject.getActionInfo().getActionType()) {
		case ActionInfoJSON.LINKURL_ACTION:
			break;
		case ActionInfoJSON.EMAIL_ACTION:
			break;
		case ActionInfoJSON.ENQUETE_ACTION:
			if (!ABVDataCache.getInstance().serviceOption.isEnquete()) {
				return false;
			}
			break;
		case ActionInfoJSON.EXAM_ACTION:
			if (!ABVDataCache.getInstance().serviceOption.isExam()) {
				return false;
			}
			break;
		case ActionInfoJSON.QUIZ_ACTION:
			if (!ABVDataCache.getInstance().serviceOption.isQuiz()) {
				return false;
			}
			break;
		}
		return true;
	}

	/**
	 * 通常ボタンのアクション
	 * @param contentPageView RelativeLayout
	 * @param pageObject PageObjectJSON
	 * @param canDrawOrgSize
	 */
	private void addButton(ZoomRelativeLayout contentPageView, final PageObjectJSON pageObject, boolean canDrawOrgSize, final int objIndex) {
		Logger.d(TAG, "[addButton]:type=" + pageObject.getActionInfo().getActionType());
		ViewMargin margin = contentPageView.getContentPageMargin();
		Logger.d(TAG, "addButton.margin=%s", margin);
		ActionButton imgBtn = makeActionButton(pageObject, margin, canDrawOrgSize, contentPageView);
		//試験、クイズ、アンケートのMediaTypeの場合：ボタンのテキストを設定
		if (pageObject.getMediaType()==MediaInfoJSON.ENQUETE_TYPE || pageObject.getMediaType()==MediaInfoJSON.QUIZ_TYPE || pageObject.getMediaType() == MediaInfoJSON.EXAM_TYPE) {
			
			String str = null;
			
			if (pageObject.getMediaType() == MediaInfoJSON.ENQUETE_TYPE) {
				str = getRString(R.string.enquete);
			} else if (pageObject.getMediaType() == MediaInfoJSON.EXAM_TYPE) {
				str = "EXAM";
			} else if (pageObject.getMediaType() == MediaInfoJSON.QUIZ_TYPE) {
				str = "QUIZ";
			}
			
			imgBtn.setText(str);

			contentPageView.addView(imgBtn);
		} else {
			contentPageView.addView(imgBtn);
		}
		final int pageNumber = pageObject.getPageNumber();
		imgBtn.setOnClickListener(new View.OnClickListener() {
			@Override
            public void onClick(View v) {
				try {
					handleAction((ActionButton)v, pageObject);
				} catch (JSONException e) {
					Logger.e(TAG, "handleAction error. pageNumber=" + pageNumber + " i=" + objIndex, e);
					handleErrorMessageToast(String.format(getString(R.string.C_E_CONTENT_2001), pageNumber + ":" + objIndex));
				}
			}
		});
	}
	/**
	 * ボタンにイメージをセットする
	 * @param pageObject
	 * @param margin
	 * @param canDrawOrgSize
	 * @param contentPageView
     * @return
     */

	private ActionButton makeActionButton(PageObjectJSON pageObject, ViewMargin margin, boolean canDrawOrgSize, ZoomRelativeLayout contentPageView) {

		LocationJSON location = pageObject.getLocation();
		ActionButton imgBtn = new ActionButton(getApplicationContext());
		if (pageObject.getActionInfo().getActionType() != ActionInfoJSON.EMAIL_ACTION) { // Emailは会議室受信側では無視
			objectIdButtonMap.put(pageObject.getActionInfo().getObjectId(), imgBtn);
		}
		imgBtn.setBackgroundColor(getRColor(AppColor.getTransparent()));// 背景を透明にする

		if (pageObject.getMediaType()==MediaInfoJSON.ENQUETE_TYPE || pageObject.getMediaType()==MediaInfoJSON.QUIZ_TYPE || pageObject.getMediaType() == MediaInfoJSON.EXAM_TYPE) {
			imgBtn.setImageResource(R.drawable.htmlback);
			//imgBtn.setAdjustViewBounds(false);
		}
		else if (pageObject.getMediaType()==MediaInfoJSON.HTML_TYPE) {
			String htmlImagePath = contentLogic.getHtmlImagePath(getContentId(), pageObject.getActionInfo().getHtml());
			try {
				if (StringUtil.isNullOrEmpty(htmlImagePath)) {
					imgBtn.setImageResource(R.drawable.btn_html);
				} else {
					if (canDrawOrgSize) {
						//noinspection deprecation(API16から非推奨になった。無視)
						imgBtn.setBackgroundDrawable(new BitmapDrawable(getResources(), BitmapUtil.getBitmap(htmlImagePath, Config.ARGB_4444)));
					} else {
						//noinspection deprecation(API16から非推奨になった。無視)
						imgBtn.setBackgroundDrawable(new BitmapDrawable(getResources(), BitmapUtil.getResizedBitmap(htmlImagePath, pageObject.getLocation().getWidth(), pageObject.getLocation().getHeight(), Config.ARGB_8888)));
					}
				}
			} catch (OutOfMemoryError e) {
				Logger.e(TAG, "imgBtn.setBackgroundDrawable/setImageResource failed.", e);
				ABVToastUtil.showMakeText(getApplicationContext(), R.string.OUT_OF_MEMORY, Toast.LENGTH_SHORT);
			}
		}
		else {
			Logger.v(TAG, "[makeActionButton]:ELSE=%s", pageObject.getMediaType());
			String fileName = pageObject.getMediaInfo().getFileName();
			if (fileName != null) {
				String imgPath = mContentDir + "/" + fileName;
				try {
					if (canDrawOrgSize) {
						//noinspection deprecation(API16から非推奨になった。無視)
						imgBtn.setBackgroundDrawable(new BitmapDrawable(getResources(), BitmapUtil.getBitmap(imgPath, Bitmap.Config.ARGB_4444)));
					}
					else {
						//noinspection deprecation(API16から非推奨になった。無視)
						imgBtn.setBackgroundDrawable(new BitmapDrawable(getResources(), BitmapUtil.getResizedBitmap(imgPath, pageObject.getLocation().getWidth(), pageObject.getLocation().getHeight(), Bitmap.Config.ARGB_8888)));
					}
				} catch (OutOfMemoryError e) {
					Logger.e(TAG, "imgBtn.setBackgroundDrawable failed.", e);
					ABVToastUtil.showMakeText(getApplicationContext(), R.string.OUT_OF_MEMORY, Toast.LENGTH_SHORT);
				}
			}
		}

		// 음악 아이콘 오서링 수정 (다음버전 반영예정)
		RelativeLayout.LayoutParams point = new RelativeLayout.LayoutParams(contentPageView.getResizedForDisplayScale(location.getWidth()), contentPageView.getResizedForDisplayScale(location.getHeight()));
		point.setMargins(margin.left + contentPageView.getResizedForDisplayScale(location.getX()), margin.top + contentPageView.getResizedForDisplayScale(location.getY()), 0, 0);
		imgBtn.setLayoutParams(point);

		return imgBtn;
	}

	/**
	 * 実際のActionを制御する
	 * @param actionButton ActionButton
	 * @param pageObject PageObjectJSON
	 */
	private void handleAction(ActionButton actionButton, PageObjectJSON pageObject) {
		ActionInfoJSON actionInfoJSON = pageObject.getActionInfo();
		int pageNumber = pageObject.getPageNumber();

		if (meetingManager.isSendable()
				&& actionInfoJSON.getActionType() != ActionInfoJSON.EMAIL_ACTION
				&& actionInfoJSON.getActionType() != ActionInfoJSON.CONTENTLINK_ACTION) { // リモート送信(メール・コンテンツリンクを除く)
        	meetingManager.sendWs(MeetingManager.CMD_ACTION, getContentId(), pageNumber, actionInfoJSON.getObjectId(), null);
        }

		int objectLogId = -1;
		// オブジェクトログ
		if(actionInfoJSON.getActionType() != ActionInfoJSON.MUSIC_ACTION){
			objectLogId = ContentLogUtil.getInstance().insertContentObjectLog(contentId, readingLogId, pageObject);
		}

		switch (actionInfoJSON.getActionType()) {
		case ActionInfoJSON.VIDEO_ACTION:
			// 動画を再生する前にBGMを一時停止させる
			stopSound();
			stopVideo();
			// 動画の再生
			showVideoView(mContentDir + "/" + actionInfoJSON.getVideoFileName(), pageNumber, actionInfoJSON.getObjectId(), objectLogId);
			break;
		case ActionInfoJSON.MUSIC_ACTION:
			playTapSound(mContentDir + "/" + actionInfoJSON.getMusicFileName(), pageObject);
			break;
		case ActionInfoJSON.LINKURL_ACTION:
			showWebView(actionInfoJSON.getLinkUrl(),actionInfoJSON.getBrowserType(), pageNumber, actionInfoJSON.getObjectId(), objectLogId);
			break;
		case ActionInfoJSON.PREVIEW_ACTION:
			showPreview(actionInfoJSON.getPreviewImages(), actionInfoJSON.getObjectId(), objectLogId);
			break;
		case ActionInfoJSON.JUMPPAGE_ACTION:
			Logger.d(TAG, "JUMPPAGE_ACTION:" + actionInfoJSON.getJumpPage());
			jumpToPage(actionInfoJSON.getJumpPage() - 1);   //CHG 2012/04/02 tanigawa
			break;
		case ActionInfoJSON.EMAIL_ACTION:
			sendEmail(actionInfoJSON.getEmailSubject(), actionInfoJSON.getEmailAddress());
			break;
		case ActionInfoJSON.TRIGGER_ACTION:
			break;
		case ActionInfoJSON.BALLOON_ACTION:
			showBalloon(actionInfoJSON.getContentHTML(), pageNumber, actionInfoJSON.getObjectId());
			break;
		case ActionInfoJSON.MEMO_ACTION:
			break;
		case ActionInfoJSON.HTML_ACTION:
			preViewFlg = true;
			String htmlFilePath = contentLogic.getHtmleFilePath(getContentId(), actionInfoJSON.getHtml(), true);
			ActivityHandlingHelper.getInstance().startHTMLWebActivity(this, null, htmlFilePath, getContentId(), WEBVIEW, pageNumber, actionInfoJSON.getObjectId(), objectLogId, readingLogId);
			break;
		case ActionInfoJSON.CONTENTLINK_ACTION:
			//コンテンツリンクに紐づいたAction Buttonのイベント
			long linkContentId = actionInfoJSON.getContentId();

			//　プロジェクト関連資料なのかをチェック
			if (ActivityHandlingHelper.getInstance().isExistCommonContent(getContentId())) {
				if (!ActivityHandlingHelper.getInstance().isExistCommonContent(linkContentId)) {
					// リソースパターンの適用
					ABVToastUtil.showMakeText(getApplicationContext(), PatternStringUtil.patternToString(getApplicationContext(),
																		R.string.msg_not_common_content,
																		getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)), Toast.LENGTH_SHORT);
					break;
				}
			} else if (ActivityHandlingHelper.getInstance().isExistRelatedContent(getContentId(), mOperationId)) {
				if (!ActivityHandlingHelper.getInstance().isExistRelatedContent(linkContentId, mOperationId)) {
					// リソースパターンの適用
					ABVToastUtil.showMakeText(getApplicationContext(), PatternStringUtil.patternToString(getApplicationContext(),
																		R.string.msg_not_related_content,
																		getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)), Toast.LENGTH_SHORT);
					break;
				}
			}
			try {
				if (ActivityHandlingHelper.getInstance().checkContent(linkContentId, (int) actionInfoJSON.getPageNo())) { // コンテンツをチェックし、なければDL後開く
					getABVUIDataCache().setReturnContentIdList(linkContentId, (int) actionInfoJSON.getPageNo());
					if (isLinkedContent) {
						ActivityHandlingHelper.getInstance().startContentActivityForLinkedConent(mOperationId, linkContentId, (int) actionInfoJSON.getPageNo());
					} else {
						ActivityHandlingHelper.getInstance().startContentActivity(linkContentId, pageNumber);
					}
				}
			} catch (Exception e) {
				Logger.e(TAG, "startContentActivity failed.", e);
				ErrorMessage.showErrorMessageToast(getApplicationContext(), ErrorCode.E107);
			}
			break;

		//ym.chae
		case ActionInfoJSON.ENQUETE_ACTION:
		case ActionInfoJSON.QUIZ_ACTION:
		case ActionInfoJSON.EXAM_ACTION:
			if (isEnquete) {
				break; //설문 조사 중이면 앙케이트를 눌러도 반응하지 않음.
			}

			//앙케이트
			if (actionInfoJSON.getEnquete().equals("")) {
				break;
			}

			long abObjectId = actionInfoJSON.getObjectId();
			long abEnqueteId = actionInfoJSON.getEnqueteId();
			boolean replyFlg = false;

			if (actionInfoJSON.getReplyLimit()==1) {
				try{
					EnqueteLogic es = AbstractLogic.getLogic(EnqueteLogic.class);
					//replyLimit 무제한 = 0 ,  1회 = 1
					if (es.getLimitEnquete(getContentId(), abObjectId)) {
						replyFlg=true;
					}
					if (actionInfoJSON.getSaveAs()==1) {
						//saveAs 공통화 안함 : 0, 공통화 함 : 1
						//공통화 된 설문이 이미 참여되었는지 DB에서 확인해봐야 함.
						if (es.getCheckEnqueteId(getContentId(), abEnqueteId)) {
							replyFlg=true;
						}
					}
					if (replyFlg) {
						//回答済みの場合：アラートを出すのでタイトルと内容はアンケート、試験、クイズによって変えるため
						String enquete_strType = null;
						String enquete_strType_over = null;
						switch (actionInfoJSON.getActionType()) {
						case ActionInfoJSON.ENQUETE_ACTION:
							enquete_strType = getRString(R.string.enquete);
							enquete_strType_over = getRString(R.string.enquete_over);
							break;
						case ActionInfoJSON.EXAM_ACTION:
							enquete_strType = getRString(R.string.exam);
							enquete_strType_over = getRString(R.string.exam_over);
							break;
						case ActionInfoJSON.QUIZ_ACTION:
							enquete_strType = getRString(R.string.quiz);
							enquete_strType_over = getRString(R.string.quiz_over);
							break;
						default:
							break;
						}
						
						ABookAlertDialog messageDialog = AlertDialogUtil.createAlertDialog(this, enquete_strType);
						messageDialog.setMessage(enquete_strType_over);
						messageDialog.setNegativeButton(R.string.confirm,null);
						messageDialog.show();
						break;
					}
				}catch(Exception e) {
					Logger.e("Enquete service fail", e);
					ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
				}
			}


			//공통화 된 설문에 대한 처리
			if (actionInfoJSON.getSaveAs() == 1 && enqueteMap.containsKey(actionInfoJSON.getEnqueteId())) {
				//공통화 일때 툴바 제거효과
				setToolbarVisable(false);
				isEnqueteOpening = true;
				enqueteLayout = enqueteMap.get(actionInfoJSON.getEnqueteId());
				mMainLayout.addView(enqueteLayout);
				isEnquete = true;
			}
			else{
				try {
					showEnqueteLayout(null, actionInfoJSON);
				} catch (JSONException e) {
					Logger.e("showEnqueteLayout failed. pageNumber=" + pageNumber, e);
					handleErrorMessageToast(String.format(getString(R.string.C_E_CONTENT_2001), pageNumber));
				} catch (Exception e) {
					Logger.e("showEnqueteLayout failed.", e);
					handleErrorMessageToast(R.string.ERROR);
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 画面が表示されてから呼ぶ
	 *
	 * TODO: moveToとロジック重複
	 *
	 * @param jumpPage
	 */
	public void jumpToPage(final int jumpPage) {
		stopVideo();
        // ページ別ログ
		ContentLogUtil.getInstance().contentPageMove(contentId, readingLogId, mCurrentPageNumber, jumpPage);

		Logger.i(TAG, "[jumpToPage]:start=" + jumpPage + ", childCount=" + mContentWrapLayout.getChildCount());
		if (jumpPage == mCurrentPageNumber || touchFlg) {
			return;
		}
		touchFlg =true;

		if (mPdfImageProvider != null) {
			mPdfImageProvider.cancelAll(true);
			mPdfImageProvider.createImage(contentId, jumpPage, mDisplaySize);
		}

		addOrRemovePages(jumpPage);

		mPageScrollView.setZoomingFlag(false);
		mPageScrollView.post(new Runnable() {
			@Override
			public void run() {
	        	mPageScrollView.smoothScrollTo(mCurrentPageNumber*mDisplaySize.width, 0);
				touchFlg = false;
			}
		});

		if (mToolBar.getVisibility() == View.VISIBLE && mSeekBarLayout != null && mSeekBarLayout.getVisibility() == View.VISIBLE) {
			//ツールバーが可視の時は内容更新
			setToolbarVisable(true);
		}
		// BGM
		if (contentsBgmFlg && !StringUtil.isNullOrEmpty(contentsBgmFilePath) && !contentBGMPlayer.isPlaying()) {
			//contentsBgmFilePath
			contentBGMPlayer = new ABVMediaPlayer(true);
			try {
				Logger.v(TAG, "[addMusic]:MediaPlayer Content BGM");
				contentBGMPlayer.setDataSource(contentsBgmFilePath);
				contentBGMPlayer.prepare();
				contentBGMPlayer.start();
			} catch (IOException e) {
				Logger.e(TAG, "Can't play content BGM", e);
				ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
			}
		}
		playPageBGMSound(jumpPage);

		//탭사운드 플레이 Bug
		playTapSoundFlg = false;

		setCurrentPageNumber();

        if (meetingManager.isSendable()) { // TODO later 止まったタイミングで送るように要修正
        	meetingManager.sendWs(MeetingManager.CMD_MOVEPAGE, getContentId(), jumpPage, null, null);
        }
	}

	private void addOrRemovePages(final int jumpPage) {
		final int currentPage = mCurrentPageNumber;
		mCurrentPageNumber = jumpPage;

		if (Math.abs(jumpPage - currentPage) != 1) {
			addPageView(jumpPage);
		}
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() { // ジャンプするページに応じて必要なだけ作成・削除する
				if (jumpPage - currentPage != 1 && jumpPage - currentPage != 2) {
					addPageView(jumpPage - 1);
					removePage(currentPage + 1);
				}
				if (jumpPage - currentPage != -1 && jumpPage - currentPage != -2) {
					addPageView(jumpPage + 1);
					removePage(currentPage - 1);
				}
				if (Math.abs(jumpPage - currentPage) != 1) {
					removePage(currentPage);
				}
			}
		}, 500); // あまり早くしすぎると描画前に走って描画が遅れる。
	}

	/**
	 * 強制ページジャンプ
	 * @param jumpPage
	 */
	public void forceJumpToPage(int jumpPage) {
		Logger.i(TAG, "[forcejumpToPage]:start=" + jumpPage + ", childCount=" + mContentWrapLayout.getChildCount());

		// ページ別ログ
		ContentLogUtil.getInstance().contentPageMove(contentId, readingLogId, mCurrentPageNumber, jumpPage);

		addOrRemovePages(jumpPage);
		mPageScrollView.setZoomingFlag(false);
		mPageScrollView.post(new Runnable() {
			@Override
			public void run() {
	        	mPageScrollView.smoothScrollTo(mCurrentPageNumber*mDisplaySize.width, 0);
			}
		});

        if (meetingManager.isSendable()) { // TODO later 止まったタイミングで送るように要修正
        	meetingManager.sendWs(MeetingManager.CMD_MOVEPAGE, getContentId(), jumpPage, null, null);
        }
	}

	/**
	 * イメージ差し替え用
	 * @param contentPageView
	 * @param pageObject
     */
	private void addChangeImage(ZoomRelativeLayout contentPageView, final PageObjectJSON pageObject) {
		LocationJSON location = pageObject.getLocation();
		int x = contentPageView.getResizedForDisplayScale(location.getX()) + contentPageView.getContentPageMargin().left;
		int y = contentPageView.getResizedForDisplayScale(location.getY()) + contentPageView.getContentPageMargin().top;
		int w = contentPageView.getResizedForDisplayScale(location.getWidth());
		int h = contentPageView.getResizedForDisplayScale(location.getHeight());

		final MediaInfoJSON mediaInfo = pageObject.getMediaInfo();
		List<String> mediaFileList = mediaInfo.getMediaFileNames();
		if (mediaFileList.isEmpty()) {
			return;
		}

		boolean isImageAspectType = mediaInfo.getAspectType() == 1;

    	if (mediaInfo.getTriggerType() == 1) {
    		//イメージタップの場合  イメージ表示領域の追加
        	String[] filelist = new String[mediaFileList.size()];
        	long[] resourceIds = mediaInfo.getMediaResourceIds();
        	for (int i = 0; i < filelist.length; i++) {
        		filelist[i] = mContentDir + "/" + mediaFileList.get(i);
        	}

        	final int pageNumber = pageObject.getPageNumber();
        	int pageidx = getPageContentArrayIndex(pageNumber);
        	mPageActionList.get(pageidx).arrayChangeImageTap.add(new ImageChangeAction());
        	final int index = mPageActionList.get(pageidx).arrayChangeImageTap.size() - 1;

        	final long pageObjectId = pageObject.getActionInfo().getObjectId();
        	mPageActionList.get(pageidx).arrayChangeImageTap.get(index).addImageChangeTap(getApplicationContext(), x, y, w, h, 1.0f, filelist, resourceIds, contentPageView, index, pageNumber, isImageAspectType);
        	objectIdButtonMap.put(pageObjectId, mPageActionList.get(pageidx).arrayChangeImageTap.get(index).mViewFlipper);
        	mPageActionList.get(pageidx).arrayChangeImageTap.get(index).mViewFlipper.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (((ZoomRelativeLayout)v.getParent()).isZooming() == false) {
						int pageidx = getPageContentArrayIndex(mCurrentPageNumber);
						//ym.chae
						if (mPageActionList.get(pageidx).arrayChangeImageTap.size()!=0) {
							// 差し替え画像(タップ)は複数リソースIDがあるので次に表示するリソースIDを使用
							long resourceId = mPageActionList.get(pageidx).arrayChangeImageTap.get(index).goNext(getApplicationContext());
					        if (meetingManager.isSendable()) {
								JSONObject json = new JSONObject();
								json.put(MeetingManager.TIME_STAMP, System.currentTimeMillis());
								meetingManager.sendWs(MeetingManager.CMD_ACTION, getContentId(), pageNumber, pageObjectId, json);
					        }
							// オブジェクトログ
							ContentLogUtil.getInstance().insertContentObjectLog(contentId, readingLogId, pageObject, resourceId);
						}
    				}
				}
    		});
    	} else {
    		//イメージボタンの場合  イメージ表示領域の追加
    		String imagefile = mContentDir + "/" + mediaFileList.get(0);
    		ImageChangeAction icba = new ImageChangeAction();
    		// イメージのアスペクト比を優先するかどうかのフラグ
    		ActionImageView changeImageView = icba.addImageChangeView(getApplicationContext(), x, y, w, h, 1.0f, imagefile, contentPageView, isImageAspectType);
    		changeImageView.setID(mediaInfo.getTargetId());
    		changeImageView.setFileNames(mediaFileList);
    	}
	}

	/**
	 * 動画差し替え用
	 * @param contentPageView RelativeLayout
	 * @param pageObject PageObjectJSON
	 */
	private void addChangeVideo(ZoomRelativeLayout contentPageView, final PageObjectJSON pageObject) {
		LocationJSON location = pageObject.getLocation();
		int x = contentPageView.getResizedForDisplayScale(location.getX()) + contentPageView.getContentPageMargin().left;
		int y = contentPageView.getResizedForDisplayScale(location.getY()) + contentPageView.getContentPageMargin().top;
		int w = contentPageView.getResizedForDisplayScale(location.getWidth());
		int h = contentPageView.getResizedForDisplayScale(location.getHeight());

		VideoMountAction videoChangeAction = new VideoMountAction(this, getContentId(), pageObject, contentPageView, readingLogId);
		videoChangeAction.setChangeVideo(true);
    	videoChangeAction.configureVideoView(x, y, w, h, 1.0f, null);
    	int pageidx = getPageContentArrayIndex(pageObject.getPageNumber());
    	videoChangeAction.setIndex(mPageActionList.get(pageidx).arrayVideoChange.size());
    	videoChangeAction.setID(pageObject.getMediaInfo().getTargetId());
    	videoChangeAction.setFileNames(pageObject.getMediaInfo().getMediaFileNames());
    	videoChangeAction.addVideoIcon(1.0f, "22");
		videoChangeAction.setActionListener(new VideoMountAction.VideoMountActionListener() {
			@Override
			public void changeStatus(int index, String videofile, int status) {
				isVideoMax = (status == VideoMountAction.VIDEO_MAX);
				mPageScrollView.setVideoMaxFlag(isVideoMax);
				if (isVideoMax) {
					stopCurrentPageMountVideo(null, true);  //他の動画を非表示
					stopCurrentPageChangeVideo(index, true);
					setToolbarVisable(false);
				}
				else {
					setSurfaceViewVisible(false, index);     //他の動画を表示
				}
			}
		});
		videoChangeAction.setSeekBarListener(new VideoMountAction.SeekBarTouchListener() {
			@Override
			public void onStartTrackingTouch() {
				mPageScrollView.setFixFlag(true);
			}
			@Override
			public void onStopTrackingTouch() {
				mPageScrollView.setFixFlag(false);
			}
		});

    	mPageActionList.get(pageidx).arrayVideoChange.add(videoChangeAction);
	}

	/**
	 * トリガー用
	 * @param contentPageView RelativeLayout
	 * @param pageObject PageObjectJSON
	 */
	private void addTigger(final ZoomRelativeLayout contentPageView, final PageObjectJSON pageObject) {
		Logger.v(TAG, "[addTigger]");
		final LocationJSON location = pageObject.getLocation();
		int x = contentPageView.getResizedForDisplayScale(location.getX()) + contentPageView.getContentPageMargin().left;
		int y = contentPageView.getResizedForDisplayScale(location.getY()) + contentPageView.getContentPageMargin().top;
		int w = contentPageView.getResizedForDisplayScale(location.getWidth());
		int h = contentPageView.getResizedForDisplayScale(location.getHeight());
		String imagefile = mContentDir + "/" + pageObject.getMediaInfo().getFileName();
		RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(w, h);   //W,H 横幅、高さ
    	param.setMargins(x, y, 0, 0);                    //X,Y 外側の余白

    	ActionButton imgButton = new ActionButton(getApplicationContext());
		final long pageObjectId = pageObject.getActionInfo().getObjectId();
		final int pageNumber = pageObject.getPageNumber();
		objectIdButtonMap.put(pageObjectId, imgButton);
    	imgButton.setPadding(0, 0, 0, 0);               //内側の余白
//    	imgButton.setAdjustViewBounds(true);            //描画の縦横比を維持
//    	imgButton.setScaleType(ScaleType.FIT_XY);       //エリア全体に画像を拡大して表示
    	BitmapDrawable bitmapDrawable = null;
    	try{
    		bitmapDrawable = new BitmapDrawable(getResources(), BitmapUtil.getResizedBitmap(imagefile, w, h, Config.RGB_565, false));
    	} catch(OutOfMemoryError e) {
    		Logger.e(TAG, "[OutOfMemoryError]", e);
			ABVToastUtil.showMakeText(getApplicationContext(), R.string.OUT_OF_MEMORY, Toast.LENGTH_SHORT);
    	}
    	imgButton.setBackgroundDrawable(bitmapDrawable);          //半透明表示
    	contentPageView.addView(imgButton, param);

		// Target抽出（TargetIDを基に差し替えイメージをチェック）
		final ActionInfoJSON actionInfo = pageObject.getActionInfo();
		for (int i = 0; i < contentPageView.getChildCount(); i++) {
			View view = contentPageView.getChildAt(i);
			if (!(view instanceof ActionImageView)) {
				continue;
			}
			final ActionImageView actionImageView = (ActionImageView)view;
			if (actionImageView.getID() == actionInfo.getTargetId()) {
				// 差し替えイメージボタンの追加
				final String viewImageFile_ = mContentDir + "/" + actionImageView.getFileName(actionInfo.getTargetIndex());
				imgButton.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						//20120803
						if (getTouchScrollPosition()) {
							if (meetingManager.isSendable()) {
								meetingManager.sendWs(MeetingManager.CMD_ACTION, getContentId(), pageNumber, pageObjectId, null);
							}
							// オブジェクトログ
							ContentLogUtil.getInstance().insertContentObjectLog(contentId, readingLogId, pageObject);
							//actionImageView.get
							Bitmap resized = BitmapUtil.getResizedBitmap(viewImageFile_, actionImageView.getWidth(), actionImageView.getHeight(), Config.RGB_565);//イメージサイズをリサイズする
							actionImageView.setImageBitmap(resized);
							//actionImageView.setImageURI(Uri.parse(viewImageFile_));
							contentPageView.invalidate();
						}
					}
				});
				return;
			}
    	}
		// Target抽出（TargetIDを基に差し替え動画をチェック）
		final int pageidx = getPageContentArrayIndex(pageNumber);
		Logger.d(TAG, "getPageContentArrayIndex(pageObject.getPageNumber()) : " + getPageContentArrayIndex(pageNumber));
		if (mPageActionList.get(pageidx).arrayVideoChange != null) {
			for (int i = 0; i < mPageActionList.get(pageidx).arrayVideoChange.size(); i++) {
				final VideoMountAction videoChangeButtonAction = mPageActionList.get(pageidx).arrayVideoChange.get(i);
				if (actionInfo.getTargetId() == videoChangeButtonAction.getID()) {
					// 差し替え動画ボタンの追加
					final int targetIndex = actionInfo.getTargetIndex();
					imgButton.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View view) {
							if (meetingManager.isSendable()) {
								meetingManager.sendWs(MeetingManager.CMD_ACTION, getContentId(), pageNumber, pageObjectId, null);
							}
							// 差し替え動画はMovieResourceIdを使用
							MediaInfoJSON mediaInfoJSON = pageObject.getMediaInfo();
							long resourceId = mediaInfoJSON.getMovieResourceId();
							// オブジェクトログ
							int objectLogId = ContentLogUtil.getInstance().insertContentObjectLog(contentId, readingLogId, pageObject, resourceId);
							String viewVideoFile_ = mContentDir + "/" + videoChangeButtonAction.getFileName(targetIndex);
			            	Logger.d(TAG, "[AddImageChangeButton]:filePath_=" + viewVideoFile_);
			            	videoChangeButtonAction.start(viewVideoFile_, 0, objectLogId);
			            }
			        });
	            	objectIdPopupMap.put(pageObjectId, videoChangeButtonAction); // popupではないがこれ以上Mapを増やしたくないのでここに格納　
					return;
				}
	    	}
		}
	}

	/**
	 * 動画再生用
	 * @param contentPageView RelativeLayout
	 * @param pageObject PageObjectJSON
	 */
	private void addVideo(ZoomRelativeLayout contentPageView, final PageObjectJSON pageObject) {
		//動画表示領域の追加
		LocationJSON location = pageObject.getLocation();
		ViewMargin margin = contentPageView.getContentPageMargin();
		int x = contentPageView.getResizedForDisplayScale(location.getX()) + margin.left;
		int y = contentPageView.getResizedForDisplayScale(location.getY()) + margin.top;
		int w = contentPageView.getResizedForDisplayScale(location.getWidth());
		int h = contentPageView.getResizedForDisplayScale(location.getHeight());

		final int pageidx = getPageContentArrayIndex(pageObject.getPageNumber());
		float iconScale = (float)pageObject.getMediaInfo().getIconInfo().getScale() / 100;
		String iconPosition = pageObject.getMediaInfo().getIconInfo().getPosition();
		Logger.d(TAG, "pageObject.getActionInfo().getEmbedType() : " + pageObject.getActionInfo().getEmbedType());

		if (pageObject.getActionInfo().getEmbedType() == 1) {
			// 埋め込み動画の場合
			String videofile = mContentDir + "/" + pageObject.getActionInfo().getVideoFileName();
			VideoMountAction videoMountAction = new VideoMountAction(ContentViewActivity.this, getContentId(), pageObject, contentPageView, readingLogId);
	    	videoMountAction.setIndex(mPageActionList.get(pageidx).arrayVideoMount.size());
	    	videoMountAction.configureVideoView(x, y, w, h, 1.0f, videofile); // 内部でActivityをContextに変換
	    	videoMountAction.addVideoIcon(iconScale, iconPosition);
			videoMountAction.setActionListener(new VideoMountAction.VideoMountActionListener() {
				@Override
				public void changeStatus(int index, String videofile, int status) {
					Logger.d(TAG, "changeStatus " + status);
					isVideoMax = (status == VideoMountAction.VIDEO_MAX);
					mPageScrollView.setVideoMaxFlag(isVideoMax);
					if (isVideoMax) {
						stopCurrentPageMountVideo(index, true);  //他の動画を非表示
						stopCurrentPageChangeVideo(null, true);
						setToolbarVisable(false);
					}
					else {
						setSurfaceViewVisible(true, index);     //他の動画を表示
					}
				}
			});
			videoMountAction.setSeekBarListener(new VideoMountAction.SeekBarTouchListener() {
				@Override
				public void onStartTrackingTouch() {
					mPageScrollView.setFixFlag(true);
				}
				@Override
				public void onStopTrackingTouch() {
					mPageScrollView.setFixFlag(false);
				}
			});

	    	mPageActionList.get(pageidx).arrayVideoMount.add(videoMountAction);

		} else { // 全画面動画
			// クリック可能エリア（TODO: later あとでサムネイルを入れる）
			RelativeLayout clickableArea = new RelativeLayout(this);
			//noinspection deprecation(API16から非推奨になった。無視)
	      	clickableArea.setBackgroundDrawable(getRDrawable(R.drawable.border));   //枠線表示
	      	clickableArea.setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View view) {
	            	videoOnClick(pageObject, pageidx);
	            }
	        });
			objectIdButtonMap.put(pageObject.getActionInfo().getObjectId(), clickableArea);

	    	RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(w, h);
	    	param1.setMargins(x, y, 0, 0);
	      	contentPageView.addView(clickableArea , param1);

			// 再生アイコン
			int videoIconSize = 196;
			int scaleIcon = (int) (videoIconSize * iconScale) ;
			Bitmap bg = BitmapUtil.getResizedBitmapResource(getResources(), R.drawable.play, scaleIcon, scaleIcon, Bitmap.Config.RGB_565, false);

			ImageButton playIcon = new ImageButton(ContentViewActivity.this);
			playIcon.setBackgroundColor(0);
			playIcon.setImageDrawable(new BitmapDrawable(getResources(), bg));
			playIcon.setScaleType(ScaleType.MATRIX);
			playIcon.setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View view) {
	            	videoOnClick(pageObject, pageidx);
	            }
			});

			RelativeLayout.LayoutParams param = createIconPosition(Integer.parseInt(iconPosition));
	        clickableArea.addView(playIcon, param);
		}
	}

	private void videoOnClick(PageObjectJSON pageObject, int pageidx) {
		if (mPageScrollView.isZooming() == false) {
			//リモート機能
		    if (meetingManager.isSendable()) {
		    	meetingManager.sendWs(MeetingManager.CMD_ACTION, getContentId(), pageObject.getPageNumber(), pageObject.getActionInfo().getObjectId(), null);
		    }
		    // オブジェクトログ
		    int objectLogId = ContentLogUtil.getInstance().insertContentObjectLog(contentId, readingLogId, pageObject);
			// 動画を再生する前にBGMを一時停止させる
			stopSound();
			stopVideo();
			// 動画の再生
			try {
				String videofile_ = mContentDir + "/" + pageObject.getActionInfo().getVideoFileName();
				showVideoView(videofile_, pageObject.getPageNumber(), pageObject.getActionInfo().getObjectId(), objectLogId);
			} catch (JSONException e) {
				Logger.e(TAG, "videoOnClick error. pageNumber=" + pageObject.getPageNumber(), e); // ※ここでgetPageNumberではJSONExceptionは発生し得ない。
				handleErrorMessageToast(String.format(getString(R.string.C_E_CONTENT_2001), pageObject.getPageNumber()));
			}
		}
	}


	/**
	 * 3D用
	 * @param contentPageView RelativeLayout
	 * @param pageObject PageObjectJSON
	 */
	private void addView3D(ZoomRelativeLayout contentPageView, PageObjectJSON pageObject) {
		LocationJSON location = pageObject.getLocation();
		ViewMargin margin = contentPageView.getContentPageMargin();
		int x = contentPageView.getResizedForDisplayScale(location.getX()) + margin.left;
		int y = contentPageView.getResizedForDisplayScale(location.getY()) + margin.top;
		int w = contentPageView.getResizedForDisplayScale(location.getWidth());
		int h = contentPageView.getResizedForDisplayScale(location.getHeight());

		ImageView img3dIcon = new ImageView(this);
		img3dIcon.setImageResource(R.drawable.icon_3d);

        final int pageidx = getPageContentArrayIndex(pageObject.getPageNumber());
    	final int index = mPageActionList.get(pageidx).array3DImage.size();
    	mPageActionList.get(pageidx).array3DImage.add(new Action3DImageView(this, w, h, img3dIcon, index, getContentId(), readingLogId, pageObject, mContentDir));

        RelativeLayout.LayoutParams paramImg3d = new RelativeLayout.LayoutParams(w, h);
        paramImg3d.setMargins(x, y, 0, 0);
        contentPageView.addView(mPageActionList.get(pageidx).array3DImage.get(index), paramImg3d);

        int wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT;
        RelativeLayout.LayoutParams paramImg3dIcon = new RelativeLayout.LayoutParams(wrapContent, wrapContent);
        paramImg3dIcon.setMargins(x + w - 43, y + h - 46, 0, 0);
        contentPageView.addView(img3dIcon, paramImg3dIcon);
	}

	private void addMarkingView(ZoomRelativeLayout zoomLayout, int pageNumber) {
		MarkingView markingView = new MarkingView(this, getContentId(), pageNumber);
		// Android6でMATCH_PARENTをしてもViewが広がらないので直接サイズを指定するやり方に変更
//		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(FP, FP);
		ViewMargin margin = zoomLayout.getContentPageMargin();
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mDisplaySize.width - margin.left - margin.right, mDisplaySize.height - margin.top - margin.bottom);
		params.setMargins(margin.left, margin.top, margin.right, margin.bottom);
		zoomLayout.addView(markingView, params);
		mMarkingViewList.add(markingView);

		// トグルボタンの状態に合わせて表示・非表示
		if (!tbtnMarking.isChecked()) {
			markingView.setVisibility(View.GONE);
		}
	}

	/**
	 * 再生中の動画を全停止する。
	 *
	 */
	public void stopVideo() {
		for (int i = 0; i < mPageActionList.size(); i++) {
			stopMountVideo(mPageActionList.get(i).arrayVideoMount, null, false);
			stopChangeVideo(mPageActionList.get(i).arrayVideoChange, null, false);
		}
	}

	/**
	 * 埋め込み動画を停止する
	 *
	 * @param invisibleSurfaceView surfaceViewを非表示にするか
	 * @param excludeIndex　停止しない動画index（nullを指定すればすべて）
	 */
	public void stopCurrentPageMountVideo(Integer excludeIndex, boolean invisibleSurfaceView) {
		int pageidx = getPageContentArrayIndex(mCurrentPageNumber);
		stopMountVideo(mPageActionList.get(pageidx).arrayVideoMount, excludeIndex, invisibleSurfaceView);
	}

	private void stopMountVideo(ArrayList<VideoMountAction> arrayVideoMount, Integer excludeIndex, boolean invisibleSurfaceView) {
		for (int i = 0; i < arrayVideoMount.size(); i++) {
			if (excludeIndex == null || i != excludeIndex) {
				arrayVideoMount.get(i).stopVideo();
				if (invisibleSurfaceView) {
					arrayVideoMount.get(i).setSurfaceVisibility(View.INVISIBLE);
				}
			}
		}
	}

	/**
	 * 差替え動画を停止する
	 *
	 * @param excludeIndex　停止しない動画index（nullを指定すればすべて）
	 * @param invisibleSurfaceView surfaceViewを非表示にするか
	 */
	public void stopCurrentPageChangeVideo(Integer excludeIndex, boolean invisibleSurfaceView) {
		int pageidx = getPageContentArrayIndex(mCurrentPageNumber);
		stopChangeVideo(mPageActionList.get(pageidx).arrayVideoChange, excludeIndex, invisibleSurfaceView);
	}

	private void stopChangeVideo(ArrayList<VideoMountAction> arrayVideoChange, Integer excludeIndex, boolean invisibleSurfaceView) {
		for (int i = 0; i < arrayVideoChange.size(); i++) {
			if (excludeIndex == null || i != excludeIndex) {
				arrayVideoChange.get(i).stopVideo();
				if (invisibleSurfaceView) {
					arrayVideoChange.get(i).setSurfaceVisibility(View.INVISIBLE);
				}
			}
		}
	}

	/**
	 * 自分以外のSurfaceViewをすべてVISIBLEにする。
	 *
	 * @param isMountVideo
	 * @param index
	 */
	public void setSurfaceViewVisible(boolean isMountVideo, int index) {
		int pageidx = getPageContentArrayIndex(mCurrentPageNumber);
		for (int i = 0; i < mPageActionList.size(); i++) {
			for (int j = 0; j < mPageActionList.get(i).arrayVideoMount.size(); j++) {
				if (i != pageidx || j != index || !isMountVideo) {
					mPageActionList.get(i).arrayVideoMount.get(j).setSurfaceVisibility(View.VISIBLE);
				}
			}
			for (int j = 0; j < mPageActionList.get(i).arrayVideoChange.size(); j++) {
				if (i != pageidx || j != index || isMountVideo) {
					mPageActionList.get(i).arrayVideoChange.get(j).setSurfaceVisibility(View.VISIBLE);
				}
			}
		}
	}

	/**
	 * リッチテキスト用
	 * @param contentPageView RelativeLayout
	 * @param pageObject PageObjectJSON
	 */
	private void addRichText(ZoomRelativeLayout contentPageView, PageObjectJSON pageObject) {
		//リッチテキスト表示領域の追加
		LocationJSON location = pageObject.getLocation();
		ViewMargin margin = contentPageView.getContentPageMargin();
		int x = contentPageView.getResizedForDisplayScale(location.getX()) + margin.left;
		int y = contentPageView.getResizedForDisplayScale(location.getY()) + margin.top;
		int w = contentPageView.getResizedForDisplayScale(location.getWidth());
		int h = contentPageView.getResizedForDisplayScale(location.getHeight());

		String html = pageObject.getMediaInfo().getContentHTML();

		RichTextHtmlAction rtha = new RichTextHtmlAction();
		rtha.addRichTextHtml(getApplicationContext(), x, y, w, h, contentPageView.getAuthoringScale(), html, contentPageView);
	}

	/**
	 * オーディオ再生用
	 * @param contentPageView RelativeLayout
	 * @param pageObject PageObjectJSON
	 */
	private void addMusic(ZoomRelativeLayout contentPageView, final PageObjectJSON pageObject) {
		ActionInfoJSON infoJSON = pageObject.getActionInfo();
		ViewMargin margin = contentPageView.getContentPageMargin();
		if (infoJSON.getPlayType() == 0) {
			Logger.v(TAG, "[addMusic]:MediaPlayer Tap Sound");
			ActionButton imgBtn = makeActionButton(pageObject, margin, false, contentPageView);
			contentPageView.addView(imgBtn);
			final String soundFilePath = mContentDir + "/" + pageObject.getMediaInfo().getFileName();

			LocationJSON location = pageObject.getLocation();
			int x = contentPageView.getResizedForDisplayScale(location.getX()) + contentPageView.getContentPageMargin().left;
			int y = contentPageView.getResizedForDisplayScale(location.getY()) + contentPageView.getContentPageMargin().top;
			int w = contentPageView.getResizedForDisplayScale(location.getWidth());
			int h = contentPageView.getResizedForDisplayScale(location.getHeight());

			// クリック可能エリア
			RelativeLayout clickableArea = new RelativeLayout(this);
//	      	clickableArea.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));   //枠線表示(確認用)
	      	clickableArea.setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View view) {
					if (meetingManager.isSendable()) {
			        	meetingManager.sendWs(MeetingManager.CMD_ACTION, contentId, pageObject.getPageNumber(), pageObject.getActionInfo().getObjectId(), null);
			        }
					playTapSound(soundFilePath, pageObject);
	            }
	        });
			objectIdButtonMap.put(pageObject.getActionInfo().getObjectId(), clickableArea);

	    	RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(w, h);
	    	param1.setMargins(x, y, 0, 0);
	      	contentPageView.addView(clickableArea , param1);

			// 再生アイコン
			int musicIconSize = 128;
			float iconScale  = (float)pageObject.getMediaInfo().getIconInfo().getScale() / 100;
			int scaleIcon = (int) (musicIconSize * iconScale) ;
			ImageButton playIcon = new ImageButton(ContentViewActivity.this);
			if(scaleIcon > 0){
				Bitmap bg = BitmapUtil.getResizedBitmapResource(getResources(), R.drawable.musicplay, scaleIcon, scaleIcon, Bitmap.Config.RGB_565);
				playIcon.setImageDrawable(new BitmapDrawable(getResources(), bg));
			}
			playIcon.setBackgroundColor(getRColor(AppColor.getTransparent()));// 背景を透明にする
			playIcon.setScaleType(ScaleType.MATRIX);
			playIcon.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					if (meetingManager.isSendable()) {
						meetingManager.sendWs(MeetingManager.CMD_ACTION, contentId, pageObject.getPageNumber(), pageObject.getActionInfo().getObjectId(), null);
					}
					playTapSound(soundFilePath, pageObject);
				}
			});

			int iconPosition = Integer.parseInt(pageObject.getMediaInfo().getIconInfo().getPosition());
			RelativeLayout.LayoutParams param = createIconPosition(iconPosition);
	        clickableArea.addView(playIcon, param);
		} else {
			final String soundFilePath = mContentDir + "/" + pageObject.getActionInfo().getMusicFileName();
			if (infoJSON.getPlayType() == 1) { // Content BGM
				//noinspection VariableNotUsedInsideIf
				if (contentBGMPlayer != null) {
					return;
				}
				contentBGMPlayer = new ABVMediaPlayer(true);
				try {
					Logger.v(TAG, "[addMusic]:MediaPlayer Content BGM");
					contentBGMPlayer.setDataSource(soundFilePath);
					contentBGMPlayer.prepare();
					contentBGMPlayer.start();
				} catch (IOException e) {
					Logger.e(TAG, "Can't play content BGM", e);
					ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
				}
			} else {
				// Page BGM
				Logger.v(TAG, "[addMusic]:pageBGMPathList add page %s", pageObject.getPageNumber());
				pageBGMPathList.put(pageObject.getPageNumber(), soundFilePath);
			}
		}
	}

	public RelativeLayout.LayoutParams createIconPosition(int iconPosition) {
		RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(WC, WC);
		switch (iconPosition % 10) { // アイコンの位置によってX位置を設定
		case 1:
			param.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		    break;
		case 2:
			param.addRule(RelativeLayout.CENTER_HORIZONTAL);
		    break;
		case 3:
			param.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			break;
		}

		switch (iconPosition / 10) { // アイコンの位置によってY位置を設定
		case 1:
			param.addRule(RelativeLayout.ALIGN_PARENT_TOP);
			break;
		case 2:
			param.addRule(RelativeLayout.CENTER_VERTICAL);
			break;
		case 3:
			param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
			break;
		}
		return param;
	}

	//북마크 또는 콘텐츠 링크로 페이지 이동시 1페이지의 ContentBGM 체크
	//페이지 BGM이 존재시 페이지 BGM을 재생하도록 수정
	private void moveCheckContentBGM() {

		JSONArray pageBGMObjects = mContentJSON.getPageObject(mCurrentPageNumber);

		if (pageBGMObjects != null) {
			for (int i = 0; i < pageBGMObjects.length(); i++) {
				PageObjectJSON pageBGMPageObject = new PageObjectJSON(pageBGMObjects.getJSONObject(i));
				if (pageBGMPageObject.getMediaType() == MediaInfoJSON.MUSIC_TYPE) {
					if (pageBGMPageObject.getActionInfo().getPlayType() == 2) {
						String pageBGMFilePath = mContentDir + "/" + pageBGMPageObject.getActionInfo().getMusicFileName();
						Logger.d(TAG, "[addMusic]:pageBGMPageObject add page " + mCurrentPageNumber);
						pageBGMPathList.put(mCurrentPageNumber, pageBGMFilePath);
						pageBgmFlg = true;
						break;
						//return;
					}
				}
			}
		}


		JSONArray contentsBGMobjects = mContentJSON.getPageObject(0);
		if (contentsBGMobjects == null) {
			return;
		}

		for (int i = 0; i < contentsBGMobjects.length(); i++) {
			PageObjectJSON contentsBGMPageObject = new PageObjectJSON(contentsBGMobjects.getJSONObject(i));

			if (contentsBGMPageObject.getMediaType() == MediaInfoJSON.MUSIC_TYPE) {
				String soundFilePath = mContentDir + "/" + contentsBGMPageObject.getActionInfo().getMusicFileName();
				if (contentsBGMPageObject.getActionInfo().getPlayType() == 1) {
					if (contentBGMPlayer == null) {
						contentBGMPlayer = new ABVMediaPlayer(true);
						try {
							if (pageBgmFlg) {
								contentsBgmFlg = true;
								contentsBgmFilePath = soundFilePath;
								return;
							}
							Logger.d(TAG, "[addMusic]:MediaPlayer Content BGM");
							contentBGMPlayer.setDataSource(soundFilePath);
							contentBGMPlayer.prepare();
							contentBGMPlayer.start();
							return;
						} catch (IOException e) {
							Logger.e(TAG, "Can't play content BGM", e);
							ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
						}
					} else {
						return;
					}
				}
			}
		}

	}

	/**
	 * 再生中のAudioPlayerを一時停止する
	 */
	public void stopSound() {
		if (tapPlayer != null && tapPlayer.isPlaying()) {
			tapPlayer.pause();
			tapPlayer.stop();
			Logger.v(TAG, "[stopSound]:tapPlayer");
		} else if (pageBGMPlayer != null && pageBGMPlayer.isPlaying()) {
			pageBGMPlayer.pause();
			Logger.v(TAG, "[stopSound]:pageBGMPlayer");
		} else if (contentBGMPlayer != null && contentBGMPlayer.isPlaying()) {
			contentBGMPlayer.pause();
			Logger.v(TAG, "[stopSound]:contentBGMPlayer");
		}
	}

	private void playTapSound(String soundFilePath, PageObjectJSON pageObject) {

		if (!playTapSoundFlg || !preSoundFilePath.equals(soundFilePath)) {
			stopSound();
		}

		//프리뷰 모드일때 사운드 계속 재생
		if (preViewFlg) {
			preViewFlg = false;
			return;
		}
		//플레이 탭사운드를 하였을때 같은 페이지 내에서는 일시정지/재생 Bug 수정
		try {
			if (!playTapSoundFlg || !preSoundFilePath.equals(soundFilePath)) {
				tapPlayer = new TapMediaPlayer(contentId);

				Logger.d(TAG, "MediaPlayer Content BGM");

				tapPlayer.setDataSource(soundFilePath);

				preSoundFilePath = soundFilePath;

				tapPlayer.setLooping(PreferenceUtil.get(this, DefPrefKey.REPEATABLE_PLAY, getResources().getBoolean(R.bool.repeat_default)));
				tapPlayer.setOnCompletionListener(new TapMediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(TapMediaPlayer mp) {
						playTapSoundFlg = false;
					}
				});
				tapPlayer.tapPlayerObjectLogId = ContentLogUtil.getInstance().insertContentObjectLog(contentId, readingLogId, pageObject);
				tapPlayer.prepare();
				tapPlayer.start();
				playTapSoundFlg = true;
			}else{
				if (tapPlayer != null && tapPlayer.isPlaying()) {
					Logger.d(TAG, "tabPlayer paused");
					tapPlayer.pause();
				}else if (tapPlayer!= null && !tapPlayer.isPlaying()) {
					Logger.d(TAG, "tabPlayer start");
					tapPlayer.start();
				}
			}

		} catch (IOException e) {
			Logger.e(TAG, "[playTapSound]:e=" + e.getMessage(), e);
			ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
		}
	}
	
	public void playPageBGMSound() {
		playPageBGMSound(mCurrentPageNumber);
	}
	
	private void playPageBGMSound(int pageNumber) {
		String bgmFilePath = pageBGMPathList.get(pageNumber);

		//프리뷰 모드일때 사운드 계속 재생
		if (preViewFlg) {
			preViewFlg = false;
			return;
		}

		if (bgmFilePath != null) {
			Logger.v(TAG, "[playPageBGMSound]:pageNumber=%s", pageNumber);
			stopSound(); // 全部停止
			pageBGMPlayer = new ABVMediaPlayer(true);
			try {
				Logger.d(TAG, "MediaPlayer PAGE BGM:" + bgmFilePath);
				pageBGMPlayer.setDataSource(bgmFilePath);
				pageBGMPlayer.prepare();
				pageBGMPlayer.start();
			} catch (IOException e) {
				Logger.e(TAG, "e=" + e.getMessage(), e);
				ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_SHORT);
			}
		} else {
			// 該当するページBGMがない場合
			// 前ページのページBGMを停止させる
			if (pageBGMPlayer != null) {
				pageBGMPlayer.stop();
				pageBGMPlayer.release();
				pageBGMPlayer = null;
			} else if (tapPlayer != null) {
				tapPlayer.stop();
				tapPlayer.release();
				tapPlayer = null;
			}
			// コンテンツBGMがある場合は再生させる
			if (contentBGMPlayer != null && !contentBGMPlayer.isPlaying()) {
				Logger.v(TAG, "[playPageBGMSound]:contentBGMPlayer start");
				contentBGMPlayer.start();
			}
		}
	}

	/**
	 * VideoView画面表示
	 * @param pageNumber
	 * @param objectId
	 */
	private void showVideoView(String videofile, int pageNumber, Long objectId, int objectLogId) {
		if (isAnotherViewOpenFlg == false) {
			fullVideoView = new FullVideoView(this, videofile, mContentDto.contentName, contentId, pageNumber, objectId, isNormalSize() , objectLogId);
			fullVideoView.setOnCloseListener(new FullVideoView.OnCloseListener() {
				@Override
				public void onClose() {
					isVideoMax = false;
				}
			});
			isVideoMax = true;
			addContentView(fullVideoView, new ViewGroup.LayoutParams(FP, FP));
			objectIdPopupMap.put(objectId, fullVideoView);
		}
	}

	/**
	 * WebView画面表示
	 * @param pageNumber
	 * @param objectId
	 */
	private void showWebView(String linkurl, String browserType, int pageNumber, long objectId, int objectLogId) {
		if (linkurl == null) {
			return;
		}
		if (isAnotherViewOpenFlg == false) {
			isAnotherViewOpenFlg = true;
			preViewFlg = true;
			boolean innerBrowser = (browserType == null) || browserType.equals("0");

			if (innerBrowser) {
				ActivityHandlingHelper.getInstance().startHTMLWebActivity(this, null, linkurl, getContentId(), WEBVIEW, pageNumber, objectId, objectLogId, readingLogId);
			} else {
				Intent i = new Intent(Intent.ACTION_VIEW);
				if (StringUtil.isNullOrEmpty(linkurl)) {
					linkurl = "http://";
				}
				Uri u = Uri.parse(linkurl);
				i.setData(u);
				startActivity(i);
				isAnotherViewOpenFlg = false;
			}
		}
	}
	/**
	 * Preview画面表示
	 * @param objectId
	 */
	private void showPreview(List<String> imagefile, Long objectId, int objectLogId) {
    	//20120803 イメージがない場合移動しない
		if (isAnotherViewOpenFlg == false && !imagefile.isEmpty()) {
			isAnotherViewOpenFlg = true;
	    	Intent intent_ = new Intent(this, PreviewActivity.class);
	    	for (int i = 0; i < imagefile.size(); i++) {
	    		intent_.putExtra("FILEPATH" + (i + 1), mContentDir + "/" + imagefile.get(i));
	    	}
	    	intent_.putExtra("Position", 0);
		    intent_.putExtra(ABookKeys.CONTENT_ID, getContentId());
			intent_.putExtra("pageNumber", mCurrentPageNumber);
			intent_.putExtra("objectId", objectId);
			intent_.putExtra("objectLogId", objectLogId);

		    startActivityForResult(intent_, PREVIEW);

		    preViewFlg = true;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Uri[] result = null;
        Uri dataUri = null;

        if (intent != null && resultCode == RESULT_OK) {
            String dataString = intent.getDataString();
            if (dataString != null) {
                dataUri = Uri.parse(dataString);
                result = new Uri[]{dataUri};
            }
        }

		switch (requestCode) {
		case VIDEOVIEW:
		case WEBVIEW:
		case PREVIEW:
			isAnotherViewOpenFlg = false;
//			playPageBGMSound(mCurrentPageNumber); //프리뷰 모드 일때 음악재생 Bug
			break;
            case ABOOK_CHECK_TASK_IMAGE:
                if (mUploadMessage == null) {
                    return;
                }
                // 画像
                try {
                    if (dataUri == null) {
                        dataUri = imageUri;
                    }
                    Uri responseUri = attachmentImageProcessing(dataUri);
                    if (responseUri != null) {
                        mUploadMessage.onReceiveValue(new Uri[]{responseUri});
                    } else {
                        mUploadMessage.onReceiveValue(null);
                    }
                } catch (Exception e) {
                    Logger.e(TAG, e);
                    mUploadMessage.onReceiveValue(null);
                    ErrorMessage.showErrorMessageToast(getApplicationContext(), ErrorCode.E107);
                }
                break;
            case ABOOK_CHECK_TASK_VIDEO:
                if (mUploadMessage == null) {
                    return;
                }
                mUploadMessage.onReceiveValue(result);
                break;
		}
        mUploadMessage = null;
	}

	/**
	 * Balloon表示
	 * @param pageidx
	 */
	private void showBalloon(String contentHTML, final int pageidx, final Long objectId) {
		if (objectIdPopupMap.containsKey(objectId)) {
			return;
		}

		int matchParent = ViewGroup.LayoutParams.MATCH_PARENT;

		WebView webBalloon = new WebView(this);
		webBalloon.setBackgroundColor(0);
		webBalloon.loadDataWithBaseURL(null, contentHTML, "text/html", "utf-8", null);
		FrameLayout.LayoutParams paramWebView = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		paramWebView.gravity = Gravity.TOP;

		ScrollView scroll = new ScrollView(this);
		scroll.addView(webBalloon, paramWebView);

		LinearLayout layoutBalloon = new LinearLayout(this);
		layoutBalloon.setBackgroundColor(Color.WHITE);
		layoutBalloon.setLayoutParams(new LinearLayout.LayoutParams(matchParent, matchParent));
		LinearLayout.LayoutParams paramScroll = new LinearLayout.LayoutParams(matchParent, matchParent);
		layoutBalloon.addView(scroll, paramScroll);
		layoutBalloon.setPadding(3, 3, 3, 3);

		ABookAlertDialog dialogBalloon = new ABookAlertDialog(this) {
			@Override
			public boolean dispatchTouchEvent(MotionEvent ev) {
				return super.dispatchTouchEvent(ev);
			}
		};
		dialogBalloon.setCanceledOnTouchOutside(false);
		dialogBalloon.setView(layoutBalloon);
		dialogBalloon.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			@Override
            public void onClick(DialogInterface dialog, int whichButton) {
		        if (meetingManager.isSendable()) {
		        	meetingManager.sendWs(MeetingManager.CMD_CLOSEPOPUP, getContentId(), pageidx, objectId, null);
		        }

				dialog.dismiss();
				objectIdPopupMap.remove(objectId);
			}
		});
		dialogBalloon.show();
		objectIdPopupMap.put(objectId, dialogBalloon);
	}

	private void sendEmail(String subject, String address) {
		Logger.d(TAG, "sendEmail:" + address);
		// Intentインスタンスを生成
		Intent intent = new Intent();

		// アクションを指定(ACTION_SENDTOではないところがミソ)
		intent.setAction(Intent.ACTION_SEND);
		// データタイプを指定
		intent.setType("message/rfc822");
		// 宛先を指定
		intent.putExtra(Intent.EXTRA_EMAIL, new String[]{address});
		// 件名を指定
		intent.putExtra(Intent.EXTRA_SUBJECT, subject);
		// 本文を指定
		intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.email_body));
		// Intentを発行
		startActivity(intent);
	}

	/**
	 * しおりの存在有無
	 * @param pageNumber 対象のページ
	 * @return boolean
	 */
	private boolean isExistBookmark(int pageNumber) {
		try {
			return bookmarkLogic.isExsitContentBookmark(getContentId(), pageNumber);
		} catch (Exception e) {
			Logger.d("ABVException getAllContentList", e.getMessage());
			handleErrorMessageToast(e.getMessage());
		}
		return false;
	}

	/**
	 * しおりダイアログ表示
	 */
	private void showBookmarkDialog() {
		int count = 0;
		try {
			final ContentBookmarkAdapter adapter = new ContentBookmarkAdapter(ContentViewActivity.this, getContentId(), mContentJSON.isPdf());
			count = adapter.getCount();
			if (count > 0) {
				final ABookAlertDialog bookmakDialog = AlertDialogUtil.createAlertDialog(ContentViewActivity.this, R.string.bookmark);
				bookmakDialog.setAdapter(adapter, new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						int pageNumber = adapter.getItem(position).pageNum;
						if (mCurrentPageNumber != pageNumber) {
							jumpToPage(pageNumber);
						}
						bookmakDialog.dismiss();
					}
				});

				bookmakDialog.setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				showAlertDialog(bookmakDialog);
			}
		} catch (IOException e) {
			Logger.e(TAG, "ABVBookmarkAdapter error.", e);
		}
		if (count == 0) {
			errorMessageDialog(ContentViewActivity.this, R.string.bookmark, ErrorCode.L111);
		}
	}

	/**
	 * インデックスダイアログ表示
	 */
	private void showPDFIndexkDialog() {
		if (mPDFIndexInfoJSON != null && mPDFIndexInfoJSON.getJsonArray() != null) {
			new PDFIndexDialog(this, mPDFIndexInfoJSON.getJsonArray()).showDialog();
		} else {
			errorMessageDialog(ContentViewActivity.this, R.string.index, ErrorCode.L112);
		}

	}

	private void showTextDialog(int pagenum) {
		int wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT;
		int matchParent = ViewGroup.LayoutParams.MATCH_PARENT;

		LinearLayout layout = new LinearLayout(ContentViewActivity.this);
		layout.setLayoutParams(new LinearLayout.LayoutParams(matchParent, matchParent));
		layout.setGravity(Gravity.CENTER);


		final WebView webView = new WebView(this);

		final String pageText = contentPageDao.getContentPageText(getContentId(), pagenum+1);
		if (pageText != null) {
			String pageText1 = pageText.replaceAll("(\r\n|\n)", "<br />");

			webView.loadDataWithBaseURL("string12345", pageText1, "text/html", "UTF-8", null);
			Logger.d(TAG, "page Text : " + pageText1);
		}

		DisplayMetrics metrics = getResources().getDisplayMetrics();
		int dialogWidth;
		int minHeight;

		if (metrics.widthPixels > metrics.heightPixels) {
			dialogWidth = (int) (metrics.heightPixels * 0.8);
			minHeight = (int) (metrics.heightPixels * 0.3);
		} else {
			dialogWidth = (int) (metrics.widthPixels * 0.8);
			minHeight = (int) (metrics.widthPixels * 0.3);
		}
		webView.setMinimumHeight(minHeight);
		LinearLayout.LayoutParams paramEdt = new LinearLayout.LayoutParams(dialogWidth, wrapContent);
		layout.addView(webView, paramEdt);
		ABookAlertDialog textViewDialog = AlertDialogUtil.createAlertDialog(ContentViewActivity.this, R.string.page_copy);

		textViewDialog.setView(layout);

		textViewDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			@Override
            public void onClick(DialogInterface dialog, int whichButton) {
			}
		});

		textViewDialog.setPositiveButton(R.string.page_all_copy, new DialogInterface.OnClickListener() {
			@Override
            public void onClick(DialogInterface dialog, int whichButton) {
				//pageText 클립보드에 복사 후 토스트로 클립보드에 복사되었다 메시지 출력
				ClipboardUtil.setText(getApplicationContext(), pageText);
				Logger.d(TAG, "コピーされた内容 : " + pageText);
				ABVToastUtil.showMakeText(getApplicationContext(), R.string.text_copy_all, Toast.LENGTH_LONG);
				dialog.dismiss();
			}
		});

		showAlertDialog(textViewDialog);

		//메모리 clear.....
		//dialog 종료시 ?
		textViewDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				webView.stopLoading();
				//noinspection deprecation(API18から非推奨になった。無視)
				webView.clearView();
				//noinspection deprecation(API19から非推奨になった。無視)
				webView.freeMemory();

			}
		});
	}

	/**
	 * 検索ダイアログ表示
	 */
	private void showSearchListDialog(String searchKeyword) {
		Logger.v(TAG, "showSearchListDialog: searchKeyword=%s", searchKeyword);
		if (mSearchDialog == null) {
			mSearchDialog = createSearchDialog(searchKeyword);
		}

		if (!StringUtil.isNullOrWhiteSpace(searchKeyword)) {
			mSearchWord = searchKeyword.trim();
			PdfThumbnailProvider pdfThumbnailProvider = new PdfThumbnailProvider(getApplicationContext(), mFoxitPdfCore, getContentId(), isNormalSize());
			pdfThumbnailProvider.setPdfImageProvider(mPdfImageProvider);
			pdfThumbnailProvider.setIsLandscape(isLandscapeView);
			int count = 0;
			ListView listView = (ListView) mSearchDialog.findViewById(R.id.result_list);
			try {
				final ContentSearchPageAdapter adapter = new ContentSearchPageAdapter(this, getContentId(), mSearchWord, pdfThumbnailProvider);
				count = adapter.getCount();
				if (count > 0) {
					listView.setAdapter(adapter);
					listView.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							int pageNum = adapter.getItem(position).pageNum - 1;
							forceJumpToPage(pageNum);
							mSearchDialog.dismiss();
						}
					});
				}
			} catch (IOException e) {
				Logger.e(TAG, "ABVSearchPageAdapter error", e);
			}
			if (count == 0) {
				errorMessageDialog(ContentViewActivity.this, R.string.search, ErrorCode.L115);
				listView.setAdapter(null);
			}
		}

		if (!mSearchDialog.isShowing()) {
			mSearchDialog.show();
		}

		setToolbarVisable(false); // ツールバー・サムネイルバーは消す
	}

	private Dialog createSearchDialog(String searchKeyword) {
		final Dialog searchDialog = new Dialog(ContentViewActivity.this);
		searchDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		searchDialog.setContentView(R.layout.ac_content_view_search);

		final ABVEditText editText = (ABVEditText) searchDialog.findViewById(R.id.edt_search);
		editText.setText(searchKeyword);
		editText.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
					showSearchListDialog(editText.getText().toString());
					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (searchDialog.getCurrentFocus() != null) {
                        imm.hideSoftInputFromWindow(searchDialog.getCurrentFocus().getWindowToken(), 0);
                    }
					return true;
				}
				return false;
			}
		});

		Button searchBtn = (Button) searchDialog.findViewById(R.id.search_button);
		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showSearchListDialog(editText.getText().toString());
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                if (searchDialog.getCurrentFocus() != null) {
                    imm.hideSoftInputFromWindow(searchDialog.getCurrentFocus().getWindowToken(), 0);
                }
            }
		});

		Button closeBtn = (Button) searchDialog.findViewById(R.id.close_button);
		closeBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchDialog.dismiss();
				// 検索ワードがクリアされた場合、検索結果表示をリセットする
				if (StringUtil.isNullOrEmpty(editText.getText().toString()) && !StringUtil.isNullOrEmpty(mSearchWord)) {
					mSearchWord = null;
					ListView listView = (ListView) mSearchDialog.findViewById(R.id.result_list);
					listView.setAdapter(null);
					forceJumpToPage(mCurrentPageNumber);
				}
			}
		});
		return searchDialog;
	}

	@Override
    public void onStart() {
		super.onStart();
    }
	@Override
    public void onPause() {
		super.onPause();

		// 閲覧履歴更新
		contentDao.updateLastViewedPage(getContentId(), mCurrentPageNumber);

		//프리뷰 일 경우에는 사운드 재생 중지 Bug
		if (preViewFlg) {
			stopVideo();
		} else{
			stopVideo();
			stopSound();
		}
	}

	/**
	 * リモート操作
	 *
	 * @param json
	 */
	@Override
	public void performRemoteEvent(final JSONObject json) {
		Logger.v(TAG, "[performRemoteEvent] %s : %s", json, objectIdPopupMap);
		String cmd = json.getString(MeetingManager.CMD);
		long remoteContentId = JsonUtil.getLong(json, MeetingManager.CONTENTID);
		int pageNumber = JsonUtil.getInt(json, MeetingManager.PAGE_NUMBER);
		long remoteObjectId = JsonUtil.getLong(json, MeetingManager.OBJECTID, 0);

		if (isMarking && !cmd.equals(MeetingManager.CMD_MARKING)) {
			// マーキング状態でマーキング以外のコマンド来たらマーキングは閉じる
			closeMarkingLayout();
		}

		if (cmd.equals(MeetingManager.CMD_OPEN) && remoteContentId != -1) {
		}
		else {
			if (pageNumber >= mAllPageCount || pageNumber < 0) {
				Logger.e(TAG, "Invalid Page number : " + pageNumber);
				return;
			}

			if (cmd.equals(MeetingManager.CMD_MOVEPAGE)) { // 移動
				movePage(pageNumber);
				return;
			}

			if (pageNumber != mCurrentPageNumber) { // ページが異なる場合ジャンプ
				movePage(pageNumber);
			}

			if (cmd.equals(MeetingManager.CMD_ACTION)) { // 通常アクションボタン
				View targetView = objectIdButtonMap.get(remoteObjectId);
				if (targetView == null) {
					VideoMountAction videoMountAction = findVideoMountAction(pageNumber, remoteObjectId); // 埋め込み動画の最初のアクション
					if (videoMountAction != null) {
						performRemoteMountVideo(videoMountAction, MeetingManager.START, 0, false, false);
					}
					Logger.e(TAG, "[performRemoteEvent] targetView not found. remoteObjectId=" + remoteObjectId); // EMAILの場合はエラーが出てしまう。
					return;
				}
				Logger.v(TAG, "[performRemoteEvent] perform click. remoteObjectId=%s targetView=%s", remoteObjectId, targetView);
				targetView.performClick(); // ボタンをクリック
			}
			else if (cmd.equals(MeetingManager.CMD_LINKURLACTION)) { // PDF Link
				String url = JsonUtil.getString(json, MeetingManager.URL); // null可
				Boolean browser = JsonUtil.getBoolean(json, MeetingManager.BROWSER, false);
				showWebView(url, browser?"1":"0", pageNumber, 0, -1); // objectIdは0にする
			}
			else if (cmd.equals(MeetingManager.CMD_3DVIEWACTION)) { // 3D
				String filePath = JsonUtil.getString(json, MeetingManager.FILE_NAME);
				filePath = ABVEnvironment.getInstance().getContentCacheDirectoryPath(remoteContentId) + "/" + filePath;
				int pageidx = getPageContentArrayIndex(pageNumber); // jsonのpageオブジェクトの配列インデックスを取得
				if (pageidx == -1) {
					Logger.e(TAG, "[performRemoteEvent] pageidx not found. pageNumber=" + pageNumber);
					return;
				}
				int index = -1;
				for (Action3DImageView action3dImageView : mPageActionList.get(pageidx).array3DImage) {
					if (action3dImageView.getObjectId() == remoteObjectId) {
						index = action3dImageView.getIndex();
						break;
					}
				}
				if (index == -1) {
					Logger.e(TAG, "[performRemoteEvent] index not found. remoteObjectId=" + remoteObjectId);
				}
				else {
					mPageActionList.get(pageidx).array3DImage.get(index).setCurrentImagePath(filePath);
				}
			}
			else if (cmd.equals(MeetingManager.CMD_MOVIEACTION)) { // 埋め込み動画・差し替え動画
				String type = JsonUtil.getString(json, MeetingManager.TYPE);
				int playTime = JsonUtil.getInt(json, MeetingManager.PLAY_TIME);
				Boolean isFullScreen = JsonUtil.getBoolean(json, MeetingManager.IS_FULL_SCREEN);

				VideoMountAction videoMountAction = findVideoMountAction(pageNumber, remoteObjectId);
				if (videoMountAction != null) { // 埋め込み動画の場合
					performRemoteMountVideo(videoMountAction, type, playTime, isFullScreen, false);
				}
				else {
					Object obj = objectIdPopupMap.get(remoteObjectId);
					if (obj instanceof VideoMountAction) { // 差し替え動画の場合
						performRemoteMountVideo((VideoMountAction)obj, type, playTime, isFullScreen, true);
					}
					else if (obj instanceof FullVideoView) { // 全画面動画の場合
						performRemoteFullVideo((FullVideoView)obj, type, playTime);
					} else {
						Logger.e(TAG, "[performRemoteEvent] target video not found. remoteObjectId=" + remoteObjectId);
					}
				}
			} else if (cmd.equals(MeetingManager.CMD_QUESTIONNAIREACTION)) { // アンケート
				Float alpha = JsonUtil.getFloat(json, MeetingManager.ALPHA);
				if (alpha != null) {
					enqueteLayout.setAlpha((int) (alpha * 255));
				}
				Boolean isBigFont = JsonUtil.getBoolean(json, MeetingManager.IS_BIG_FONT_SIZE);
				if (isBigFont != null) {
					if (isBigFont) {
						enqueteLayout.setFontBig();
					}
					else {
						enqueteLayout.setFontSmall();
					}
				}

				Boolean isRight = JsonUtil.getBoolean(json, MeetingManager.IS_RIGHT);
				Logger.v(TAG, "isNormalSize: %s", isNormalSize());
				if (isRight != null && !isNormalSize()) {
					if (isRight) {
						enqueteLayout.right();
					}
					else {
						enqueteLayout.left();
					}
				}
			} else if (cmd.equals(MeetingManager.CMD_MARKING)) { // マーキング描画
				peformRemoteMarking(json);
			} else if (cmd.equals(MeetingManager.CMD_CLOSEPOPUP)) { // 各種閉じる
				closePopup(remoteObjectId);
			} else if (cmd.equals(MeetingManager.CMD_CURSORMODE)) { // カーソルモード切替
				Boolean isCursorMode = JsonUtil.getBoolean(json, MeetingManager.IS_CURSOR_MODE);
				mMainLayout.setRemoteDraw(isCursorMode);
			} else if (cmd.equals(MeetingManager.CMD_CURSOR)) { // カーソル移動
				Float x = JsonUtil.getFloat(json, MeetingManager.X);
				Float y = JsonUtil.getFloat(json, MeetingManager.Y);
				if (x != null && y != null) {
					mMainLayout.setRemoteDraw(true);
					mMainLayout.drawRemoteCursor(x, y);
				}
			} else if (cmd.equals(MeetingManager.CMD_ZOOM)) {
				Float x = JsonUtil.getFloat(json, MeetingManager.X);
				Float y = JsonUtil.getFloat(json, MeetingManager.Y);
				Float scale = JsonUtil.getFloat(json, MeetingManager.SCALE);
				if (x != null && y != null && scale != null) {
					ZoomRelativeLayout zoomLayout = mShowPageLayout.get(mCurrentPageNumber);
					ViewMargin margin = zoomLayout.getContentPageMargin();
					Matrix matrix = new Matrix();
					matrix.postScale(scale, scale);
					matrix.postTranslate(x * zoomLayout.getAuthoringScale() + margin.left, y * zoomLayout.getAuthoringScale() + margin.top);
					zoomLayout.setZoomMatrix(matrix);
				}
			} else {
				Logger.e(TAG, "Not Implemented Command. " + cmd);
			}
		}
	}

	private VideoMountAction findVideoMountAction(int pageNumber, long objectId) {
		int pageidx = getPageContentArrayIndex(pageNumber); // jsonのpageオブジェクトの配列インデックスを取得
		if (pageidx == -1) {
			Logger.w(TAG, "[performRemoteEvent] pageidx not found. pageNumber=" + pageNumber);
		} else {
			for (VideoMountAction videoMountAction : mPageActionList.get(pageidx).arrayVideoMount) {
				if (videoMountAction.getObjectId() == objectId) {
					return videoMountAction;
				}
			}
		}
		return null;
	}

	private void peformRemoteMarking(final JSONObject json) {
		String action = JsonUtil.getString(json, MeetingManager.MARKING_ACTION);

		if (!isMarking && !action.equals(MeetingManager.MARKING_ACTION_INVISIBLE) && !action.equals(MeetingManager.MARKING_ACTION_VISIBLE)) {
			showMarkingLayout();
		}

		handler.post(new Runnable() {
			@Override
			public void run() {
				switch (JsonUtil.getString(json, MeetingManager.MARKING_ACTION)) {
					case MeetingManager.MARKING_ACTION_DRAW:
						draw(json);
						break;
					case MeetingManager.MARKING_ACTION_CLEAR:
						mMarkingLayout.clear();
						break;
					case MeetingManager.MARKING_ACTION_SAVE:
						int markShareFlag =JsonUtil.getInt(json, MeetingManager.MARKING_SHARE);
						if ( markShareFlag == 1) {
							mMarkingLayout.chairmanMarkingShareFlag = true;
						} else {
							mMarkingLayout.chairmanMarkingShareFlag = false;
						}
						mMarkingLayout.saveClose();
						break;
					case MeetingManager.MARKING_ACTION_END:
						closeMarkingLayout();
						break;
					case MeetingManager.MARKING_ACTION_VISIBLE:
						setMarkingViewVisibility(true);
						break;
					case MeetingManager.MARKING_ACTION_INVISIBLE:
						setMarkingViewVisibility(false);
						break;
					default:
						break;
				}
			}
		});
	}

	private void draw(JSONObject json) {
		int pageWidth;
		if (mContentJSON.isPdf()) {
			PageInfoJSONData page = mPageInfoJSON.getPageData(mCurrentPageNumber);
			pageWidth = page.pageWidth;
		} else {
			pageWidth = mContentJSON.getWidth();
		}

		try {
			if (mMarkingLayout != null) {
				MarkingJson markingJson = new MarkingJson(json, (float) (mMarkingLayout.getWidth() - mMarkingLayout.margin.left - mMarkingLayout.margin.right) / pageWidth);
				mMarkingLayout.drawRemoteMarkig(markingJson);
			}
		} catch (JSONException e) {
			Logger.e(TAG, e);
		}
	}

	/**
	 * 埋め込み動画
	 *
	 * @param videoMountAction
	 * @param type
	 * @param playTime
	 * @param isFullScreen
	 * @param isChangeVideo
	 */
	private void performRemoteMountVideo(VideoMountAction videoMountAction, String type, int playTime, Boolean isFullScreen, boolean isChangeVideo) {
		if (type == null) {
		}
		else if (type.equals(MeetingManager.START)) {
			if (videoMountAction.isPrepared()) {
				videoMountAction.pauseAfterStartVideo();
			}
			else if (!isChangeVideo) {
				videoMountAction.start(videoMountAction.getVideoFile(), 0);
			}
			else { // 1秒待ってからダメなら無視
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {}
				if (videoMountAction.isPrepared()) {
					videoMountAction.pauseAfterStartVideo();
				}
			}
		}
		else if (type.equals(MeetingManager.PAUSE)) {
			videoMountAction.pauseVideo();
		}

		if (videoMountAction.isPrepared() && playTime >= 0) {
			videoMountAction.seekTo(playTime * 1000);
		}

		if (isFullScreen == null) {
		}
		else if (isFullScreen) {
			isVideoMax = true;
			mPageScrollView.setVideoMaxFlag(true);
			setToolbarVisable(false);
			if (isChangeVideo) {
				stopCurrentPageMountVideo(null, true);
				stopCurrentPageChangeVideo(videoMountAction.getIndex(), true);
			}
			else {
				stopCurrentPageMountVideo(videoMountAction.getIndex(), true);
				stopCurrentPageChangeVideo(null, true);
			}
			setToolbarVisable(false);
			videoMountAction.showMax();
		}
		else {
			setSurfaceViewVisible(!isChangeVideo, videoMountAction.getIndex());
			videoMountAction.showDefault();
		}
	}

	private void performRemoteFullVideo(FullVideoView videoView, String type, int playTime) {
		if (type == null) {
		}
		else if (type.equals(MeetingManager.START)) {
			videoView.restartVideo();
		}
		else if (type.equals(MeetingManager.PAUSE)) {
			videoView.pauseVideo();
		}

		if (playTime >= 0) {
			videoView.jump(playTime * 1000);
		}
	}


	private void movePage(int pageNumber) {
		for (long popupObjectId : objectIdPopupMap.keySet()) {
			closePopup(popupObjectId);
		}
		jumpToPage(pageNumber);
	}

	private void closePopup(long objectId) {
		Object popup = objectIdPopupMap.get(objectId);
		if (popup != null) {
			Logger.v(TAG, "objectId=%s popup=%s", objectId, popup);
			if (popup instanceof EnqueteLayout) {
				((EnqueteLayout)popup).close();
			}
			else if (popup instanceof FullVideoView) {
				((FullVideoView)popup).close();
				fullVideoView = null;
			}
			else if (popup instanceof View) {
				((View)popup).setVisibility(View.GONE);
			}
			else if (popup instanceof AlertDialog) {
				((AlertDialog)popup).cancel();
			}
			objectIdPopupMap.remove(objectId);
		}
	}

	/**
	 * マーキングレイアウト表示
	 */
	private void showMarkingLayout() {
		// マーキングしている間は画面を固定
		if (isRotatable()) {
			setFixedOrientation(true);
		}

		if (!isMarking) {
			for (MarkingView markingView : mMarkingViewList) {
				if (markingView.getPageNum() == mCurrentPageNumber) {
					markingView.setVisibility(View.GONE);
				}
			}

			// オーサリングのページサイズでマーキングを保存するため情報取得
			int pageWidth;
			int pageHeight;
			if (mContentJSON.isPdf()) {
				PageInfoJSONData page = mPageInfoJSON.getPageData(mCurrentPageNumber);
				pageWidth = page.pageWidth;
				pageHeight = page.pageHeight;
			}
			else {
				pageWidth = mContentJSON.getWidth();
				pageHeight = mContentJSON.getHeight();
			}

			ViewMargin margin = (mShowPageLayout.get(mCurrentPageNumber) == null)? null: mShowPageLayout.get(mCurrentPageNumber).getContentPageMargin();
			// （mMarkingLayoutがnullでない）回転された場合などマージンだけ変更
			if (mMarkingLayout == null) {
				mMarkingLayout = new MarkingLayout(this, mContentDto, mCurrentPageNumber, pageWidth, pageHeight, margin, contentLogic, new MarkingLayout.OnMarkingListener() {
					@Override
					public void close() {
						closeMarkingLayout();
					}
				});
				if (mCurrentPageNumber <= 0) {
					mMarkingLayout.setBackPageStatus(false);
				}
				if (mCurrentPageNumber>= (mAllPageCount - 1)) {
					mMarkingLayout.setNextPageStatus(false);
				}
			} else {
				mMarkingLayout.setTouchDrawViewMargin(margin);
			}
			mMarkingLayout.setUnAuthorizedContentListener(unAuthorizedContentListener);
			mMarkingLayout.setMovePageListener(movePageListener);
			isMarking = true;
			setToolbarVisable(false);
			tbtnMarking.setChecked(false);
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
			mMainLayout.addView(mMarkingLayout, params);

			if (meetingManager.isSendable()) {
				JSONObject json = new JSONObject();
				json.put(MeetingManager.MARKING_ACTION, MeetingManager.MARKING_ACTION_START);
				meetingManager.sendWs(MeetingManager.CMD_MARKING, contentId, mCurrentPageNumber, null, json);
			}
		}
	}

	public void setMarkingReadOnly(boolean readOnly) {
		if (isMarking) {
			mMarkingLayout.setReadOnly(readOnly);
		}
	}

	private void closeMarkingLayout() {
		mMainLayout.removeView(mMarkingLayout);
		isMarking = false;
		tbtnMarking.setChecked(true);

		for (MarkingView markingView : mMarkingViewList) {
			markingView.reLoad();
		}
		mMarkingLayout = null;

		// 画面を固定を解除
		if (isRotatable()) {
			setFixedOrientation(false);
		}
	}

	//앙케이트 레이아웃
	private void showEnqueteLayout(EnqueteWebView webView, ActionInfoJSON actionInfoJSON) {
		isEnqueteOpening = true;
		isEnqueteFullScreen = (actionInfoJSON.getFullScreen() == 1 || isNormalSize());
		String htmlPath = contentLogic.getHtmleFilePath(getContentId(), actionInfoJSON.getEnquete(), isEnqueteFullScreen);
		final long abObjectId = actionInfoJSON.getObjectId();
		final long abEnqueteId = actionInfoJSON.getEnqueteId();
		final int saveAs = actionInfoJSON.getSaveAs();

		final int pixelWidth = isEnqueteFullScreen? mDisplaySize.width: (int) (getResources().getDisplayMetrics().density * EnqueteLayout.HALF_WIDTH);
		Logger.d(TAG, "pixel_width=%s density=%s", pixelWidth, getResources().getDisplayMetrics().density);

		enqueteLayout = new EnqueteLayout(this, webView, getContentId(), mCurrentPageNumber, actionInfoJSON, htmlPath, pixelWidth, isEnqueteFullScreen, new EnqueteLayout.OnWebViewListener() {

			@Override
			public void close() {
				if (saveAs == 1) {
					enqueteMap.put(abEnqueteId, enqueteLayout);
				}
				
				isEnqueteOpening = false;
				isEnquete = false;
				mMainLayout.removeView(enqueteLayout);
	            if (meetingManager.isSendable()) {
	            	meetingManager.sendWs(MeetingManager.CMD_CLOSEPOPUP, getContentId(), mCurrentPageNumber, abObjectId, null);
	            }
			}

			@Override
			public void Left() {
				setToolbarVisable(false);
				mMainLayout.removeView(enqueteLayout);
				RelativeLayout.LayoutParams params = createParam(pixelWidth , FP);
				mMainLayout.addView(enqueteLayout, params);
				isEnqueteLeft = true;
	            if (meetingManager.isSendable()) {
	            	JSONObject json = new JSONObject();
					json.put(MeetingManager.IS_RIGHT, false);
	            	meetingManager.sendWs(MeetingManager.CMD_QUESTIONNAIREACTION, getContentId(), mCurrentPageNumber, abObjectId, json);
	            }
			}
			@Override
			public void Right() {
				setToolbarVisable(false);
				mMainLayout.removeView(enqueteLayout);
		        RelativeLayout.LayoutParams param1 = createParam(pixelWidth ,ViewGroup.LayoutParams.MATCH_PARENT);
		        param1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		        mMainLayout.addView(enqueteLayout, param1);
				isEnqueteLeft = false;
	            if (meetingManager.isSendable()) {
	            	JSONObject json = new JSONObject();
					json.put(MeetingManager.IS_RIGHT, true);
	            	meetingManager.sendWs(MeetingManager.CMD_QUESTIONNAIREACTION, getContentId(), mCurrentPageNumber, abObjectId, json);
	            }
			}

			@Override
			public void TouchEvent() {
				isSeeking = true;
			}

			@Override
			public void DisallowMovePage() {
				isDisallowMovePage = true;
			}
		});
		isEnquete = true;
		objectIdPopupMap.put(abObjectId, enqueteLayout);

		setToolbarVisable(false);
		RelativeLayout.LayoutParams params;
		if (isEnqueteFullScreen) {
			params = createParam(FP , FP);
		} else{
			params = createParam(pixelWidth, FP);
			if (!isEnqueteLeft) {
				params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			}
		}

		mMainLayout.addView(enqueteLayout, params);
	}

	// メインレイアウトクラス
    private class MmainLayout extends RelativeLayout {

        private boolean isTouching;
        private float mX;
		private float mY;
        private Bitmap bitmap;
        private float bitmapW;
        private float bitmapH;
		private boolean isRemoteDraw;

        public MmainLayout(Context context) {
            super(context);

            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_cursor);
            bitmapW = bitmap.getWidth() / 2;
            bitmapH = bitmap.getHeight() / 2;
        }

        // カーソルを最上部に書くためにdispatchDrawで描画
        @Override
        protected void dispatchDraw(Canvas canvas) {
            super.dispatchDraw(canvas);
            if (isTouching && isCursorModeEnable() || isRemoteDraw) {
            	canvas.drawBitmap(bitmap, mX  - bitmapW, mY  - bitmapH - convertDensitySize(20), null);
            }
        }
        // カーソル描画
        public void drawCursor(int action , float x,float y) {
            switch (action) {
            case MotionEvent.ACTION_DOWN:
                isTouching = true;
                mX = x;
                mY = y;
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                isTouching = true;
                mX = x;
                mY = y;
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                //isTouching = false;
                invalidate();
                break;
            }

            if (isCursorModeEnable() && !slide.isChecked() && meetingManager.isSendable()) {
            	ZoomRelativeLayout zoomRelativeLayout = mShowPageLayout.get(mCurrentPageNumber);
            	if (zoomRelativeLayout == null) {
            		Logger.e(TAG, "zoomRelativeLayout is null");
            		return;
            	}
            	Logger.v(TAG, "AuthoringScale : " + zoomRelativeLayout.getAuthoringScale());
            	JSONObject json = new JSONObject();
                if (getMargin() != null) {
                    json.put(MeetingManager.X, (x - bitmapW - getMargin().left) / zoomRelativeLayout.getAuthoringScale());
                    json.put(MeetingManager.Y, (y - bitmapH - getMargin().top) / zoomRelativeLayout.getAuthoringScale());
                }
            	meetingManager.sendWs(MeetingManager.CMD_CURSOR, getContentId(), mCurrentPageNumber, null, json);
            }
        }

		// カーソル描画
		public void drawRemoteCursor(float x, float y) {
            Logger.v(TAG, "drawRemoteCursor x=%s y=%s", x, y);
            if (onCreateFinish && isRemoteDraw) {
            	ZoomRelativeLayout zoomRelativeLayout = mShowPageLayout.get(mCurrentPageNumber);
            	if (zoomRelativeLayout == null) {
            		Logger.e(TAG, "zoomRelativeLayout is null");
            		return;
            	}
            	Logger.v(TAG, "AuthoringScale : " + zoomRelativeLayout.getAuthoringScale());
                if (getMargin() != null) {
                    mX = x * zoomRelativeLayout.getAuthoringScale() + bitmapW + getMargin().left;
                    mY = y * zoomRelativeLayout.getAuthoringScale() + bitmapH + getMargin().top;
                }
            	invalidate();
            }
		}

		public void setRemoteDraw(boolean remoteDraw) {
			isRemoteDraw = remoteDraw;
		}

		private ViewMargin getMargin() {
			ZoomRelativeLayout zoomRelativeLayout = mShowPageLayout.get(mCurrentPageNumber);
			if (zoomRelativeLayout != null) {
				return zoomRelativeLayout.getContentPageMargin();
			}
			return null;
		}

    }

    private int getPageContentArrayIndex(int pageNumber) {
    	int retIndex = -1;
    	for (int i = 0; i < mPageActionList.size(); i++) {
			if (mPageActionList.get(i).getPageNumber() == pageNumber) {
				retIndex = i;
				break;
			}
		}
    	return retIndex;
    }

    private void videoMaxToDefault() {
    	isVideoMax = false;
		mPageScrollView.setVideoMaxFlag(false);
		int pageidx = getPageContentArrayIndex(mCurrentPageNumber);

		ArrayList<VideoMountAction> arrayVideoMount = mPageActionList.get(pageidx).arrayVideoMount;
		for (int i = 0; i < arrayVideoMount.size(); i++) {
			if (arrayVideoMount.get(i).getSurfaceVisibility() == View.VISIBLE) {
				arrayVideoMount.get(i).showDefault();
				setSurfaceViewVisible(true, i);     //他の動画を表示
				return;
			}
		}

		ArrayList<VideoMountAction> arrayVideoChange = mPageActionList.get(pageidx).arrayVideoChange;
		for (int i = 0; i < arrayVideoChange.size(); i++) {
			if (arrayVideoChange.get(i).getSurfaceVisibility() == View.VISIBLE) {
				arrayVideoChange.get(i).showDefault();
				setSurfaceViewVisible(false, i);     //他の動画を表示
				return;
			}
		}
	}

    public void setDefaultVideo() {
		for (int i = 0; i < mPageActionList.size(); i++) {
	        for (int j = 0; j < mPageActionList.get(i).arrayVideoMount.size(); j++) {
	        	mPageActionList.get(i).arrayVideoMount.get(j).setDefaultPosition();
			}
	        for (int j = 0; j < mPageActionList.get(i).arrayVideoChange.size(); j++) {
	        	mPageActionList.get(i).arrayVideoChange.get(j).setDefaultPosition();
			}
		}
	}

    public void resetScrollStatus() {
    	mScrollStatus = ScrollStatus.NONE;
    }

	//20120803
    //スクロールが移動してる状態はFALSE
    private boolean getTouchScrollPosition() {
    	return mCurrentPageNumber*mDisplaySize.width == mPageScrollView.getScrollX();
    }

    /**
     * PDFサイズをオーサリング上のサイズに変換するクラス
     * @author jang
     *
     */
    private static class PDFAuthoringSize {
    	private static final float EDIT_VIEW_LAND_WIDTH = 1024f;  // AATでiPadのサイズに合わせた長辺のサイズ
    	private static final float EDIT_VIEW_LAND_HEIGHT = 748f;  // AAtでiPadのサイズに合わせた短辺のサイズ
    	private static final float EDIT_VIEW_PORT_WIDTH = 768f;   // AATでiPadのサイズに合わせた短辺のサイズ
    	private static final float EDIT_VIEW_PORT_HEIGHT = 1004f; // AAtでiPadのサイズに合わせた長辺のサイズ

    	public float width;
		public float height;

    	public PDFAuthoringSize(Size size) {
    		float authoringWidth;
			float authoringHeight;
			if (size.width > size.height) {
    			authoringWidth = EDIT_VIEW_LAND_WIDTH;
    			authoringHeight = EDIT_VIEW_LAND_HEIGHT;
    		} else {
    			authoringWidth = EDIT_VIEW_PORT_WIDTH;
    			authoringHeight = EDIT_VIEW_PORT_HEIGHT;
    		}
    		float scale = Math.min(authoringWidth / size.width, authoringHeight / size.height);
    		width = scale * size.width;
    		height = scale * size.height;
    	}

    }

    /**
	 * コンテンツリンク中でコンテンツがない場合、ダウンロードするように
	 * checkContentをもう一度呼び出す
	 *
	 */

    @Override
	public void onDownloadedContentDetail(final HttpDownloadSimpleNotification notification) {
		//	ここでは、finishedとfailed以外はこない。
		if (notification.getDownloadState() == HttpDownloadState.failed) {
			//Logger.e("コンテンツ詳細情報取得失敗　：" + notification.getError().toString());
			handler.post(new Runnable() {
				@Override
				public void run() {
					closeProgressPopup();
					if (ExceptionHandler.isNoSpaceLeftOnDeviceIOException(notification.getError())) {
						//	空き容量が足りない
						handleErrorMessageToast(ErrorCode.STORAGE_ERROR);
					} else {
						handleErrorMessageToast(ErrorCode.L120);
					}
				}
			});
		} else {
			ActivityHandlingHelper.getInstance().checkContent(getContentId(), mCurrentPageNumber);
		}
	}

	//Enquete modeかCheck
	public boolean isEnqueteStatus() {
		return isEnquete;
	}

	// マーキング中かどうか確認
	public boolean isMarkingStatus() {
		return isMarking;
	}

	private void showEnqueteMessageDialog() {

		ABookAlertDialog enqueteDialog = AlertDialogUtil.createAlertDialog(this, R.string.enquete);
		enqueteDialog.setMessage(R.string.enquete_alert_marking_message);
		enqueteDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		enqueteDialog.show();

	}

	@Override
    public int getCurrentPageNumber() {
		return mCurrentPageNumber;
	}

	public int getLThumViewSize() {
		return mLThumViewSize;
	}

	@Override
    protected void releaseInit() {
		mActivityFinishFlg = true;
	}

	/**
	 * 会議室機能
	 * 拡大・縮小関連のアクション情報を転送
	 * @param dx float PDF座標左上
	 * @param dy float PDF座標左上
	 * @param scale float 拡大率
	 */
	public void callZoomAction(float dx, float dy, float scale, float width, float height) {
		if (meetingManager.isSendable()) {
			ViewMargin viewMargin = mShowPageLayout.get(mCurrentPageNumber).getContentPageMargin();
			PageInfoJSONData pageInfoJson =  mPageInfoJSON.getPageData(mCurrentPageNumber);
			float scaleWidth = width / scale / pageInfoJson.pageWidth;
			float scaleHeight = height / scale / pageInfoJson.pageHeight;
			dx = (dx  - viewMargin.left) / scaleWidth;
			dy = (dy - viewMargin.top) / scaleHeight;
			Logger.d(TAG, "callZoomAction:x=%s, y=%s, scale=%s", dx, dy, scale);
			final JSONObject json = new JSONObject();
			json.put(MeetingManager.X, dx);
			json.put(MeetingManager.Y, dy);
			json.put(MeetingManager.SCALE, scale);
			meetingManager.sendWs(MeetingManager.CMD_ZOOM, getContentId(), mCurrentPageNumber, null, json);
		}
	}

	public void callZoomLog(double dx, double dy, String eventType) {
		ZoomRelativeLayout zoomRelativeLayout = mShowPageLayout.get(mCurrentPageNumber);
		if (zoomRelativeLayout == null) {
			Logger.e(TAG, "zoomRelativeLayout is null");
			return;
		}

		// オーサリング座標に変換
		dx = dx / zoomRelativeLayout.getAuthoringScale();
		dy = dy / zoomRelativeLayout.getAuthoringScale();

		Logger.d(TAG, "callZoomLog dx:" + dx + ",dy:" + dy);

		ContentLogUtil.getInstance().insertZoomLog(contentId, readingLogId, mCurrentPageNumber, dx, dy, eventType);
	}

	private UnAuthorizedContentListener unAuthorizedContentListener = new UnAuthorizedContentListener() {
		@Override
		public void unAuthorizedContentNotification(String msg) {
			showUnAuthorizedContentWarningDialog(msg);
		}
	};

	private MovePageInterface movePageListener = new MovePageInterface() {
		@Override
		public void nextPage() {
			showProgressPopup();
			moveTo(1);
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mMarkingLayout.setBackPageStatus(true);
					if (mCurrentPageNumber >= mAllPageCount-1) {
						mMarkingLayout.setNextPageStatus(false);
					}
					closeMarkingLayout();
					showMarkingLayout();
					closeProgressPopup();
				}
			}, intervalAddOrRemovePage);
		}
		@Override
		public void backPage() {
			showProgressPopup();
			moveTo(-1);
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mMarkingLayout.setNextPageStatus(true);
					if (mCurrentPageNumber <= 0) {
						mMarkingLayout.setBackPageStatus(false);
					}
					closeMarkingLayout();
					showMarkingLayout();
					closeProgressPopup();
				}
			}, intervalAddOrRemovePage);
		}
	};

    @Override
    protected void commonConfigureRemote() {
        taskListButton = (ImageButton) findViewById(R.id.btn_show_task_list);
        helpButton = (ImageButton) findViewById(R.id.btn_help);

        if (mXWalkOpenType == Constant.XWalkOpenType.DEFAULT) {
            helpButton.setVisibility(View.GONE);
            operationHomeButton.setVisibility(View.GONE);
            taskListButton.setVisibility(View.GONE);
        } else {
            helpButton.setVisibility(View.VISIBLE);
            operationHomeButton.setVisibility(View.VISIBLE);

            subMenuBtn.setVisibility(View.GONE);
            exitMeetingBtn.setVisibility(View.GONE);
            mBtnRemoteStart.setVisibility(View.GONE);
        }

        switch (mXWalkOpenType) {
            case Constant.XWalkOpenType.TASK_REPORT:
                if (mOperationType == OperationType.LIST) {
                    taskListButton.setVisibility(View.GONE);
                } else {
                    taskListButton.setVisibility(View.VISIBLE);
                }
                operationNameTitle.setVisibility(View.VISIBLE);
                break;
            case Constant.XWalkOpenType.PANO_EDIT:
                taskListButton.setVisibility(View.GONE);
                operationNameTitle.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void finishActivity() {
        setResult(RESULT_OK, new Intent());
        finish();
        if (objectId == -1) { // HTMLコンテンツの場合で、KeyUpではない場合、全コンテンツActivityを終了
            ActivityHandlingHelper.getInstance().finishAllContentViewActivity();
        }
    }

    @Override
    protected void webViewLoadUrl(String url){
        //showWebView(url,"0", 1, 0, -1);
        operationTaskLayout.taskWebViewLoadUrl(url);
    }

    // OZDからのscript呼び出す用
    public void callOzWebViewLoadUrl(String url) {
    	operationTaskLayout.taskWebViewLoadUrl(url);
	}

	/**
	 * PDFプロジェクトのアクション制御メソッド
	 * @param checkParam
	 * @param operationTaskDto
	 */
	@Override
    protected void onActionOperationPdfWebView(final Map<String, String> checkParam, OperationTaskDto operationTaskDto) {
        String cmd = checkParam.get(ABookKeys.CMD);

        switch (cmd) {
            case ABookKeys.CMD_INSERT_TASK_REPORT:			// 作業報告の登録
            case ABookKeys.CMD_UPDATE_TASK_REPORT:			// 作業報告の更新
            case ABookKeys.CMD_DELETE_TASK_REPORT:			// 作業報告の削除
			case ABookKeys.CMD_LOCAL_SAVE_TASK_REPORT:			// 一時保存
                getTaskHotspotJSON();
            case ABookKeys.CMD_CANCEL_TASK_REPORT:			// 作業報告のキャンセル
                if(operationTaskDto != null) {
                    updateOperationTaskPosition(operationTaskDto.pdfX, operationTaskDto.pdfY);
                }
                cmdOperationTaskLayout(cmd, checkParam);
                break;
            case ABookKeys.CMD_CHANGE_DISPLAY_STATUS:
                switch (mStatusCode) {
                    case Constant.XWalkWebViewDisplayStatus.InitView:
                        hideOperationTaskLayout();
                        setToolbarVisableForTask(false);
                        break;
                    case Constant.XWalkWebViewDisplayStatus.TaskView:
					case Constant.XWalkWebViewDisplayStatus.ReportPreView:
                        setOperationCurrentLayout(mCurrentPageNumber);
                        String taskKey = checkParam.get(ABookKeys.TASK_KEY);
                        operationTaskLayout.setTaskFormPosition(taskKey, isNormalSize());
                        operationTaskLayout.setTaskCodeBlinkAnimation(taskKey, true);
                        operationTaskLayout.showOperationTaskLayout();
                        if (isNormalSize()) {
                            setToolbarVisableForTask(true);
                        }
                        break;
                    case Constant.XWalkWebViewDisplayStatus.TaskListView:
                        operationTaskLayout.showOperationTaskLayout();
                        if (isNormalSize()) {
                            setToolbarVisableForTask(true);
                        }
                        break;
                }
                break;
            case ABookKeys.CMD_MOVE_PAGE:
                int pageNum = Integer.parseInt(checkParam.get(ABookKeys.PAGE_NUM));

                if (pageNum > 0) {
                    jumpToPage(pageNum - 1);
                    setOperationCurrentLayout(mCurrentPageNumber);
                }
                break;
        }
    }

    private void setOperationCurrentLayout(int currentPageNum) {
        operationTaskLayout.currentLayout = mShowPageLayout.get(currentPageNum);
    }

    // 作業のホットスポットJSONを取得
    private void getTaskHotspotJSON() {
        try {
            String contentPath = ABVEnvironment.getInstance().getTaskPdfDirName(ContentFileExtractor.getInstance().getContentCacheDirWithExtract(operationDto.contentId));
            String hotspots = FileUtil.readTextFile(contentPath + "/" + ABookKeys.TASK_HOTSPOT + ".json");
            mTaskHotspotJSON = new TaskHotspotJSON(hotspots);
        } catch (IOException e) {
            Logger.e(TAG, "read taskHotspot.json failed.", e);
            initError();
            return;
        } catch (OutOfMemoryError e) {
            ABVToastUtil.showMakeText(getApplicationContext(), R.string.OUT_OF_MEMORY, Toast.LENGTH_SHORT);
            Logger.e(TAG, "[OutOfMemoryError]taskHotspot.json", e);
            initError();
            return;
        } catch (JSONException e) {
            Logger.e(TAG, "read taskHotspot.json failed.", e);
            initError();
            return;
        }
    }

    private void createScaleZoomBar() {
        mScaleZoomLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.scale_zoom_toolbar, null);

        RelativeLayout.LayoutParams params = createParam(WC, WC);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        params.setMargins(10, 0, 0, 0);

        mScaleZoomLayout.setVisibility(View.VISIBLE);
        mMainLayout.addView(mScaleZoomLayout, params);

        // 移動・タップの切り替えボタン
		btnMoveOrClickToggleIcon = (ImageButton) mScaleZoomLayout.findViewById(id.btn_move_click_toggle);

		if (isReportEdit()) {
			// 報告の場合
			btnMoveOrClickToggleIcon.setVisibility(View.VISIBLE);
			btnMoveOrClickToggleIcon.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					mMoveTaskFlg = !mMoveTaskFlg;
					if (mMoveTaskFlg) {
						// タップモードのイメージ
						btnMoveOrClickToggleIcon.setImageResource(R.drawable.ic_show_select);
					} else {
						// 移動モードのイメージ
						btnMoveOrClickToggleIcon.setImageResource(R.drawable.ic_show_move);
					}
				}
			});
		} else {
			// 報告（回答）の場合
			btnMoveOrClickToggleIcon.setVisibility(View.INVISIBLE);
		}


        // ピンと作業コードの切替ボタン
		btnPinToggleIcon = (ImageButton) mScaleZoomLayout.findViewById(id.btn_pin_toggle);
		btnPinToggleIcon.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mShowPinFlg = !mShowPinFlg;
				if (mShowPinFlg) {
					// ピン表示モードの場合、以下のイメージでセット
					// 作業コードモードのイメージ
					btnPinToggleIcon.setImageResource(R.drawable.ic_show_directions_button);
					// 非表示ボタンをピン非表示のイメージ
					btnHideTaskDirectBtn.setImageResource(R.drawable.ic_hidden_show_pin_button);
				} else {
					// 作業コード表示モードの場合、以下のイメージでセット
					// ピンモードのイメージ
					btnPinToggleIcon.setImageResource(R.drawable.ic_show_pin_button);
					// 非表示ボタンを作業コード非表示のイメージ
					btnHideTaskDirectBtn.setImageResource(R.drawable.ic_hidden_show_directions_button);
				}
				changeTaskMainIcon(mShowPinFlg);
			}
		});

		btnPinToggleIcon.setVisibility(View.VISIBLE);
        btnHideTaskDirectBtn = (ImageButton) mScaleZoomLayout.findViewById(R.id.btn_hide_task_direct);
        btnHideTaskDirectBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    hideTaskDirect(true);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    hideTaskDirect(false);
                }
                return true;
            }
        });
        btnHideTaskDirectBtn.setVisibility(View.VISIBLE);

        btnScaleZoomPlus = (ImageButton) mScaleZoomLayout.findViewById(R.id.btn_scale_zoom_plus);
        btnScaleZoomPlus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setScaleZoomInOut(true);
            }
        });
        btnScaleZoomPlus.setVisibility(View.VISIBLE);

        btnScaleZoom03 = (ImageButton) mScaleZoomLayout.findViewById(R.id.btn_scale_zoom_03);
        btnScaleZoom03.setVisibility(View.GONE);

        btnScaleZoom02 = (ImageButton) mScaleZoomLayout.findViewById(R.id.btn_scale_zoom_02);
        btnScaleZoom02.setVisibility(View.GONE);

        btnScaleZoom01 = (ImageButton) mScaleZoomLayout.findViewById(R.id.btn_scale_zoom_01);
        btnScaleZoom01.setVisibility(View.VISIBLE);

        btnScaleZoomMinus = (ImageButton) mScaleZoomLayout.findViewById(R.id.btn_scale_zoom_minus);
        btnScaleZoomMinus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setScaleZoomInOut(false);
            }
        });
        btnScaleZoomMinus.setVisibility(View.VISIBLE);
    }

    private void createOperationTaskLayout(ZoomRelativeLayout rootLayout, int pageNumber, boolean configChangedFlg) {
        if (operationTaskLayout == null) {
            operationTaskLayout = new OperationTaskLayout(this, getContentId(), linkUrl, isNormalSize());
            operationTaskLayout.setVisibility(View.INVISIBLE);
        }

        mMainLayout.removeView(operationTaskLayout);
        mMainLayout.addView(operationTaskLayout);

        List<OperationTaskDto> tasks = mTaskHotspotJSON.getPageTasks(pageNumber);
        operationTaskLayout.addAllOperationTaskIcon(rootLayout, tasks);

		//画面回転の時
		if (configChangedFlg && !isNormalSize()) {
			operationTaskLayout.currentLayout = rootLayout;
			RelativeLayout.LayoutParams params;
			DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
			int halfWidth = (int) (displayMetrics.density * OperationTaskLayout.HALF_WIDTH);
			int screenWidth = displayMetrics.widthPixels;
			params = createParam(halfWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
			params.addRule(operationTaskLayout.getAlignOfTaskLayer());
			operationTaskLayout.setTaskCodeBlinkAnimation();
			operationTaskLayout.setLayoutParams(params);
			setOperationTaskViewStatus(isOpenedOperationTask);
		}
	}

    public void setCurrentOperationTask(OperationTaskDto operationTaskDto) {
        operationTaskLayout.currentTaskDto = operationTaskDto;
    }

    public void showOperationTaskLayout(ZoomRelativeLayout layout, OperationTaskDto operationTaskDto, float clickX) {
        operationTaskLayout.showTaskForm(layout, mXWalkOpenType, operationTaskDto, isNormalSize(), clickX);
		// 拡大・縮小・切替ボタンの非表示
		mScaleZoomLayout.setVisibility(View.INVISIBLE);
        isOpenedOperationTask = true;
    }

    public void cmdOperationTaskLayout(String cmd, Map<String, String> checkParam) {
        String taskKey = checkParam.get(ABookKeys.TASK_KEY);
        String taskCode = "";

        // 作業報告レベル
        int taskReportLevel = Integer.parseInt(checkParam.get(ABookKeys.TASK_REPORT_LEVEL));

        // フォームが閉じられたと見做すので、以下の処理を行う
        isOpenedOperationTask = false;
		// 拡大・縮小・切替ボタンの表示
		mScaleZoomLayout.setVisibility(View.VISIBLE);

        if (operationTaskLayout.currentLayout != null && !StringUtil.isNullOrEmpty(taskKey)) {
            switch(cmd){
                	// #32782 指示者テーブル関連削除 start
				case ABookKeys.CMD_INSERT_TASK_REPORT:
				case ABookKeys.CMD_UPDATE_TASK_REPORT:
				case ABookKeys.CMD_LOCAL_SAVE_TASK_REPORT:		// 一時保存

					if (taskReportLevel == Constant.TaskReportLevel.ReportType) {
						JSONObject hotspot = new JSONObject(checkParam.get(ABookKeys.HOT_SPOT));

						taskCode = hotspot.getString(ABookKeys.TASK_CODE);

						operationTaskLayout.setIconStatus(taskKey, true);
						operationTaskLayout.currentTaskDto.taskKey = taskKey;
						operationTaskLayout.currentTaskDto.taskCode = taskCode;
						operationTaskLayout.currentTaskDto.isFinished = operationTaskLayout.isTaskFinished(taskKey);
						operationTaskLayout.addOperationTaskIcon(operationTaskLayout.currentLayout, operationTaskLayout.currentTaskDto);
						//hideOperationTaskLayout();
					} else {
						operationTaskLayout.setIconStatus(taskKey, false);
					}

					break;
				case ABookKeys.CMD_DELETE_TASK_REPORT:
					if (taskReportLevel == Constant.TaskReportLevel.ReportType) {
						operationTaskLayout.setIconStatus(taskKey, true);
					} else {
						operationTaskLayout.setIconStatus(taskKey, false);
					}
					break;
                default:
                    operationTaskLayout.setIconStatus(taskKey, false);
                    break;
			}
			// 一時保存コマンド以外は、operationTaskLayout.currentTaskDtoをリセットする
			if (!cmd.equals(ABookKeys.CMD_LOCAL_SAVE_TASK_REPORT)) {
				operationTaskLayout.currentTaskDto = null;
			}
        }
    }

	/**
	 * 作業一覧レイアウトを非表示処理
	 */
	public void hideOperationTaskLayout() {
		// 拡大・縮小・切替ボタンの表示
		mScaleZoomLayout.setVisibility(View.VISIBLE);

		operationTaskLayout.setVisibility(View.INVISIBLE);
        operationTaskLayout.currentTaskDto = null;
        setOperationTaskViewStatus(false);
    }

    public void updateOperationTaskPosition(float pdfX, float pdfY) {
        operationTaskLayout.currentTaskDto.pdfX = pdfX;
        operationTaskLayout.currentTaskDto.pdfY = pdfY;

    }

    public void updateOperationTaskPosition() {
        ABookCheckWebViewHelper.getInstance().doABookCheckParamPdf(mOperationId, operationTaskLayout.currentTaskDto, mContentPath);
        mTaskHotspotJSON.setTaskPosition(operationTaskLayout.currentTaskDto);

        if (!isOpenedOperationTask) {
            setCurrentOperationTask(null);
        }
    }

    public int getOperationReportUpdateType() {
        return mEnableReportHistory;
    }

    /**
     * 指示アイコン非表示
     */
    public void hideTaskDirect(boolean isHide) {
        //(mShowPageLayout.get(mCurrentPageNumber)).setVisibility(isHide ? View.INVISIBLE : View.VISIBLE);
        setOperationCurrentLayout(mCurrentPageNumber);
        operationTaskLayout.toggleAllTaskCode(isHide);
        mPageScrollView.setFixFlag(isHide);
        isOpenedOperationTask = isHide;
    }

	/**
	 * 作業のアイコンをピン・作業コードに切替
	 * @param isShowPin
	 */
	public void changeTaskMainIcon(boolean isShowPin) {
		// mShowPageLayoutに存在するzoomLayoutの子ビューであるActionOperationTaskPin、ActionOperationTaskCodeを全て削除して、新たにアイコンを再描画する
		for (int i = 0; i < mShowPageLayout.size(); i++) {
			int key = mShowPageLayout.keyAt(i);
			ZoomRelativeLayout zoomRelativeLayout = mShowPageLayout.get(key);
            for (int j = zoomRelativeLayout.getChildCount() - 1; j >= 0; j--) {
                View view = zoomRelativeLayout.getChildAt(j);
                if (view instanceof ActionOperationTaskCode) {
                    ((ActionOperationTaskCode) view).stopAnimation();
                } else if (view instanceof ActionOperationTaskPin) {
                    ((ActionOperationTaskPin) view).stopAnimation();
                }

                if (view instanceof ActionOperationTaskCode || view instanceof ActionOperationTaskPin) {
                    // ピン、作業コードのビューを削除
                    zoomRelativeLayout.removeView(view);
                }
            }
            List<OperationTaskDto> tasks = mTaskHotspotJSON.getPageTasks(i);
			operationTaskLayout.addAllOperationTaskIcon(zoomRelativeLayout, tasks);
		}
	}

    @Override
    public void showTaskList() {
		// 拡大・縮小・切替ボタンの非表示
		mScaleZoomLayout.setVisibility(View.INVISIBLE);

        operationTaskLayout.showTaskList(mCurrentPageNumber, isNormalSize());
    }

    public void setOperationTaskViewStatus(boolean isOpened) {
        isOpenedOperationTask = isOpened;

        if (isOpened) {
            setToolbarVisable(false);
            mPageScrollView.setFixFlag(true);
        } else {
            mPageScrollView.setFixFlag(false);
        }
    }

    public void commonProgressChanged(int progress) {
        setVisbilityProgress(true);
        if (progress >= 100) {
            setVisbilityProgress(false);
        }
    }

    protected void setVisbilityProgress(boolean visible) {
        if (visible) {
            m_progress.setVisibility(View.VISIBLE);
        } else {
            m_progress.setVisibility(View.GONE);
        }
    }

    public boolean getOpenedProjestTask() {
        return isOpenedOperationTask;
    }

    public long getOperationId() {
        return mOperationId;
    }

    public void setScaleZoomInOut(boolean zoomInFlg) {
        ZoomRelativeLayout zoomLayout = mShowPageLayout.get(mCurrentPageNumber);
        float scaleFactor = zoomLayout.getScaleFactor();
        if (zoomInFlg) {
        	if (scaleFactor <= 1.0f) {
				scaleFactor = 2.5f;
			} else if (scaleFactor > 1.0f && scaleFactor <= 2.5f) {
				scaleFactor = IFPDFConst.MAX_SCALE;
			}
		} else {
			if (scaleFactor > 2.5f && scaleFactor <= IFPDFConst.MAX_SCALE) {
				scaleFactor = 2.5f;
			} else if (scaleFactor > 1.0f && scaleFactor <= 2.5f) {
				scaleFactor = 1.0f;
			}
		}

        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int centerX = displayMetrics.widthPixels / 2;
        int centerY = displayMetrics.heightPixels / 2;

        ViewMargin margin = zoomLayout.getContentPageMargin();
        Matrix matrix = new Matrix();
        matrix.postScale(scaleFactor, scaleFactor, centerX, centerY);
        zoomLayout.setZoomMatrix(matrix);
		zoomLayout.changeTaskChildView();

        setToolbarVisable(false);
        mShowPageLayout.get(mCurrentPageNumber).setScaleFactorAndMatrix(scaleFactor);

        setScaleZoomIcon(scaleFactor);
    }

    public void setScaleZoomIcon(float scaleFactor) {
        if (scaleFactor > 2.5f && scaleFactor <= IFPDFConst.MAX_SCALE) {
            btnScaleZoom03.setVisibility(View.VISIBLE);
            btnScaleZoom02.setVisibility(View.GONE);
            btnScaleZoom01.setVisibility(View.GONE);
            mPageScrollView.setFixFlag(true);
            mPageScrollView.setZoomingFlag(true);
        } else if (scaleFactor > 1.0f && scaleFactor <= 2.5f) {
            btnScaleZoom03.setVisibility(View.GONE);
            btnScaleZoom02.setVisibility(View.VISIBLE);
            btnScaleZoom01.setVisibility(View.GONE);
            mPageScrollView.setFixFlag(true);
            mPageScrollView.setZoomingFlag(true);
        } else {
            btnScaleZoom03.setVisibility(View.GONE);
            btnScaleZoom02.setVisibility(View.GONE);
            btnScaleZoom01.setVisibility(View.VISIBLE);
            mPageScrollView.setFixFlag(isOpenedOperationTask);
            mPageScrollView.setZoomingFlag(false);
        }
    }
}

