package jp.agentec.abook.abv.ui.viewer.activity;

import java.sql.Timestamp;
import java.util.ArrayList;

import jp.agentec.abook.abv.bl.acms.client.json.content.ContentJSON;
import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.CommonExecutor;
import jp.agentec.abook.abv.bl.common.exception.NetworkDisconnectedException;
import jp.agentec.abook.abv.bl.common.log.Logger;
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.download.ContentDownloader;
import jp.agentec.abook.abv.bl.download.ContentZipDownloadNotification;
import jp.agentec.abook.abv.bl.dto.ContentDto;
import jp.agentec.abook.abv.bl.dto.EnqueteDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.EnqueteLogic;
import jp.agentec.abook.abv.cl.util.ContentLogUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.activity.ABVContentViewActivity;
import jp.agentec.abook.abv.ui.common.util.ABVToastUtil;
import jp.agentec.abook.abv.ui.common.view.ABVPopupListWindow;
import jp.agentec.abook.abv.ui.home.helper.ActivityHandlingHelper;
import jp.agentec.adf.util.DateTimeUtil;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

//TODO: later 遠隔連動関連はContentView,NoPdfViewと共通しているので要集約
public class EnqueteWebViewActivity extends ABVContentViewActivity {
	private static final String TAG = "EnqueteWebViewActivity";
	public static final int HALF_WIDTH = 340;
	/** Called when the activity is first created. */
	private ProgressBar m_progress;

	private ImageButton btnFontSmall;
	private ImageButton btnFontBig;
	
	private Button closeButton;
	private Button btnLinkOriginalBack;
	private Button historyListBtn;
	private ImageButton mBtnRemoteStart;
	private ImageButton promoteBtn;
	private ImageButton pauseBtn;
	private ImageButton reloadButton;
	private ImageButton downloadButton;
	
	private int objectLogId;
	private boolean mPageFinishedFlg;

	private WebView webView;

	private Double mLatitude;
	private Double mLongitude;
	private JsInf jsInf = new JsInf();
	private boolean pageStart;
	
	private String mContentType;
	private long mContentId;
	private long abObjectId;
	private long abEnqueteId; 
	private int replyLimit;
	private int sendResult;
	private int showResult;
	@Override
	public void onCreate(Bundle savedInstanceState) {
        Logger.i(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); // タイトルバー非表示
		setContentView(R.layout.ac_enquete_webview);

		// ***** 引数の取得
		Intent intent = getIntent();
		if (objectId != -1 || ABVEnvironment.getInstance().disableLogSend) {
			// アクションとして起動された場合, Streaming表示の場合ログは記録しない
			readingLogFlg = false;
		}
		objectLogId = intent.getIntExtra("objectLogId", -1);
		boolean isDownloadable = intent.getBooleanExtra("isDownloadable", false);
		boolean isUpdate = intent.getBooleanExtra("isUpdate", false);
		
		final String url = intent.getStringExtra("LINKURL"); // LinkURL
		m_progress = (ProgressBar) findViewById(R.id.refresh_prog);
		
		mContentType = intent.getStringExtra("contentType");

		mContentId = intent.getLongExtra("contentId", -1);
		this.abEnqueteId = intent.getLongExtra("abEnqueteId", -1);//actionInfoJSON.getEnqueteId();
		this.abObjectId = 0; // objectId = 0 intent.getLongExtra("abObjectId", 0);//actionInfoJSON.getObjectId();
		// 表示位置リンク
		final String questionNo = "0";//intent.getStringExtra("questionNo");//actionInfoJSON.getQuestionNo();

		this.replyLimit = intent.getIntExtra("replyLimit", -1);// 0:無制限 1:一回
		this.showResult = intent.getIntExtra("showResult", -1);// 1：採点表示
		this.sendResult = intent.getIntExtra("sendResult", -1);// 1：結果送信

		// ***** WebViewセット
		webView = (WebView) findViewById(R.id.webView3);
		webView.setVerticalScrollbarOverlay(true); // スクロールバー部分の隙間を消す
		// webView.setWebViewClient(new WebViewClient());

		// //ブラウザの描画領域を対象としたイベントをフック
		WebSettings settings = webView.getSettings();
		settings.setSupportMultipleWindows(true); // 新しいウィンドウを開くイベントを取得する
		settings.setLoadsImagesAutomatically(true); // イメージを自動的にロードする
		settings.setBuiltInZoomControls(true); // ズーム機能を有効にする
		settings.setSupportZoom(true); // ズーム機能を有効にする
		settings.setJavaScriptEnabled(true); // JavaScriptを有効にする
		settings.setLoadWithOverviewMode(true); // 画面の横幅にページの横幅を合わせる
		settings.setUseWideViewPort(true); // 画面の横幅にページの横幅を合わせる
		//noinspection deprecation(API18から非推奨になった。無視)
		settings.setPluginState(PluginState.ON); // 「EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up.」のエラー対応（あまり効果ない？）
		settings.setDomStorageEnabled(true); // WebStorage有効化
		settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		// webView.loadDataWithBaseURL("", url2, "text/html", "UTF-8", "");
		//ターゲットバージョン30以上からデフォルトがfalseに設定されている問題対応
		settings.setAllowFileAccess(true);

		final RelativeLayout fl = (RelativeLayout) findViewById(R.id.frameTopbar);

		// ***** 戻るボタン
		closeButton = (Button) findViewById(R.id.closeBtn);
		closeButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finishActivity();
			}
		});

		// ***** リンク元コンテンツへ戻るボタン
		btnLinkOriginalBack = (Button) findViewById(R.id.btn_link_original_back);
		btnLinkOriginalBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				goToBack();
			}
		});

		boolean isFromHomeMenu = intent.getIntExtra("pageNumber", -1) == -1;
		subMenuBtn = (ImageButton) findViewById(R.id.btn_sub_menu);
		historyListBtn = (Button) findViewById(R.id.btn_history_list);
		if (isFromHomeMenu) {
			closeButton.setBackgroundResource(R.drawable.btn_home);
			
			historyListBtn.setVisibility(View.GONE);
			subMenuBtn.setVisibility(View.GONE);
			
			historyListBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					showHistoryList(v);
				}
			});

			subMenuBtn.setOnClickListener(new OnClickListener() {

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

					ArrayList<String> menuNameList = new ArrayList<>();
					final boolean isExist = contentLogic.isExsitContentFavorite(getContentId());
					if (isExist) {
						menuNameList.add(getRString(R.string.remove_favorite_content));
					} else {
						menuNameList.add(getRString(R.string.add_favorite_content));
					}

					mShowedPopupWindow.setRepresentNames(menuNameList);
					mShowedPopupWindow.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							switch (position) {
								case 0 :
									// お気に入り
									contentLogic.setFavoriteContent(getContentId(), !isExist);
									break;
								default :
									break;
							}
							mShowedPopupWindow.dismiss();
						}
					});

					mShowedPopupWindow.showAsDropDown(v);
				}
			});

		} else {
			historyListBtn.setVisibility(View.GONE);
		}

		subMenuBtn.setVisibility(View.GONE);
		
		final ImageButton btnWebClose = (ImageButton) findViewById(R.id.btnWebClose);
		btnWebClose.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (fl.getVisibility() == View.VISIBLE) {
					fl.setVisibility(View.GONE);
					//noinspection deprecation(API16から非推奨になった。無視)
					btnWebClose.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_webview_open));
				} else {
					fl.setVisibility(View.VISIBLE);
					//noinspection deprecation(API6から非推奨になった。無視)
					btnWebClose.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_webview_close));
				}
			}
		});

		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {

				setVisbilityProgress(true);
				if (newProgress >= 100) {
					setVisbilityProgress(false);
				}
			}
		});

		webView.setWebViewClient(new WebViewClient() {
			//오서링 설문 지정시 해당 설문으로 이동수정
			@Override
			public void onPageFinished(WebView view, String url) {
				Logger.d(TAG, "abQuestionNo : " + questionNo);
                if (pageStart) {
                    //クイズで回答可能回数1回設定した場合：クイズをやったことを確認するため答えたクイズをデータベースに保存する。
                    if (mContentType.equals(ContentJSON.KEY_EXAM_TYPE) && replyLimit == 1) {
                        EnqueteLogic enqueteLogic = AbstractLogic.getLogic(EnqueteLogic.class);
                        EnqueteDto dto = new EnqueteDto();
                        dto.abObjectId = abObjectId;
                        dto.abEnqueteId = abEnqueteId;
                        dto.contentId = mContentId;
                        dto.param = "";
                        dto.replyDateStr = DateTimeUtil.getCurrentTimestamp();
                        dto.replyFlg = true;//replyFlg = trueの場合：新着更新ボタンを押した時にも送信しない。
                        enqueteLogic.insertEnquete(dto);
                    }
                } else {
                    webView.loadUrl("javascript:setResultSendType(true)");
                    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                        webView.loadUrl("javascript:setAndroid403(true)");
                    }

                    if (!questionNo.equals("0")) {
                        webView.loadUrl("javascript:initDisplay('" + questionNo + "')");
                    }

                    pageStart = true;

                }
				callFixWidth();
				//試験の場合：結果送信しない設定した場合
				if (mContentType.equals(ContentJSON.KEY_EXAM_TYPE) && sendResult == 0) {
					callChangeButton();
				}
			}

			@Override
			public void onScaleChanged(WebView view, float oldScale, float newScale) {
				super.onScaleChanged(view, oldScale, newScale);
				callFixWidth();
			}

			protected void callFixWidth() {
				int htmlInputWidth = (int) (HALF_WIDTH * 0.7) ; 
				Logger.d(TAG, "htmlInputWidth : " + htmlInputWidth);
				StringBuffer javascript = new StringBuffer();
				javascript.append("javascript:jQuery(\":input:text\").not(\".notResize\").css(\"width\",\"" + htmlInputWidth + "px\").css(\"vertical-align\",\"middle\");");
				javascript.append("javascript:jQuery(\"textarea\").not(\".notResize\").css(\"width\",\"" + htmlInputWidth + "px\").css(\"font-size\",\"16px\");");
				javascript.append("javascript:jQuery(\":text\").not(\".notResize\").css(\"width\",\"" + htmlInputWidth + "px\");");

				webView.loadUrl(javascript.toString());
			}
			
			protected void callChangeButton() {
				Logger.d(TAG, "changeButton : ");
				webView.loadUrl("javascript:changeButton()");
			}
			
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				boolean isGotoNextScreen = true;////試験の場合：オフライン時 結果送信する場合且つオフライン時結果送信しない場合：結果画面に進ままない。
				boolean show_result = true; //試験の場合結果採点表示
				boolean send_result = true; //試験の場合：結果送信

				//試験の場合：結果画面非表示設定した場合：別の画面に呼び出す
				if (mContentType.equals(ContentJSON.KEY_EXAM_TYPE) && showResult == 0) {
					show_result = false;
				}

				//試験の場合：結果送信しない設定した場合
				if (mContentType.equals(ContentJSON.KEY_EXAM_TYPE) && sendResult == 0) {
					send_result = false;
				}

				if (url.startsWith("abook-api")) {
					if (ContentViewActivity.enqueteMap.containsKey(abEnqueteId)) {
						//hashmap에 해당 앙케이트 아이디의 값 삭제
						ContentViewActivity.enqueteMap.remove(abEnqueteId);
					}
					Uri uri = Uri.parse(url);
					String param = uri.getQuery();
					Timestamp ts = DateTimeUtil.getCurrentTimestamp();
					boolean enResult;
					EnqueteLogic enqueteLogic = AbstractLogic.getLogic(EnqueteLogic.class);
					EnqueteDto dto = new EnqueteDto();
					dto.abObjectId = abObjectId;
					dto.abEnqueteId = abEnqueteId;
					dto.contentId = mContentId;
					dto.param = param;
					dto.replyDateStr = ts;

					if (send_result) {
						try {
							//앙케이트 결과 값을 서버에 송신한다.
							//cs 를 넘겨받아서 처리
							enResult = enqueteLogic.enqueteReply(dto.contentId, dto.abObjectId, ts, dto.param);

							//성공시 reply_flg 값을 true
							dto.replyFlg = enResult;

						} catch (NetworkDisconnectedException ne) {
							dto.replyFlg = false;
							Logger.e(TAG, "enqueteReply error", ne);

							//オフライン時試験結果送信しないサービスオプション設定した場合：アラート出す。次の画面に移動しない
							if (mContentType.equals(ContentJSON.KEY_EXAM_TYPE) && !ABVDataCache.getInstance().serviceOption.isTransmitExamAtOffline()) {
								ABVToastUtil.showMakeText(getApplicationContext(), R.string.exam_message, Toast.LENGTH_LONG);
								show_result = false;
								isGotoNextScreen = false;
							}

						} catch (Exception e) {
							dto.replyFlg = false;
							Logger.e(TAG, "enqueteReply error", e);
							ABVToastUtil.showMakeText(getApplicationContext(), R.string.ERROR, Toast.LENGTH_LONG);
						}
					} else {
						//試験結果送信しない設定した場合且つ回答可能回数1回設定した場合：試験をやったことを確認
						dto.replyFlg = true;
					}

					if (isGotoNextScreen) {
						//アンケートの場合又は試験の場合：データベースに保存する。
						enqueteLogic.insertEnquete(dto);
						if (show_result) {
							//앙케이트 결과 송신 후 showEnd 호출
							webView.loadUrl("javascript:showEnd()");
						} else {
							webView.loadUrl("javascript:showMsgs()");
						}
					}
				}
				return true;
			}
		});

		// webView.postUrl(url,EncodingUtils.getBytes("", "utf-8"));
		Logger.d(TAG, "loadUrl: " + url);
		webView.loadUrl(url);
		
		btnFontSmall = (ImageButton)findViewById(R.id.font_small);
		btnFontSmall.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setFontSmall();
			}
		});
		
		btnFontSmall.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return false;
			}
		});

		
		btnFontBig = (ImageButton)findViewById(R.id.font_big);
		btnFontBig.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setFontBig();
			}
		});
		
		btnFontBig.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return false;
			}
		});
		
		reloadButton = (ImageButton) findViewById(R.id.btn_reload);
		reloadButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Logger.d(TAG, "ReloadUrl");
				if (mLatitude != null && mLongitude != null) {
					webView.loadUrl(url + "&reload=true&mLatitude=" + mLatitude + "&mLongitude=" + mLongitude);
				}
				else {
					webView.loadUrl(url + "&reload=true");
				}
			}
		});
		
		downloadButton = (ImageButton) findViewById(R.id.btn_download);
		downloadButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Logger.d(TAG, "Click download");
				try {
					downloadButton.setEnabled(false);
					ContentDownloader.getInstance().download(mContentId);
					ABVToastUtil.showMakeText(getApplicationContext(), R.string.download_start, Toast.LENGTH_SHORT);
				} catch (Exception e) {
					Logger.e(TAG, "Download failed." ,e);
					downloadButton.setEnabled(true);
					handleErrorMessageToast(e);
				}
			}
		});
		if (isDownloadable) {
			downloadButton.setVisibility(View.VISIBLE);
			if (isUpdate) {
				downloadButton.setBackgroundResource(R.drawable.btn_update);
			}
			else {
				downloadButton.setBackgroundResource(R.drawable.btn_download);
			}
		}
		

		mBtnRemoteStart = (ImageButton) findViewById(R.id.btn_remote_start);
        mBtnRemoteStart.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				meetingManager.setPaused(false);
				configureRemote();
			}
		});
        
		exitMeetingBtn = (ImageButton) findViewById(R.id.btn_exitMeeting);
		exitMeetingBtn.setOnClickListener(new View.OnClickListener() {
			@Override
            public void onClick(View v) {
				Logger.v(TAG, "exit onClick");
				showMeetingExitDialog();
			}
		});

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

		pauseBtn = (ImageButton) 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(isLinkedContent) {
			ContentDto contentDto = AbstractDao.getDao(ContentDao.class).getContent(contentId);
			if (ContentJSON.KEY_ENQUETE_TYPE.equals(contentDto.contentType) || ContentJSON.KEY_EXAM_TYPE.equals(contentDto.contentType)) {
				closeButton.setBackgroundResource(R.drawable.btn_first_back);
				btnLinkOriginalBack.setVisibility(View.VISIBLE);
				subMenuBtn.setVisibility(View.GONE);
				historyListBtn.setVisibility(View.GONE);
				reloadButton.setVisibility(View.GONE);
				downloadButton.setVisibility(View.GONE);
				mBtnRemoteStart.setVisibility(View.GONE);
				exitMeetingBtn.setVisibility(View.GONE);
				promoteBtn.setVisibility(View.GONE);
				pauseBtn.setVisibility(View.GONE);
			}
		} else {
			configureRemote();
		}
	}

	private void removeNewFlag() {
		// Newフラグ更新
		ContentDto contentDto = AbstractDao.getDao(ContentDao.class).getContent(mContentId);
		if (contentDto.newFlg) {
			contentDto.newFlg = false;
			contentDao.updateContent(contentDto, false);
		}
	}

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

	private class JsInf {
		@JavascriptInterface
		public void existSetLocation(String ret) {
			Logger.d(TAG, "existSetLocation=%s", ret);
			if (ret != null && ret.equals("true")) { // setLocationメソッドが存在する場合、ページ読み込み完了とみなす
				mPageFinishedFlg = true;
			}
			else { // 存在しない場合、ページ読み込み未完了とみなし１秒後に再度呼出しを繰り返す
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
					    callExistsSetLocation();
					}
				}, 1000);
			}
		}
		
		@JavascriptInterface
		public void existSendLog(String ret) {
			Logger.d(TAG, "existSendLog=%s", ret);
			if (ret != null && ret.equals("true")) {
				runOnUiThread(new Runnable() { // sendLogメソッドが存在する場合、呼び出す
					@Override
					public void run() {
						try {
							webView.loadUrl("javascript:sendLog()");
						} catch (Exception e) {
							Logger.e(TAG, "javascript:sendLog error. " + e.toString());
						}
					}
				});
			}
			else {
				finishActivity();
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		Logger.d(TAG, "onDestroy");
		finishWebView();
		super.onDestroy();
	}

	public void finishWebView() {
		CommonExecutor.execute(new Runnable() {
			@Override
            public void run() {
				for (int i = 0; i < 100; i++) {
					if (mPageFinishedFlg) {
						break;
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
					}
				}
				handler.post(new Runnable() {
					@Override
					public void run() {
						if (webView != null) {
							ViewGroup parent = (ViewGroup) webView.getParent();
							if (parent != null) {
								parent.removeView(webView);
							}	
							webView.removeAllViews();
							webView.destroy();
							webView = null;
						}
					}
				});
			}
        });
	}
	
	@Override
	public void onDetachedFromWindow() {
		Logger.d(TAG, "onDetachedFromWindow");
	    super.onDetachedFromWindow();
		finishWebView();
	}

	@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
    		finishActivity();
		} else {
			return super.onKeyUp(keyCode, event);
		}
		return false;
	}

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

	@Override
	public void onResume() {
		Logger.i(TAG, "onResume");
		super.onResume();
		if (objectLogId != -1) {
			ContentLogUtil.getInstance().resumeObjectLog(getContentId(), objectLogId);
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
    	webView.stopLoading();
		if (objectLogId != -1) {
			ContentLogUtil.getInstance().endObjectLog(getContentId(), objectLogId);
		}
	}
	
	@Override
	public void configureRemote() {
		if (objectId == -1 && meetingManager.isSubscribed()) {
			closeButton.setVisibility(View.INVISIBLE);
			historyListBtn.setVisibility(View.INVISIBLE);
			if (meetingManager.isPaused()) {
				mBtnRemoteStart.setVisibility(View.VISIBLE);
				pauseBtn.setVisibility(View.GONE);
				exitMeetingBtn.setVisibility(View.GONE);
				promoteBtn.setVisibility(View.GONE);
			}
			else {
				subMenuBtn.setVisibility(View.GONE);
				mBtnRemoteStart.setVisibility(View.GONE);
				pauseBtn.setVisibility(View.VISIBLE);
				exitMeetingBtn.setVisibility(View.VISIBLE);
				promoteBtn.setVisibility(View.VISIBLE);
			}
		}
		else {
			closeButton.setVisibility(View.VISIBLE);
			if (objectId == -1) {
				historyListBtn.setVisibility(View.VISIBLE);
			}
			else {
				historyListBtn.setVisibility(View.GONE);
				subMenuBtn.setVisibility(View.GONE);
			}
			mBtnRemoteStart.setVisibility(View.GONE);
			if (meetingManager.isSendable()) { // 会議室退室ボタン表示
				exitMeetingBtn.setVisibility(View.VISIBLE);
			}
			pauseBtn.setVisibility(View.GONE);
			promoteBtn.setVisibility(View.GONE);
		}
		
		if (meetingManager.isConnected() && meetingManager.isOwner()) {
			webView.setOnTouchListener(new OnTouchListener() {
				boolean showCount = false;
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					Logger.d(TAG, "onTouch showCount=" + showCount);
					showCount = !showCount;
					setMeetingParticipantCount(showCount, findViewById(android.R.id.content));
					v.performClick();
					return false;
				}
			});
		}
		historyListBtn.setVisibility(View.GONE);
	}

	@Override
	public void onDownloadingContentZip(ContentZipDownloadNotification notification) { // Streaming表示でダウンロードが完了した場合
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				ABVToastUtil.showMakeText(getApplicationContext(), R.string.download_success, Toast.LENGTH_SHORT);
				downloadButton.setVisibility(View.GONE);
			}
		});
	}

	private void callExistsSetLocation() { // setLocation functionがjavascriptに定義されているかどうかを調べる（結果はexistSetLocationメソッドにコールバック）
		runOnUiThread(new Runnable() {
		    @Override
            public void run() {
		        webView.loadUrl("javascript:android.existSetLocation(typeof setLocation == 'function')");
		    }
		});
	}

	private void callExistsSendLog() { // setLocation functionがjavascriptに定義されているかどうかを調べる（結果はexistSendLogメソッドにコールバック）
		runOnUiThread(new Runnable() {
		    @Override
            public void run() {
		    	webView.loadUrl("javascript:android.existSendLog(typeof sendLog == 'function')");
		    }
		});
		
		handler.postDelayed(new Runnable() { // 10秒後に終了していない場合に終了
			@Override
			public void run() {
				//noinspection VariableNotUsedInsideIf
				if (webView != null) {
					Logger.w(TAG, "Finish forcibly");
					finishActivity();
				}
			}
		}, 10000);
	}

	public void setFontSmall() {
		webView.loadUrl("javascript:defaultFontSize()");
		btnFontSmall.setBackgroundResource(R.drawable.btn_small_font_on_blue);
		btnFontBig.setBackgroundResource(R.drawable.btn_big_font_off_blue);
	}

	public void setFontBig() {
		webView.loadUrl("javascript:largeFontSize()");
		btnFontSmall.setBackgroundResource(R.drawable.btn_small_font_off_blue);
		btnFontBig.setBackgroundResource(R.drawable.btn_big_font_on_blue);
	}

}