	var ELEMENT_NODE  = 1;
	var TEXT_NODE     = 3;
	var loginStatusForSettingMenu = false;
	// 板選択時のスレッド表示数
	var THREAD_LIST_NUM = 3;
	// 板ポップアップ時のスレッド表示数
	var THREAD_MAX_NUM = 10;
	// 番組数
	var CHANNEL_NUM = 7;
	// 表示設定ウィンドウ
	var propWin = null;
	// URL履歴ウィンドウ
	var historyWin = null;
	// 時計用タイマーオブジェクト
	var hTimer = null;
	// スレッド用タイマーオブジェクト
	var tTimer = null;
	// 板用タイマーオブジェクト
	var bTimer = null;
	// 広告バナータイマーオブジェクト
	var adTimer = null;
	// スレッドスクロールタイマーオブジェクト
	var scTimer = null;
	//自動消滅レイヤータイマー
	var autoProgramListHiddenTimer = null;
	var autoTitleListHiddenTimer = null;
	var autoRelationHiddenTimer = null;
	var autoTypePreviewHiddenTimer = null;
	var systemMessageClearTimer = null;
	//
	//透過メニュー制御用オブジェクト
	var menuCtrl = null;
	var statisticMenuCtrl = null;
	// 
	var scTimeout = null;
	// アクティブユーザ用タイマーオブジェクト
	var activationTimer = null;
	// 即時アクティブユーザ更新フラグ
	var immediateUpdate = true;
	// メッセージ送信中かそうでないか
	var sendFlg = false;
	var threadLen = 0;
	var xmlfilename = "";
	// レス数
	var resNum = 0;
	// スレッドDOM
	var threadDom = null;
	// 
	var threadArray = new Array();
	// スクロールフラグ
	var scrollFlg = true;
	// スレッド文字色
	var font_color = "#000000";
	// スレッド背景色
	var bg_color = "#FFFFFF";
	// フォントサイズ
	var threadFontSize = 9;
	var threadFontFamily = "";
	var today  = 0;
	var chIdList = new Array("1ch","3ch","4ch","6ch","8ch","10ch","12ch");
	var chNameList = new Array("livenhk","liveetv","liventv","livetbs","livecx","liveanb","livetx");
	var chNamejpList = new Array("番組ch(NHK)","番組ch(教育)","番組ch(NTV)","番組ch(TBS)","番組ch(フジ)","番組ch(朝日)","番組ch(TX)");
	var chNamejpLongList = new Array("NHK総合","NHK教育","日テレ","TBS","フジテレビ","テレ朝","テレ東");
	var nowFocusCh = null;
	var boardmainScrollval=0;
	var lastScrollPosition = -1;
	var leftMenuWidth = "190px";
	var leftMenuCornerSize = "4px";
	var leftMenuBlurTopImg = "images/t_.gif";
	var leftMenuBlurLeftTopImg = "images/lt_.gif";
	var leftMenuBlurRightTopImg = "images/rt_.gif";
	var leftMenuBlurBottomImg = "images/b_.gif";
	var leftMenuBlurLeftBottomImg = "images/lb_.gif";
	var leftMenuBlurRightBottomImg = "images/rb_.gif";
	var leftMenuBlurLeftImg = "images/l_.gif";
	var leftMenuBlurRightImg = "images/r_.gif";
	var leftMenuBlurTitleHeight = "30px";
	var defaltBlurBgColor   = "#E9E9E9";
	var BlurBgColor = 0x161616;
	var defaltFocusBgColor  = "#FFFFFF";
	var leftMenuBlurBgColor = "#E9E9E9";
	var leftMenuBlurSpace = "8px";
	var leftMenuBlurSpaceBgColor = "#FFFFFF";
	var leftMenuFocusTopImg = "images/t.gif";
	var leftMenuFocusLeftTopImg = "images/lt.gif";
	var leftMenuFocusRightTopImg = "images/rt.gif";
	var leftMenuFocusBottomImg = "images/b.gif";
	var leftMenuFocusLeftBottomImg = "images/lb.gif";
	var leftMenuFocusRightBottomImg = "images/rb.gif";
	var leftMenuFocusLeftImg = "images/l.gif";
	var leftMenuFocusRightImg = "images/r.gif";
	var leftMenuFocusTitleHeight = "80px";
	var leftMenuFocusBgColor = "#F9F9F9";

	/* スレッドタイトルリスト */
	var nhk1TitleList = null;
	var nhk3TitleList = null;
	var ntvTitleList  = null;
	var tbsTitleList  = null;
	var cxTitleList   = null;
	var exTitleList   = null;
	var txTitleList   = null;
	var topTitleList  = null;
	var threadTitleList = new Array(CHANNEL_NUM);

	var tmpId = null;
	var initId = null;
	var currentThreadId = null;
	var loginFlg = false;
	var ballooMode = false;
	var mixMode = false;
	var errorCount = 0;
    var _2chUrl = null
	var prevOriginalThreadID = null;
	var barChartData = new Array();
	var resStatistics = new Array();
	var connStatistics = new Array();

	var tmpFontSize = 9;
	var tmpColorSet = '03';
	var threadColorSet = '03';
	var boardMax = false;
	var scrollMaxX = null;
	var agentIE = 0;
	var agentSafari = 0;
	var agentOpera = 0;
	
	var firstTimeSelectThread = true;
	
	//定型ポップアップ
	var _typePreviewPopup = null;

	//スクロールステータス
	var _scrollStatus = false;

	//Flash設定ダイアログ管理
	var _onFLashSettingDialog = false;
	
	if(navigator.userAgent.toUpperCase().indexOf("MSIE") > 0) {
		agentIE = 1;
	}
	if(navigator.userAgent.toUpperCase().indexOf("SAFARI") > 0) {
		agentSafari = 1;
	}
	if(navigator.userAgent.toUpperCase().indexOf("OPERA") > 0) {
		agentOpera = 1;
	}

	var defaultHeight = 830;
	var defaultWidth  = 1080;

	var flash  = null;
	var initFlashInterval = null;
	
	var iphoneSubWindow = null;

	function autoScrollControl() {
		if(flash != null) {
			_scrollStatus = flash.setLogviewMode(_scrollStatus);
			if(_scrollStatus) {
				document.getElementById("offscroll_btn").style.visibility = "hidden"
				document.getElementById("offscroll_btn").style.position = "absolute"
				document.getElementById("onscroll_btn").style.visibility = "visible"
				document.getElementById("onscroll_btn").style.position = "relative"
			}else{
				document.getElementById("onscroll_btn").style.visibility = "hidden"
				document.getElementById("onscroll_btn").style.position = "absolute"
				document.getElementById("offscroll_btn").style.visibility = "visible"
				document.getElementById("offscroll_btn").style.position = "relative"
			}
		}
	}
	
	function initFlash(id) {
		try {
			if(initId == null) {
				return;
			}
			var obj = null;
			if(window[id] != null) {
				obj = window[id];
			} else if(document[id] != null) {
				obj = document[id];
			}
			obj.setURL('./cgi/getthread.php');
			obj.initThread(initId, true);
			flash = obj;
			window.clearInterval(initFlashInterval);
		} catch(e) {
		}
	}
	
	function initModeFromFlash() {
		if(flash != null) {
			if(ballooMode && mixMode) {
				changeMode(1);
			} else if(ballooMode) {
				changeMode(2);
			} else if(mixMode) {
				changeMode(3);
			} else {
				changeMode(1);
			}
		}
	}

	function init(id) {
		_typePreviewPopup = new TypePreview(180, 180, 8, '#101010', '#FEFEFE', 85, 10);
		var propertyPanelLayer = document.getElementById('proppanel');

		resize();
		var fontSize = getCookieValue("font_size");
		var fontFamily = getCookieValue("font_family");
		var colorSet = getCookieValue("color_set");

		var mixModeResume = getCookieValue("mix_mode");
		if(mixModeResume == 'true') {
			mixMode = true;
		}else{
			mixMode = false;
		}
		ballooMode = getCookieValue("balloo_mode") == 'true';
		if(ballooMode && mixMode) {
			changeMode(1);
		} else if(ballooMode) {
			changeMode(2);
		} else if(mixMode) {
			changeMode(3);
		} else {
			changeMode(1);
		}

		watch();
		// 時計用タイマー起動
		hTimer = mStartWatch(hTimer, "watch()", 1000);

		// スレッド初期化(Cookieから初期表示チャンネルを読み込み)
		initId = getCookieValue("channel");

		// 板リスト初期化
		initBoard();
		// 板リスト自動更新用タイマー起動
		bTimer = mStartWatch(bTimer, "boardUpdate()", 10000);

		// Flashオブジェクト初期化
		initFlash(id);
		if(flash == null) {
			initFlashInterval = window.setInterval('initFlash(\"'+id+'\")', 1000);
		}

		// 広告バナー初期化
		initBanner();
		// 広告バナー自動更新用タイマー起動
		// adTimer = mStartWatch(adTimer, "bannerChange()", 30000);

		// ログイン情報表示
		showUser();

		// アクティブユーザ用タイマー起動
		activationTimer = mStartWatch(activationTimer, "activate()", 300000);
		activate();
		var statisticsLayer = document.getElementById("statistics");
	}

	// タイマー起動
	function mStartWatch(obj, methodName, time) {
		mStopWatch(obj);
		obj = setInterval(methodName, time);
		return obj;
	}

	// タイマー停止
	function mStopWatch(obj) {
		if(obj){
			clearInterval(obj);
			obj = null;
		}
	}

	/* 板初期化 */
	function initBoard(){
		initBoardreq = xmlHttpRequest();
		initBoardreq.onreadystatechange = function(){
			if (initBoardreq.readyState == 4) {
	            if (initBoardreq.status == 200) {
					board = initBoardreq.responseXML.getElementsByTagName("board");
					setThreadTitle(board);
					var resStatisticsTotal = 0;
					resStatistics = new Array();
					var connStatisticsTotal = 0;
					connStatistics = new Array();
					for(j = 0; j < chIdList.length; j++){
						// 番組名
						var chBaseElm = document.getElementById(chIdList[j] + '_base');
						var baseTitle = chBaseElm.getAttribute('title');
						chBaseElm.setAttribute('title', baseTitle.substring(0, baseTitle.indexOf('｜')+1) + topTitleList[j][0]);
						document.getElementById(chIdList[j] + '-header').innerHTML = trimString(topTitleList[j][0], 12);
						// レス数
						res = topTitleList[j][1];
						if(res == ""){
							res = 0;
						}
						barChartData[chIdList[j] + '-bar'] = new Array();
						for(var i = 1; i < 30; i++) {
							barChartData[chIdList[j] + '-bar'].push(0);
						}
						barChartData[chIdList[j] + '-bar'].push(Number(res));
						// レス率
						res_st = topTitleList[j][2];
						if(res_st == ""){
							res_st = 0;
						}
						resStatisticsTotal += Number(res_st);
						resStatistics.push(new Number(res));
						// 接続数
						conn = topTitleList[j][3];
						if(conn == ""){
							conn = 0;
						}
						// 接続率
						conn_st = topTitleList[j][4];
						if(conn_st == ""){
							conn_st = 0;
						}
						connStatisticsTotal += Number(conn_st);
						connStatistics.push(Number(conn_st));
						document.getElementById(chIdList[j] + '-res').innerHTML = conn + "人 | " + res + "res/分";

						drawBarChart(chIdList[j] + '-bar', barChartData[chIdList[j] + '-bar']);
						showStatistics(null);
					}
					// スレッド初期化
					if(initId == null || initId.length < 1) {
						// レス率の高いチャンネルを初期表示
						var index = 0;
						var value = 0;
						for(var i = 0; i < resStatistics.length; i++) {
							if(resStatistics[i] > value) {
								index = i;
								value = resStatistics[i];
							}
						}
						initId = chNameList[index]+"_";
					}
					//TODO
					selectThread(toChId(initId), initId);
	            } else {
	                errorRes("番組リストを取得できませんでした。");
	            }
			}
	    }

	    /* HTTPリクエスト実行 */
	    initBoardreq.open("GET", "./cgi/boardlist.php" , true);
	    initBoardreq.setRequestHeader("Cache-Control", "no-cache");
	    initBoardreq.setRequestHeader("Pragma", "no-cache");
	    initBoardreq.send(null);
	}
	
	function systemMessageClear() {
		if(systemMessageClearTimer != null) {
			clearInterval(systemMessageClearTimer);
			systemMessageClearTimer=null;
		}
		document.getElementById('system_message').innerHTML = "&nbsp;";
	}

	function getStatisticsArray(values, deficiency) {
		if(deficiency > 0) {
			var validCount = 0;
			for(var i = 0; i < values.length; i++) {
				if(values[i] > 0) {
					validCount++;
				}
			}
			var increment = deficiency / validCount;
			for(var i = 0; i < values.length; i++) {
				if(values[i] > 0) {
					values[i] += increment;
				}
			}
		}
		return values;
	}

	/* 板自動更新 */
	function boardUpdate(){
		initBoardreq = xmlHttpRequest();
		initBoardreq.onreadystatechange = function(){
			if (initBoardreq.readyState == 4) {
	            if (initBoardreq.status == 200) {
					board = initBoardreq.responseXML.getElementsByTagName("board");
					setThreadTitle(board);
					var resStatisticsTotal = 0;
					resStatistics = new Array();
					var connStatisticsTotal = 0;
					connStatistics = new Array();
					for(j = 0; j < chIdList.length; j++){
						if(document.getElementById(chIdList[j] + '-sel')){
							channelLinkNode = document.getElementById(chIdList[j] + '-sel');
							channelLinkNode.innerHTML = chNamejpList[j] + "　" + topTitleList[j][0].substring(0, 4);
						}else if(document.getElementById(chIdList[j] + '-focus')){
							channelFocusNode = document.getElementById(chIdList[j] + '-focus');
							while(channelFocusNode.childNodes.length > 0) {
								channelFocusNode.removeChild(channelFocusNode.firstChild);
							}
							createAnchorFocus(channelFocusNode, chIdList[j]);
							// スレッドリストポップアップが表示状態の場合、内容を更新する
							if(document.getElementById("2ch_list").style.visibility == "visible"){
								showTitleList(chIdList[j]);
							}
						}
						// 番組名
						var chBaseElm = document.getElementById(chIdList[j] + '_base');
						var chBaseMaskElm = document.getElementById(chIdList[j] + '_base_mask');
						var baseTitle = chBaseElm.getAttribute('title');
						chBaseElm.setAttribute('title', baseTitle.substring(0, baseTitle.indexOf('｜')+1) + topTitleList[j][0]);
						chBaseMaskElm.setAttribute('title', baseTitle.substring(0, baseTitle.indexOf('｜')+1) + topTitleList[j][0]);
						var header = document.getElementById(chIdList[j] + '-header');
						header.innerHTML = trimString(topTitleList[j][0], 12);
						var id = threadTitleList[j][0][1].substring(0, threadTitleList[j][0][1].length - 4);
						header.href = "javascript:selectThread('" + chIdList[j] + "', '" + id +"')";
						// レス数
						res = topTitleList[j][1];
						if(res == ""){
							res = 0;
						}
						barChartData[chIdList[j] + '-bar'].push(Number(res));
						if(barChartData[chIdList[j] + '-bar'].length > 30) {
							barChartData[chIdList[j] + '-bar'].shift();
						}
						// レス率
						res_st = topTitleList[j][2];
						if(res_st == ""){
							res_st = 0;
						}
						resStatisticsTotal += Number(res_st);
						resStatistics.push(new Number(res));
						// 接続数
						conn = topTitleList[j][3];
						if(conn == ""){
							conn = 0;
						}
						// 接続率
						conn_st = topTitleList[j][4];
						if(conn_st == ""){
							conn_st = 0;
						}
						connStatisticsTotal += Number(conn_st);
						connStatistics.push(Number(conn_st));
						document.getElementById(chIdList[j] + '-res').innerHTML = conn + "人 | " + res + "res/分";
						
						drawBarChart(chIdList[j] + '-bar', barChartData[chIdList[j] + '-bar']);
						showStatistics(null);
					}

					_2chUrl = get2chUrl(initId.substring(0, initId.indexOf("_")+1), initId);
	            } else {
	                errorRes("番組リストを取得できませんでした。");
	            }
			}
	    }

	    /* HTTPリクエスト実行 */
	    initBoardreq.open("GET", "./cgi/boardlist.php" , true);
	    initBoardreq.setRequestHeader("Cache-Control", "no-cache");
	    initBoardreq.setRequestHeader("Pragma", "no-cache");
	    initBoardreq.send(null);
	}

	/* 局ごとのスレッドリストセット */
	function setThreadTitle(board){
		topTitleList  = new Array('', '', '', '', '', '');

		for(i = 0; i < CHANNEL_NUM; i++){
			threadTitleList[i] = new Array();
			topTitleList[i] = new Array();
		}
		
		len = board.length;
		for(i = 0; i < len; i++){
			switch(board.item(i).getAttribute("name")){
				case chNameList[0]:
					if(threadTitleList[0].length <= 0){
						topTitleList[0] = new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("res"), board.item(i).getAttribute("res_statistics"), board.item(i).getAttribute("conn"), board.item(i).getAttribute("conn_statistics"));
					}
					threadTitleList[0].push(new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("filename"), board.item(i).getAttribute("href")));
					break;
				case chNameList[1]:
					if(threadTitleList[1].length <= 0){
						topTitleList[1] = new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("res"), board.item(i).getAttribute("res_statistics"), board.item(i).getAttribute("conn"), board.item(i).getAttribute("conn_statistics"));
					}
					threadTitleList[1].push(new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("filename"), board.item(i).getAttribute("href")));
					break;
				case chNameList[2]:
					if(threadTitleList[2].length <= 0){
						topTitleList[2] = new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("res"), board.item(i).getAttribute("res_statistics"), board.item(i).getAttribute("conn"), board.item(i).getAttribute("conn_statistics"));
					}
					threadTitleList[2].push(new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("filename"), board.item(i).getAttribute("href")));
					break;
				case chNameList[3]:
					if(threadTitleList[3].length <= 0){
						topTitleList[3] = new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("res"), board.item(i).getAttribute("res_statistics"), board.item(i).getAttribute("conn"), board.item(i).getAttribute("conn_statistics"));
					}
					threadTitleList[3].push(new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("filename"), board.item(i).getAttribute("href")));
					break;
				case chNameList[4]:
					if(threadTitleList[4].length <= 0){
						topTitleList[4] = new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("res"), board.item(i).getAttribute("res_statistics"), board.item(i).getAttribute("conn"), board.item(i).getAttribute("conn_statistics"));
					}
					threadTitleList[4].push(new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("filename"), board.item(i).getAttribute("href")));
					break;
				case chNameList[5]:
					if(threadTitleList[5].length <= 0){
						topTitleList[5] = new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("res"), board.item(i).getAttribute("res_statistics"), board.item(i).getAttribute("conn"), board.item(i).getAttribute("conn_statistics"));
					}
					threadTitleList[5].push(new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("filename"), board.item(i).getAttribute("href")));
					break;
				case chNameList[6]:
					if(threadTitleList[6].length <= 0){
						topTitleList[6] = new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("res"), board.item(i).getAttribute("res_statistics"), board.item(i).getAttribute("conn"), board.item(i).getAttribute("conn_statistics"));
					}
					threadTitleList[6].push(new Array(board.item(i).getAttribute("threadname"), board.item(i).getAttribute("filename"), board.item(i).getAttribute("href")));
					break;
				default:
					break;
			}
		}
	}
	
	/* 初期表示チャンネル取得スレッド */
	function getCookieValue(cookieName){
		cookie_value = "";
		if(window.navigator.cookieEnabled){
			if(document.cookie){
				cookies = document.cookie.split("; ");
				for(i = 0; i < cookies.length; i++){
					str = cookies[i].split("=");
					if(str[0] == cookieName){
						cookie_value = unescape(str[1]);
						break;
					}
				}
			}
		}
		return cookie_value;
	}

	function setCookie(key, value) {
		if(window.navigator.cookieEnabled){
			nowtime = new Date().getTime();
			clear_time = new Date(nowtime + (60 * 60 * 24 * 1000 * 365));
			expires = clear_time.toGMTString();
			document.cookie = key + "=" + value + "; expires=" + expires;
		}
	}

	function dat(res, no, time, who, originalNo, originalTID) {
		this.res = res;
		this.no = no;
		this.time = time;
		this.who = who;
		this.originalNo = originalNo;
		this.originalTID = originalTID;
	}

	/* スレッド差分取得 */
	function threadUpdate(id) {
		xmlhttp = xmlHttpRequest();
		xmlhttp.onreadystatechange = function(){
	        if (xmlhttp.readyState == 4) {
	            if (xmlhttp.status == 200) {
	            	errorCount = 0;
	            	speak = xmlhttp.responseXML.getElementsByTagName("speak");
	            	len = speak.length;
	            	var str = "";
					if(len > 0){
						// 取得したレス数
						len = speak.length;
						for(i = 0; i < len; i++){
							// 改行文字をbrタグに置換
							// アンカータグ変換
							if(ballooMode) {
								if(!mixMode && (speak.item(i).getAttribute("location") == '2ch' || speak.item(i).getAttribute("location") == 'system_2ch')) {
									continue;
								}
								if(speak.item(i).getAttribute("location") == '2ch') {
									str = '<font size="-2">';
									if(speak.item(i).childNodes[0].nodeValue.indexOf("\n", 1) != -1) {
										str += "ID:" + speak.item(i).getAttribute("who") + "</font><br/>";
										str += speak.item(i).childNodes[0].nodeValue;
									}else{
										str += "ID:" + speak.item(i).getAttribute("who") + "</font>　　";
										str += speak.item(i).childNodes[0].nodeValue;
									}
								}else
								if(speak.item(i).getAttribute("location") == 'balloo'){
									str = '<font size="-2">';
									if(speak.item(i).childNodes[0].nodeValue.indexOf("\n", 1) != -1) {
										str += "ID:" + speak.item(i).getAttribute("who") + "</font><br/>";
										str += speak.item(i).childNodes[0].nodeValue;
									}else{
										str += "ID:" + speak.item(i).getAttribute("who") + "</font>　　";
										str += speak.item(i).childNodes[0].nodeValue;
									}
								}else{
									str = speak.item(i).childNodes[0].nodeValue;
								}
								str = str.replace(/\n/g, "<br/>");
								str = str.replace(/&#60;/g, "<");
								str = str.replace(/&#62;/g, ">");
								threadArray.push(new dat(str, speak.item(i).getAttribute("no"), speak.item(i).getAttribute("timestamp"), speak.item(i).getAttribute("who"), speak.item(i).getAttribute("originalNum"), speak.item(i).getAttribute("originalID")));
							}else{
								if(speak.item(i).getAttribute("location") == '2ch'){
									str = '<font size="-2">';
									if(speak.item(i).childNodes[0].nodeValue.indexOf("\n", 1) != -1) {
										str += "ID:" + speak.item(i).getAttribute("who") + "</font><br/>";
										str += speak.item(i).childNodes[0].nodeValue;
									}else{
										str += "ID:" + speak.item(i).getAttribute("who") + "</font>　　";
										str += speak.item(i).childNodes[0].nodeValue;
									}
									str = str.replace(/\n/g, "<br/>");
									str = str.replace(/&#60;/g, "<");
									str = str.replace(/&#62;/g, ">");
									var originalNo = speak.item(i).getAttribute("originalNum");
									var originalID = speak.item(i).getAttribute("originalID");
									threadArray.push(new dat(str, speak.item(i).getAttribute("no"), speak.item(i).getAttribute("timestamp"), speak.item(i).getAttribute("who"), originalNo, originalID));
								}else{
									str = speak.item(i).childNodes[0].nodeValue;
									str = str.replace(/\n/g, "<br/>");
									str = str.replace(/&#60;/g, "<");
									str = str.replace(/&#62;/g, ">");
									var originalNo = speak.item(i).getAttribute("originalNum");
									var originalID = speak.item(i).getAttribute("originalID");
									threadArray.push(new dat(str, speak.item(i).getAttribute("no"), speak.item(i).getAttribute("timestamp"), speak.item(i).getAttribute("who"), originalNo, originalID));
								}
							}
						}
						if(scTimer == null){
							scTimer = mStartWatch(scTimer, "showThread_iphone()", 200);
						}
					}
					
					var title = xmlhttp.responseXML.getElementsByTagName("thread").item(0).getAttribute("title");
//					document.title = "Balloo.jp - " + title;
//					document.title = "Balloo.jp";
//					var programTitleElm = document.getElementById('program_title');
//					for(var i = 0; i < programTitleElm.childNodes.length; i++) {
//						programTitleElm.removeChild(programTitleElm.childNodes[i]);
//					}
					//
					//TODO
					//
//					programTitleElm.appendChild(document.createTextNode(title));
					var ch_id = xmlhttp.responseXML.getElementsByTagName("thread").item(0).getAttribute("channel");
//					if(id == ch_id+"_") {
//						_2chUrl = get2chUrl(ch_id, ch_id);
//					}
				} else {
		            if(xmlhttp.status == 400){
		            	// 引数lastnoが不正
						errorRes("リクエストが不正です。");
		            }else if(xmlhttp.status == 404){
		            	// スレッドXMLファイルがない
						errorRes("スレッドが見つかりませんでした。");
		            }else{
		            	// そのほかのエラー
						errorRes("レスポンスを取得できませんでした。");
		            }
					errorCount++;
					if(errorCount > 11) {
						mStopWatch(tTimer);
						tTimer=null;
		            	errorCount = 0;
					}
				}
	        }
		}

	    /* HTTPリクエスト実行 */
	    reqTime = new Date();
		if(threadArray && threadArray.length > 0) {
		    xmlhttp.open("GET", "./cgi/getthread.php?thread_id=" + id + "&lastno=" + threadArray[threadArray.length - 1].no, true);
		}else{
		    xmlhttp.open("GET", "./cgi/getthread.php?thread_id=" + id + "&lastno=0", true);
		}
	    xmlhttp.setRequestHeader("Cache-Control", "no-cache");
	    xmlhttp.setRequestHeader("Pragma", "no-cache");
	    xmlhttp.send(null);
	}
	
	function threadUpdate_iphone(id) {
		xmlhttp = xmlHttpRequest();
		xmlhttp.onreadystatechange = function(){
	        if (xmlhttp.readyState == 4) {
	            if (xmlhttp.status == 200) {
	            	errorCount = 0;
	            	speak = xmlhttp.responseXML.getElementsByTagName("speak");
	            	len = speak.length;
	            	var str = "";
					if(len > 0){
						// 取得したレス数
						len = speak.length;
						for(i = 0; i < len; i++){
							// 改行文字をbrタグに置換
							// アンカータグ変換
							if(speak.item(i).getAttribute("location") == '2ch' || speak.item(i).getAttribute("location") == 'balloo') {
								str = "　　ID:" + speak.item(i).getAttribute("who") + "<br/>";
								str += speak.item(i).childNodes[0].nodeValue;
								str = str.replace(/\n/g, "<br/>");
								str = str.replace(/&#60;/g, "<");
								str = str.replace(/&#62;/g, ">");
								var originalNo = speak.item(i).getAttribute("originalNum");
								var originalID = speak.item(i).getAttribute("originalID");
								threadArray.push(new dat(str, speak.item(i).getAttribute("no"), speak.item(i).getAttribute("timestamp"), speak.item(i).getAttribute("who"), originalNo, originalID));
							}else{
								str = speak.item(i).childNodes[0].nodeValue;
								str = str.replace(/\n/g, "<br/>");
								str = str.replace(/&#60;/g, "<");
								str = str.replace(/&#62;/g, ">");
								var originalNo = speak.item(i).getAttribute("originalNum");
								var originalID = speak.item(i).getAttribute("originalID");
								threadArray.push(new dat(str, speak.item(i).getAttribute("no"), speak.item(i).getAttribute("timestamp"), speak.item(i).getAttribute("who"), originalNo, originalID));
							}
						}
						if(scTimer == null){
							scTimer = mStartWatch(scTimer, "showThread_iphone()", 200);
						}
					}
					
					var title = xmlhttp.responseXML.getElementsByTagName("thread").item(0).getAttribute("title");
//					document.title = "Balloo.jp - " + title;
//					document.title = "Balloo.jp";
//					var programTitleElm = document.getElementById('program_title');
//					for(var i = 0; i < programTitleElm.childNodes.length; i++) {
//						programTitleElm.removeChild(programTitleElm.childNodes[i]);
//					}
					//
					//TODO
					//
//					programTitleElm.appendChild(document.createTextNode(title));
					var ch_id = xmlhttp.responseXML.getElementsByTagName("thread").item(0).getAttribute("channel");
//					if(id == ch_id+"_") {
//						_2chUrl = get2chUrl(ch_id, ch_id);
//					}
				} else {
		            if(xmlhttp.status == 400){
		            	// 引数lastnoが不正
						errorRes("リクエストが不正です。");
		            }else if(xmlhttp.status == 404){
		            	// スレッドXMLファイルがない
						errorRes("スレッドが見つかりませんでした。");
		            }else{
		            	// そのほかのエラー
						errorRes("レスポンスを取得できませんでした。");
		            }
					errorCount++;
					if(errorCount > 11) {
						mStopWatch(tTimer);
						tTimer=null;
		            	errorCount = 0;
					}
				}
	        }
		}

	    /* HTTPリクエスト実行 */
	    reqTime = new Date();
		if(threadArray && threadArray.length > 0) {
		    xmlhttp.open("GET", "./cgi/getthread.php?thread_id=" + id + "&lastno=" + threadArray[threadArray.length - 1].no, true);
		}else{
		    xmlhttp.open("GET", "./cgi/getthread.php?thread_id=" + id + "&lastno=0", true);
		}
	    xmlhttp.setRequestHeader("Cache-Control", "no-cache");
	    xmlhttp.setRequestHeader("Pragma", "no-cache");
	    xmlhttp.send(null);
	}

	/* スレッドスクロール */
	function scrollThread(sc){
		targetNode = document.getElementById('boardmain');
		if(scrollFlg && targetNode.scrollTop <= targetNode.scrollHeight){
			targetNode.scrollTop += sc;
		}else{
			mStopWatch(scTimeout);
			scTimeout = null;
		}
	}
	
	/* スレッドエリアにエラーメッセージ表示 */
	function errorRes(errorres){
		alert(errorres);
	}

	/* 時計表示 */
	function watch() {
		
		var targetNode = document.getElementById('watch');
		var now = new Date();
		var min = now.getMinutes();
		var sec = now.getSeconds();
		var timeValue = now.getHours()+":"
		if(min < 10) {
			timeValue += "0"+min+":";
		}else{
			timeValue += min+":";
		}
		if(sec < 10) {
			timeValue += "0"+sec;
		}else{
			timeValue += sec;
		}
		targetNode.innerHTML = timeValue;

		dateUpdate(now);
	}

	/* 現在の日付表示 */
	function dateUpdate(now) {
		var targetNode = document.getElementById('date');
		var wdays = new Array("日","月","火","水","木","金","土");
		var year = now.getFullYear();
		var mon  = now.getMonth()+1;
		var day  = now.getDate();
		var wday = wdays[now.getDay()];

		if(today != day) {
			today = day;
			var newTextDateNode  = document.createTextNode(year+'年'+mon+'月'+day+'日（'+wday+'）');
			if(targetNode.firstChild != null) {
				targetNode.removeChild(targetNode.firstChild);
			}
			targetNode.appendChild(newTextDateNode);
		}
	}
	
	/* 広告バナー初期化 */
	function initBanner(){
	}
	
	/* 広告バナー入れ替え */
	function bannerChange(){
		bannerReq = xmlHttpRequest();
		bannerReq.onreadystatechange = function(){
			if (bannerReq.readyState == 4) {
	            if (bannerReq.status == 200) {
					banner = bannerReq.responseText.split("\n", 2);
					ad1ImgNode = document.getElementById("ad1img");
					ad1ImgNode.removeAttribute("src");
					srcAttr = document.createAttribute("src");
					srcAttr.value = banner[0];
					ad1ImgNode.setAttributeNode(srcAttr);
					
					ad1LinkNode = document.getElementById("ad1link");
					ad1LinkNode.removeAttribute("href");
					hrefAttr = document.createAttribute("href");
					hrefAttr.value = banner[1];
					ad1LinkNode.setAttributeNode(hrefAttr);
	            } else {
	                window.alert("通信エラーが発生しました。" + bannerReq.status);
	            }
			}
	    }

	    /* HTTPリクエスト実行 */
	    bannerReq.open("GET", "./cgi/getbanner.php" , true);
	    bannerReq.send(null);
	}

	function addNode() {
		if(noText()) {
			return;
		}
		var textAreaValue = document.getElementById('input_area').value;
		var targetNode = document.getElementById('boardmain');
		var newTrNode = document.createElement("tr");
		var newTdLeftNode  = document.createElement("td");
		var newTdRightNode = document.createElement("td");
		var newAttrWidhtLeft  = document.createAttribute("width");
		var newAttrWidhtRight = document.createAttribute("width");
		var newTextLeftNode  = document.createTextNode(new String(targetNode.getElementsByTagName("tr").length+1));
		var newAttrValign = document.createAttribute("valign");
		var newAttrStyle = document.createAttribute("style");

		newTdLeftNode.appendChild(newTextLeftNode);

		textAreaValue.replace(">", "&gt;");
		textAreaValue.replace("<", "&lt;");
		if(textAreaValue.indexOf("\n") >= 0) {
			var texts = textAreaValue.split("\n");
			for(var i=0;i<texts.length;i++) {
				if(i > 0 ) {
					newTdRightNode.appendChild(createBRNode());
				}
				newTdRightNode.appendChild(document.createTextNode(texts[i]));
			}
		}else{
			newTdRightNode.appendChild(document.createTextNode(textAreaValue));
		}

		newAttrWidhtLeft.value  ='5%';
		newAttrWidhtRight.value ='95%';
		newAttrValign.value  ='top';
		newTdLeftNode.setAttributeNode(newAttrWidhtLeft);
		newTdLeftNode.setAttributeNode(newAttrValign);
		newTdRightNode.setAttributeNode(newAttrWidhtRight);

		newTrNode.appendChild(newTdLeftNode);
		newTrNode.appendChild(newTdRightNode);

		var targetTable = targetNode.getElementsByTagName("tr").item(0).parentNode;
		targetTable.appendChild(newTrNode);
		targetNode.scrollTop = targetNode.scrollHeight;
		document.getElementById('input_area').value = "";
	}

	function noText() {
		var textAreaValue = document.form1.input_area.value;
		textAreaValue.replace(" ", "");
		textAreaValue.replace("　", "");
		if(textAreaValue.length > 0) {
			return false;
		}
		return true;
	}

	function selectChannel(ch_id) {
		hiddenLayer("2ch_list");
		if(nowFocusCh != ch_id) {
			for(var i=0;i<chIdList.length;i++) {
				var targetChannelTop    = document.getElementById(chIdList[i]+'-t'); 
				var targetChannelMain   = document.getElementById(chIdList[i]+'-m'); 
				var targetChannelBottom = document.getElementById(chIdList[i]+'-b'); 
				if(chIdList[i] == ch_id) {
					selectThread(ch_id, threadTitleList[i][0][1].substring(0, threadTitleList[i][0][1].length - 4));
					createFocus(targetChannelTop, targetChannelMain, targetChannelBottom, chIdList[i]);
					nowFocusCh=ch_id;
				}else{
					createBlur(targetChannelTop, targetChannelMain, targetChannelBottom, chIdList[i]);
				}
			}
		}
	}

	function turnOn(chId) {
		var offId = toChId(initId);
		if(offId != null) {
			document.getElementById(offId+'_base').getAttributeNode('class').nodeValue = 'ch'+offId.slice(0,-2)+'_base_off';
		}
		if(chId != null) {
			document.getElementById(chId+'_base').getAttributeNode('class').nodeValue = 'ch'+chId.slice(0,-2)+'_base_on';
		}
	}

	function toChId(chName) {
		var chId = null;
		if(chName != null) {
			if(chName.indexOf('_') != -1) {
				chName = chName.substring(0,chName.indexOf('_'));
			}
			for(var i = 0; i < chNameList.length; i++) {
				if(chNameList[i] == chName) {
					chId = chIdList[i];
					break;
				}
			}
		}
		return chId;
	}

	/* スレッド選択 */
	function selectThread(ch_id, id) {
		turnOn(ch_id);
		initId = id;
		_2chUrl = get2chUrl(id.substring(0, id.indexOf("_")+1), id);
		// Cookieが使用可能ならチャンネル情報をCookieに入れる
		setCookie("channel", escape(id.substring(0, id.indexOf("_") + 1)));
		threadLen = 0;
		mStopWatch(tTimer);
		tTimer=null;
		// スレッド初期化
		if(flash != null) {
			try {
				var docRoot = "http://"+location.host;
				flash.setURL(docRoot);
				if(firstTimeSelectThread) {
					flash.initThread(id, true);
				}else{
					flash.initThread(id, false);
				}
				firstTimeSelectThread = false;
				immediateUpdate = true;
			} catch(e) {
			}
		}
	}

	// 発言更新時にFlashから呼び出される関数
	function updateThreadInfo(threadId, threadTitle) {
		currentThreadId = threadId;
//		document.title = "Balloo.jp - " + threadTitle;
		document.title = "Balloo.jp";
		_2chUrl = get2chUrl(initId.substring(0, initId.indexOf("_")+1), initId);
		if(immediateUpdate) {
			immediateUpdate = false;
			activate();
		}
	}

	function get2chUrl(label, filename) {
		var templabel =  label.indexOf("_") > 0 ? label.substring(0, label.indexOf("_")) : label;
		for(var i=0;i<chNameList.length;i++) {
			if(templabel == chNameList[i]) {
				var threadTitle = threadTitleList[i];
				if(filename == label+".xml") {
					return threadTitle[0][2];
				}
				for(var j=0;j<threadTitle.length;j++) {
					if(threadTitle[j][1].indexOf(filename) >= 0) {
						return threadTitle[j][2];
					}
				}
				return threadTitle[0][2];
			}
		}
	}

	/* レスアンカーポップアップ */
	function showRelation(resno, suffix) {
		//NOT WORK
		return;
		
		var mainTableNode = document.getElementById('tablemain');
		var tableBgcolor  = mainTableNode.getAttributeNode('bgcolor');
		var targetNode = document.getElementById('boardmain');

		targetNo = -1;
		len = targetNode.getElementsByTagName("tr").length;
		for(i = 0; i < len; i++){
			var ballooID = new Number(targetNode.getElementsByTagName("tr")[i].getElementsByTagName("td")[0].getAttribute("id"));
			if(resno == ballooID){
				targetNo = i;
				break;
			}
		}
		if(targetNo == -1){
			return ;
		}
		// 何番目のレスか
		var targetTrNode = targetNode.getElementsByTagName("tr")[targetNo];
		// レス内容
		var targetTdNode = targetTrNode.getElementsByTagName("td")[1];

		var dialogNode = document.getElementById("relation");
		var dialogInnerNode = document.getElementById("relation_inner"); 
		while(dialogInnerNode.childNodes.length > 0) {
			dialogInnerNode.removeChild(dialogInnerNode.firstChild);
		}

		var textValue = null;
		var tdChilds = targetTdNode.childNodes;
		for(var i=0;i<tdChilds.length;i++) {
			if(tdChilds[i].nodeType == TEXT_NODE) {
				if(tdChilds[i].data.charAt(0) == '　' && tdChilds[i].data.charAt(1) == '　') {
					var message = tdChilds[i].data.substring(2, tdChilds[i].data.length);
					dialogInnerNode.appendChild(document.createTextNode(message));
				}else{
					dialogInnerNode.appendChild(document.createTextNode(tdChilds[i].data));
				}
			}
			if(tdChilds[i].nodeType == ELEMENT_NODE) {
				if(tdChilds[i].nodeName.toLowerCase() == 'br') {
					dialogInnerNode.appendChild(createBRNode());
				}
				if(tdChilds[i].nodeName.toLowerCase() == 'a') {
					if(tdChilds[i].firstChild.data.charAt(0) == '　' && tdChilds[i].firstChild.data.charAt(1) == '　') {
						var message = tdChilds[i].firstChild.data.substring(2, tdChilds[i].firstChild.data.length);
						dialogInnerNode.appendChild(document.createTextNode(message));
					}else{
						dialogInnerNode.appendChild(document.createTextNode(tdChilds[i].firstChild.data));
					}
				}
			}
		}

		var anode = document.getElementById('tanchor_'+suffix);
		dialogNode.style.top = getOffsetTop(anode) - dialogNode.offsetHeight - boardmainScrollval + "px";
		dialogNode.style.left = getOffsetLeft(anode)+10 + "px";
		
		// 背景色変更。現在の背景色に合わせて色が変わる
		dialogNode.style.visibility = 'visible';
		if(!autoRelationHiddenTimer) {
			autoRelationHiddenTimer = mStartWatch(autoRelationHiddenTimer, 'closeRelation()', 8000);
		}
	}
	
	/* スレッドリストポップアップ表示 */
	function showTitleList(ch_id) {
		if(ballooMode && !mixMode) {
			return;
		}
		var titles = null;
		for(i = 0; i < CHANNEL_NUM; i++){
			if(ch_id == chIdList[i]) {
				titles = threadTitleList[i];
				break;
			}
		}
		var dialogNode = document.getElementById("2ch_list"); 
		var dialogInnerNode = document.getElementById("2ch_list_inner");
		while(dialogInnerNode.childNodes.length > 0) {
			dialogInnerNode.removeChild(dialogInnerNode.firstChild);
		}
		for(i = 1;i < THREAD_MAX_NUM; i++) {
			var anchorNode = document.createElement("a");
			var hrefAttr = document.createAttribute("href");
			var targetAttr = document.createAttribute("target");
			var textNode = document.createTextNode(i+". "+titles[i][0]);
			id = titles[i][1].substring(0, titles[i][1].length - 4);
			hrefAttr.value = get2chUrl(id, id)+"/l50";
			targetAttr.value = "_blank";
			anchorNode.setAttributeNode(hrefAttr);
			anchorNode.setAttributeNode(targetAttr);
			anchorNode.appendChild(textNode);
			dialogInnerNode.appendChild(anchorNode);
			dialogInnerNode.appendChild(createBRNode());
		}
		dialogNode.style.top = getOffsetTop(document.getElementById(ch_id+'-header')) - 15;
		dialogNode.style.left = 80;
		dialogNode.style.visibility = 'visible';
		if(!autoTitleListHiddenTimer) {
			autoTitleListHiddenTimer = mStartWatch(autoTitleListHiddenTimer, 'autoHiddenTitleList()', 5000);
		}
	}
	
	function autoHiddenTitleList() {
		mStopWatch(autoTitleListHiddenTimer);
		autoTitleListHiddenTimer = null;
		document.getElementById("2ch_list").style.visibility = 'hidden';
	}

	function createBRNode() {
		return document.createElement("br");
	}

	function getOffsetTop(obj) {
		if(obj.parentNode) {
			if(obj.nodeName.toLowerCase() == 'td') {
				return 0 + getOffsetTop(obj.parentNode);
			}else{
				return obj.offsetTop + getOffsetTop(obj.parentNode);
			}
		}else{
			if(obj.offsetTop) {
				return obj.offsetTop;
			}
		}
		return 0;
	}

	function getOffsetLeft(obj) {
		if(obj.parentNode) {
			if(obj.nodeName.toLowerCase() == 'tr') {
				return 0 + getOffsetLeft(obj.parentNode);
			}else{
				return obj.offsetLeft + getOffsetLeft(obj.parentNode);
			}
		}else{
			if(obj.offsetTop) {
				return obj.offsetLeft;
			}
		}
		return 0;
	}

	function createBlur(top, main, bottom, ch_id) {
		var parentNode = top.parentNode;

		parentNode.removeChild(top);
		parentNode.removeChild(main);
		parentNode.removeChild(bottom);

		var trTop    = createBlurTopTR(document.createElement("tr"), ch_id);
		var trMain   = createBlurMain(document.createElement("tr"), ch_id);
		var trbottom = createBlurBottomTR(document.createElement("tr"), ch_id);

		parentNode.appendChild(trTop);
		parentNode.appendChild(trMain);
		parentNode.appendChild(trbottom);
	}

	function createBlurTopTR(trNode, ch_id) {
		var td = document.createElement("td");
		var widthSpace     = document.createAttribute("width");
		widthSpace.value   = leftMenuBlurSpace;
		var widthSpaceColor     = document.createAttribute("bgcolor");
		widthSpaceColor.value   = leftMenuBlurSpaceBgColor;
		td.setAttributeNode(widthSpace);
		td.setAttributeNode(widthSpaceColor);
		trNode.appendChild(td);

		td = document.createElement("td");
		var width4Attr1    = document.createAttribute("width");
		width4Attr1.value  = leftMenuCornerSize;
		var width4Attr2    = document.createAttribute("width");
		width4Attr2.value  = leftMenuCornerSize;
		var height4Attr   = document.createAttribute("height");
		height4Attr.value = leftMenuCornerSize;
		var imageWidthAttr    = document.createAttribute("width");
		imageWidthAttr.value  = leftMenuWidth;
		var bgImageLeftTop    = document.createAttribute("background");
		bgImageLeftTop.value  = leftMenuBlurLeftTopImg;
		var bgImageRightTop   = document.createAttribute("background");
		bgImageRightTop.value = leftMenuBlurRightTopImg;
		var bgImageTop      = document.createAttribute("background");
		bgImageTop.value    = leftMenuBlurTopImg;
		var colspanAttr     = document.createAttribute("colspan");
		colspanAttr.value    = '2';

		td.setAttributeNode(width4Attr1);
		td.setAttributeNode(bgImageLeftTop);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(imageWidthAttr);
		td.setAttributeNode(height4Attr);
		td.setAttributeNode(bgImageTop);
		td.setAttributeNode(colspanAttr);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(width4Attr2);
		td.setAttributeNode(bgImageRightTop);
		trNode.appendChild(td);

		var idAttr    = document.createAttribute("id");
		idAttr.value  = ch_id+"-t";
		var bgColor   = document.createAttribute("bgcolor");
		bgColor.value = leftMenuBlurBgColor;
		trNode.setAttributeNode(idAttr);
		trNode.setAttributeNode(bgColor);

		return trNode;
	}

	function createBlurMain(trNode, ch_id) {
		var td = document.createElement("td");
		var widthSpace     = document.createAttribute("width");
		widthSpace.value   = leftMenuBlurSpace;
		var widthSpaceColor     = document.createAttribute("bgcolor");
		widthSpaceColor.value   = leftMenuBlurSpaceBgColor;
		td.setAttributeNode(widthSpace);
		td.setAttributeNode(widthSpaceColor);
		trNode.appendChild(td);

		td = document.createElement("td");
		var width4Attr1     = document.createAttribute("width");
		width4Attr1.value   = leftMenuCornerSize;
		var width4Attr2     = document.createAttribute("width");
		width4Attr2.value   = leftMenuCornerSize;
		var height30Attr1   = document.createAttribute("height");
		height30Attr1.value = leftMenuBlurTitleHeight;
		var height30Attr2   = document.createAttribute("height");
		height30Attr2.value = leftMenuBlurTitleHeight;
		var bgImageLeft    = document.createAttribute("background");
		bgImageLeft.value  = leftMenuBlurLeftImg;
		var bgImageRight   = document.createAttribute("background");
		bgImageRight.value = leftMenuBlurRightImg;

		td.setAttributeNode(width4Attr1);
		td.setAttributeNode(height30Attr1);
		td.setAttributeNode(bgImageLeft);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.appendChild(createAnchorBlur(ch_id));
		trNode.appendChild(td);

		td = document.createElement("td");
		var iconNode = document.createElement("img");
		var iconAttr = document.createAttribute("src");
		iconAttr.value = 'images/small1.gif';
		iconNode.setAttributeNode(iconAttr);
		td.appendChild(iconNode);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(width4Attr2);
		td.setAttributeNode(height30Attr2);
		td.setAttributeNode(bgImageRight);
		trNode.appendChild(td);

		var idAttr    = document.createAttribute("id");
		idAttr.value  = ch_id+"-m";
		var bgColor   = document.createAttribute("bgcolor");
		bgColor.value = leftMenuBlurBgColor;
		trNode.setAttributeNode(idAttr);
		trNode.setAttributeNode(bgColor);

		return trNode;
	}

	/* 未選択時のスレッドリスト生成？ */
	function createAnchorBlur(ch_id) {
		var anchorNode = document.createElement("a");
		var hrefAttr = document.createAttribute("href");
		var selIdAttr = document.createAttribute("id");
		hrefAttr.value = "javascript:selectChannel('"+ch_id+"')";
		selIdAttr.value = ch_id + "-sel";
		anchorNode.setAttributeNode(hrefAttr);
		anchorNode.setAttributeNode(selIdAttr);
		
		var title = null;
		for(i = 0; i < CHANNEL_NUM; i++){
			if(ch_id == chIdList[i]){
				title = topTitleList[i][0].substring(0, 4);
				channelName = chNamejpList[i];
				break;
			}
		}

		var textNode = document.createTextNode(channelName+"　"+title);
		anchorNode.appendChild(textNode);

		return anchorNode;
	}

	function createBlurBottomTR(trNode, ch_id) {
		var td = document.createElement("td");
		var widthSpace     = document.createAttribute("width");
		widthSpace.value   = leftMenuBlurSpace;
		var widthSpaceColor     = document.createAttribute("bgcolor");
		widthSpaceColor.value   = leftMenuBlurSpaceBgColor;
		td.setAttributeNode(widthSpace);
		td.setAttributeNode(widthSpaceColor);
		trNode.appendChild(td);

		td = document.createElement("td");
		var width4Attr1    = document.createAttribute("width");
		width4Attr1.value  = leftMenuCornerSize;
		var width4Attr2    = document.createAttribute("width");
		width4Attr2.value  = leftMenuCornerSize;
		var height4Attr   = document.createAttribute("height");
		height4Attr.value = leftMenuCornerSize;
		var imageWidthAttr    = document.createAttribute("width");
		imageWidthAttr.value  = leftMenuWidth;
		var bgImageLeftBottom    = document.createAttribute("background");
		bgImageLeftBottom.value  = leftMenuBlurLeftBottomImg;
		var bgImageRightBottom   = document.createAttribute("background");
		bgImageRightBottom.value = leftMenuBlurRightBottomImg;
		var bgImageBottom   = document.createAttribute("background");
		bgImageBottom.value = leftMenuBlurBottomImg;
		var colspanAttr     = document.createAttribute("colspan");
		colspanAttr.value    = '2';

		td.setAttributeNode(width4Attr1);
		td.setAttributeNode(bgImageLeftBottom);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(imageWidthAttr);
		td.setAttributeNode(height4Attr);
		td.setAttributeNode(bgImageBottom);
		td.setAttributeNode(colspanAttr);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(width4Attr2);
		td.setAttributeNode(bgImageRightBottom);
		trNode.appendChild(td);

		var idAttr    = document.createAttribute("id");
		idAttr.value  = ch_id+"-b";
		var bgColor   = document.createAttribute("bgcolor");
		bgColor.value = leftMenuBlurBgColor;
		trNode.setAttributeNode(idAttr);
		trNode.setAttributeNode(bgColor);

		return trNode;
	}

	function createFocus(top, main, bottom, ch_id) {
		var parentNode = top.parentNode;

		parentNode.removeChild(top);
		parentNode.removeChild(main);
		parentNode.removeChild(bottom);

		var trTop    = createFocusTopTR(document.createElement("tr"), ch_id);
		var trMain   = createFocusMain(document.createElement("tr"), ch_id);
		var trbottom = createFocusBottomTR(document.createElement("tr"), ch_id);

		parentNode.appendChild(trTop);
		parentNode.appendChild(trMain);
		parentNode.appendChild(trbottom);
	}

	function createFocusTopTR(trNode, ch_id) {
		var td = document.createElement("td");
		var width4Attr1    = document.createAttribute("width");
		width4Attr1.value  = leftMenuCornerSize;
		var width4Attr2    = document.createAttribute("width");
		width4Attr2.value  = leftMenuCornerSize;
		var height4Attr   = document.createAttribute("height");
		height4Attr.value = leftMenuCornerSize;
		var imageWidthAttr    = document.createAttribute("width");
		imageWidthAttr.value  = leftMenuWidth;
		var bgImageLeftTop    = document.createAttribute("background");
		bgImageLeftTop.value  = leftMenuFocusLeftTopImg;
		var bgImageRightTop   = document.createAttribute("background");
		bgImageRightTop.value = leftMenuFocusTopImg;
		var bgImageTop      = document.createAttribute("background");
		bgImageTop.value    = leftMenuFocusTopImg;
		var colspanAttr1    = document.createAttribute("colspan");
		colspanAttr1.value  = "2";
		var colspanAttr2    = document.createAttribute("colspan");
		colspanAttr2.value  = "2";

		td.setAttributeNode(width4Attr1);
		td.setAttributeNode(bgImageLeftTop);
		td.setAttributeNode(colspanAttr1);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(imageWidthAttr);
		td.setAttributeNode(height4Attr);
		td.setAttributeNode(bgImageTop);
		td.setAttributeNode(colspanAttr2);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(width4Attr2);
		td.setAttributeNode(bgImageRightTop);
		trNode.appendChild(td);

		var idAttr    = document.createAttribute("id");
		idAttr.value  = ch_id+"-t";
		var bgColor   = document.createAttribute("bgcolor");
		bgColor.value = leftMenuFocusBgColor;
		trNode.setAttributeNode(idAttr);
		trNode.setAttributeNode(bgColor);

		return trNode;
	}

	function createFocusMain(trNode, ch_id) {
		var td = document.createElement("td");
		var width4Attr1     = document.createAttribute("width");
		width4Attr1.value   = leftMenuCornerSize;
		var width4Attr2     = document.createAttribute("width");
		width4Attr2.value   = leftMenuCornerSize;
		var height80Attr1   = document.createAttribute("height");
		height80Attr1.value = leftMenuFocusTitleHeight;
		var height80Attr2   = document.createAttribute("height");
		height80Attr2.value = leftMenuFocusTitleHeight;
		var bgImageLeft    = document.createAttribute("background");
		bgImageLeft.value  = leftMenuFocusLeftImg;
		var colspanAttr1   = document.createAttribute("colspan");
		colspanAttr1.value = "2";

		td.setAttributeNode(width4Attr1);
		td.setAttributeNode(height80Attr1);
		td.setAttributeNode(bgImageLeft);
		td.setAttributeNode(colspanAttr1);
		trNode.appendChild(td);

		td = createAnchorFocus(document.createElement("td"), ch_id);
		var focusIdAttr = document.createAttribute("id");
		focusIdAttr.value = ch_id + "-focus";
		td.setAttributeNode(focusIdAttr);
		trNode.appendChild(td);

		td = document.createElement("td");
		var iconNode = document.createElement("img");
		var iconAttr = document.createAttribute("src");
		iconAttr.value = 'images/middle1.gif';
		iconNode.setAttributeNode(iconAttr);
		td.appendChild(iconNode);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(width4Attr2);
		td.setAttributeNode(height80Attr2);
		trNode.appendChild(td);

		var idAttr    = document.createAttribute("id");
		idAttr.value  = ch_id+"-m";
		var bgColor   = document.createAttribute("bgcolor");
		bgColor.value = leftMenuFocusBgColor;
		trNode.setAttributeNode(idAttr);
		trNode.setAttributeNode(bgColor);

		return trNode;
	}

	/* 板選択時のスレッドリスト表示 */
	function createAnchorFocus(tdNode, ch_id) {

		for(i = 0; i < CHANNEL_NUM; i++){
			if(ch_id == chIdList[i]){
				titleList = threadTitleList[i];
				channelName = chNamejpList[i];
				break;
			}
		}

		// スレッドタイトルセット
		for(i = 0; i < THREAD_LIST_NUM; i++){
			if(titleList[i]){
				if(i == 0){
					textNodeList = document.createTextNode(channelName + "　" + titleList[i][0].substring(0, 4));
				}else{
					textNodeList = document.createTextNode(titleList[i][0].substring(0, 10) + "...");
				}
				anchorNodeList = document.createElement("a");
				hrefAttrList = document.createAttribute("href");
				id = titleList[i][1].substring(0, titleList[i][1].length - 4);
				hrefAttrList.value = "javascript:selectThread('"+ch_id+"', '" + id + "')";
				anchorNodeList.setAttributeNode(hrefAttrList);
				anchorNodeList.appendChild(textNodeList);
				tdNode.appendChild(anchorNodeList);
				tdNode.appendChild(createBRNode());
				// スレッド一覧リンク
				if(i == THREAD_LIST_NUM - 1){
					textNodeList = document.createTextNode("...");
					anchorNodeList = document.createElement("a");
					hrefAttrList = document.createAttribute("href");
					hrefAttrList.value = "javascript:showTitleList('"+ch_id+"')";
					anchorNodeList.setAttributeNode(hrefAttrList);
					anchorNodeList.appendChild(textNodeList);
					tdNode.appendChild(anchorNodeList);
					tdNode.appendChild(createBRNode());
				}
			}else{
				break;
			}
		}
		
		return tdNode;
	}

	function createFocusBottomTR(trNode, ch_id) {
		var td = document.createElement("td");
		var width4Attr1    = document.createAttribute("width");
		width4Attr1.value  = leftMenuCornerSize;
		var width4Attr2    = document.createAttribute("width");
		width4Attr2.value  = leftMenuCornerSize;
		var height4Attr   = document.createAttribute("height");
		height4Attr.value = leftMenuCornerSize;
		var imageWidthAttr    = document.createAttribute("width");
		imageWidthAttr.value  = leftMenuWidth;
		var bgImageLeftBottom    = document.createAttribute("background");
		bgImageLeftBottom.value  = leftMenuFocusLeftBottomImg;
		var bgImageRightBottom   = document.createAttribute("background");
		bgImageRightBottom.value = leftMenuFocusBottomImg;
		var bgImageBottom   = document.createAttribute("background");
		bgImageBottom.value = leftMenuFocusBottomImg;
		var colspanAttr1    = document.createAttribute("colspan");
		colspanAttr1.value  = "2";
		var colspanAttr2    = document.createAttribute("colspan");
		colspanAttr2.value  = "2";

		td.setAttributeNode(width4Attr1);
		td.setAttributeNode(bgImageLeftBottom);
		td.setAttributeNode(colspanAttr1);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(imageWidthAttr);
		td.setAttributeNode(height4Attr);
		td.setAttributeNode(bgImageBottom);
		td.setAttributeNode(colspanAttr2);
		trNode.appendChild(td);

		td = document.createElement("td");
		td.setAttributeNode(width4Attr2);
		td.setAttributeNode(bgImageRightBottom);
		trNode.appendChild(td);

		var idAttr    = document.createAttribute("id");
		idAttr.value  = ch_id+"-b";
		var bgColor   = document.createAttribute("bgcolor");
		bgColor.value = leftMenuFocusBgColor;
		trNode.setAttributeNode(idAttr);
		trNode.setAttributeNode(bgColor);

		return trNode;
	}

	function hiddenLayer(target) {
		var dialogNode = document.getElementById(target); 
		dialogNode.style.visibility='hidden';
	}

	function setScrollTop(top, height) {
		var scrollMax = document.getElementById('boardmain').scrollHeight;
		boardmainScrollval = top;
	}

	function closeRelation() {
		var mainTableNode = document.getElementById('tablemain');
		var tableBgcolor  = mainTableNode.getAttributeNode('bgcolor');
		mStopWatch(autoRelationHiddenTimer);
		autoRelationHiddenTimer = null;
		hiddenLayer("relation");
	}

	/* メッセージ送信 */
	function sendInputMessage(){
		if(!ballooMode) {
			// 2chサイト表示
			if(_2chUrl && _2chUrl.indexOf("http:") >=0) {
				window.open(_2chUrl+'/1', '_blank');
			}
			return;
		}
		if(noText()){
			return ;
		}
//TODO: 投稿ロックフラグ　確認してから対応！
		if(ballooMode) {
			document.form1.input_area.disabled = false;
		}
		document.form1.submit_btn.disabled = false;
		sendMessage(document.form1.input_area.value);
		document.form1.input_area.value = "";
	}

	function sendMessage(message) {
		sendFlg = true;
		messagePost = xmlHttpRequest();
	    /* レスポンスデータ処理用のコールバック関数を定義 */
		messagePost.onreadystatechange = function(){
	        if(messagePost.readyState == 4){
	            if(messagePost.status == 200){
					if(messagePost.responseText != "1"){
						errorRes("投稿に失敗しました。");
					}
	            }else if(messagePost.status == 400){
	                errorRes("メッセージ内容が不正です。<br/>文字数は500文字までです。");
	            }else if(messagePost.status == 404){
	            	errorRes("メッセージ送信に失敗しました。");
	            }
				if(ballooMode) {
					document.form1.input_area.disabled = false;
				}
				document.form1.submit_btn.disabled = false;
	            sendFlg = false;
	        }
		}

		var val = "message_body=" + encodeURI(message);
		val += "&thread_id=" + currentThreadId;
		val += "&user_id=" + tmpId;
	    /* HTTPリクエスト実行 */
	    messagePost.open("POST", "./cgi/send.php", true);
		messagePost.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
	    messagePost.send(val);
	}

	function sendByEnter(event) {
		if(event.keyCode == 13) {
			sendInputMessage();
		}
	}

	function mixModeControl(mode) {
		mixMode = mode;
		setCookie("mix_mode", mode ? "true" : "false");
		if(initId != null) {
			firstTimeSelectThread = true;
			selectThread(toChId(initId), initId);
		}
	}
	
	/* フォントサイズを上げる */
	function upFontSize(){
		if(threadFontSize <= 18){
			threadFontSize++;
			tablemain.style.fontSize = threadFontSize + "pt";
		}
	}
	
	/* フォントサイズを下げる */
	function downFontSize(){
		if(threadFontSize >= 6){
			threadFontSize--;
			tablemain.style.fontSize = threadFontSize + "pt";
		}
	}

	/* 表示設定ウィンドウ表示 */
	function openProperty(){
		var left = window.screen.width  / 2 - (200 / 2);
		var top  = window.screen.height  / 2 - (150 / 2);
		propWin = window.open("./property.html", "property", "width=205,height=160,scrollbars=1,resizable=no,titlebar=no,left=" + left + ",top=" + top);
	}
	
	/* スレッド内文字色変更 */
	function changeFontColor(c){
		font_color = c;
		// Cookieが使用可能ならチャンネル情報をCookieに入れる
		setCookie("font_color", escape(font_color));
		document.getElementById("tablemain").style.color = c;
		node = document.getElementById("tablemain").getElementsByTagName("a");
		len = node.length;
		for(i = 0; i < len; i++){
			node.item(i).style.color = c;
		}
	}
	
	/* 背景色変更 */
	function changeBgColor(c){
		bg_color = c;
		// Cookieが使用可能ならチャンネル情報をCookieに入れる
		setCookie("bg_color", escape(bg_color));
		document.getElementById('tablemain').getAttributeNode('bgcolor').value = c;
	}
	
	/* URL履歴ウィンドウ表示 */
	function openUrlHistory(){
		var left = window.screen.width  / 2 - (600 / 2);
		var top  = window.screen.height  / 2 - (600 / 2);
		historyWin = window.open("./history.html", "history", "width=600,height=600,scrollbars=1,resizable=no,titlebar=no,left=" + left + ",top=" + top);
	}
	
	/* 登録1ウィンドウ表示 */
	function openFixedFormMessage1(){
		if(loginFlg == true){
			var left = window.screen.width  / 2 - (600 / 2);
			var top  = window.screen.height  / 2 - (600 / 2);
			historyWin = window.open("./copipe1.html", "copipe1", "width=600,height=600,scrollbars=1,resizable=yes,titlebar=no,left=" + left + ",top=" + top);
		}else{
			alert("ログインしてください。");
		}
	}
	
	/* 登録2ウィンドウ表示 */
	function openFixedFormMessage2(){
		if(loginFlg == true){
			var left = window.screen.width  / 2 - (600 / 2);
			var top  = window.screen.height  / 2 - (600 / 2);
			historyWin = window.open("./copipe2.html", "copipe2", "width=600,height=600,scrollbars=1,resizable=yes,titlebar=no,left=" + left + ",top=" + top);
		}else{
			alert("ログインしてください。");
		}
	}
	
	function closeWindow(){
		if(propWin){
			propWin.close();
		}
		if(historyWin){
			historyWin.close();
		}
	}

	/* ユーザログイン情報表示 */
	function showUser() {
		var userReq = xmlHttpRequest();
		userReq.onreadystatechange = function(){
			if (userReq.readyState == 4) {
				var userinfo = null;
				if (userReq.status == 200) {
					if(userReq.responseXML.getElementsByTagName("userinfo").length > 0) {
						userinfo = userReq.responseXML;
					}
				}
				var active = false;
				var handle = "";
				var id = null;
				if(userinfo != null) {
					active = true;
					handle = userinfo.getElementsByTagName("handle")[0].firstChild.nodeValue;
					id = userinfo.getElementsByTagName("userinfo")[0].getAttribute("user_id");
				}
				updateUser(active, handle, id);
			}
		}

		/* HTTPリクエスト実行 */
		userReq.open("GET", "./cgi/getuser.php" , true);
		userReq.setRequestHeader("Cache-Control", "no-cache");
		userReq.setRequestHeader("Pragma", "no-cache");
		userReq.send(null);
	}

	function updateUser(active, handle, id) {
		tmpId = id;
		var userElm = document.getElementById('user_name');
		userElm.innerHTML = "&nbsp;";
		loginStatusForSettingMenu = false;
		if(active) {
			var h = htmlspecialchars(trimString(handle, 13)) + " さん";
			userElm.innerHTML = insertBr(h, 55);
			loginStatusForSettingMenu = true;
			var loginBtn = document.getElementById('login_btn');
			loginBtn.style.visibility = 'hidden';
			loginBtn.style.position = 'absolute';
			var logoutBtn = document.getElementById('logout_btn');
			logoutBtn.style.visibility = 'visible';
			logoutBtn.style.position = 'relative';
			loginFlg = true;
			var userSettingBtn = document.getElementById('user_setting_btn');
			userSettingBtn.style.visibility = 'visible';
			userSettingBtn.style.position = 'relative';
			if(ballooMode) {
				document.form1.input_area.disabled = false;
			}
			document.form1.submit_btn.disabled = false;
		} else {
			var logoutBtn = document.getElementById('logout_btn');
			logoutBtn.style.visibility = 'hidden';
			logoutBtn.style.position = 'absolute';
			var loginBtn = document.getElementById('login_btn');
			loginBtn.style.visibility = 'visible';
			loginBtn.style.position = 'relative';
			loginFlg = false;
			var userSettingBtn = document.getElementById('user_setting_btn');
			userSettingBtn.style.visibility = 'hidden';
			userSettingBtn.style.position = 'absolute';
			if(!ballooMode) {
				document.form1.input_area.disabled = true;
			}
		}
	}

	function logout() {
		var userReq = xmlHttpRequest();
		userReq.onreadystatechange = function(){
			if (userReq.readyState == 4) {
				if (userReq.status == 200) {
					if(userReq.responseXML.getElementsByTagName("status").length > 0) {
						userinfo = userReq.responseXML;
					}
					systemMessageClear();
					document.getElementById('system_message').innerHTML = "ログアウトしました";
					systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
				}
				loginFlg = false;
				tmpId = null;
				showUser();
			}
		}

		/* HTTPリクエスト実行 */
		userReq.open("GET", "./cgi/logout.php" , true);
		userReq.setRequestHeader("Cache-Control", "no-cache");
		userReq.setRequestHeader("Pragma", "no-cache");
		userReq.send(null);
	}

	function showLoginForm() {
		if(onFlashDialog()) {
			return;
		}
		var propertyPanelLayer = document.getElementById('proppanel');
		var formNode = document.getElementById("proppanel1");
		var isIE  = navigator.userAgent.toLowerCase().indexOf("msie") > 0;
		if (isIE) {
			propertyPanelLayer.style.width = document.documentElement.scrollLeft + document.documentElement.clientWidth - 5 + "px";
			propertyPanelLayer.style.height = document.documentElement.scrollTop + document.documentElement.clientHeight - 5 + "px";
		}else{
			propertyPanelLayer.style.width = innerWidth - 5+"px";
			propertyPanelLayer.style.height = innerHeight - 5+"px";
		}
		propertyPanelLayer.style.visibility = "visible";
		formNode.style.visibility = "visible";
	}

	function showLoginForm2() {
		document.getElementById("login_panel").style.visibility = "visible";
	}

	function login() {
		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					var xmlStatus = req.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
					var msg = "";
					if(xmlStatus == '0') {
						msg = "ログインしました。";
						activate();
						closeLoginForm();
//						_propertyPanel.closePanel();
					} else {
						msg = "ログインに失敗しました。<br/>";
					}
					systemMessageClear();
					document.getElementById('system_message').innerHTML = msg;
					systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
				}
			}
		}

		var val = "mailaddress=" + document.form1.login_mailaddress.value;
		val += "&password=" + document.form1.login_password.value;
		/* HTTPリクエスト実行 */
		req.open("POST", "./cgi/login.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(val);
	}

	function getInnerHtmlLoginForm() {
		var innerHtml = "";
		innerHtml += '<table>';
		innerHtml += '<tr>';
		innerHtml += '<td colspan="2" id="msg_login"></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>ログインID</td>';
		innerHtml += '<td><input type="text" name="mailaddress" value="" maxlength="128" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>パスワード</td>';
		innerHtml += '<td><input type="password" name="password" maxlength="12" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td></td>';
		innerHtml += '<td><button type="button" name="login_form_btn" onclick="login();">ログイン</button></td>';
		innerHtml += '</tr>';
		innerHtml += '</table>';
		return innerHtml;
	}

	function closeLoginForm() {
		var propertyPanelLayer = document.getElementById('proppanel');
		var formNode = document.getElementById("proppanel1");
		propertyPanelLayer.style.visibility = "hidden";
		formNode.style.visibility = "hidden";
	}

	function changeLoginTab(num) {
		var loginForm = document.getElementById('login_form');
		var loginUserRegist = document.getElementById('login_user_regist');

		loginForm.style.visibility = 'hidden';
		loginUserRegist.style.visibility = 'hidden';

		clearInnerHtml('login_form');
		clearInnerHtml('login_user_regist');

		switch(num) {
			case 1:
				loginForm.innerHTML = getInnerHtmlLoginForm();
				loginForm.style.top = loginForm.parentNode.style.top + 10;
				loginForm.style.left = loginForm.parentNode.style.left + 110;
				loginForm.style.visibility = 'visible';
				break;
			case 2:
				loginUserRegist.innerHTML = getInnerHtmlRegistUserInput();
				loginUserRegist.style.top = loginUserRegist.parentNode.style.top + 10;
				loginUserRegist.style.left = loginUserRegist.parentNode.style.left + 110;
				loginUserRegist.style.visibility = 'visible';
				break;
		}
	}

	function registUser() {
		if(document.form1.regist_password.value != document.form1.regist_password2.value) {
			//var msg = "「パスワード」と「パスワード（確認）」が一致しません。<br/>";
			//document.getElementById('msg_user_regist').innerHTML = msg;
			alert("「パスワード」と「パスワード（確認）」が一致しません。");
			return;
		}
		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					var xmlStatus = req.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
					var msg = "";
					if(xmlStatus == '0') {
						msg = "ユーザ情報登録メールを送信しました。";
						document.getElementById('system_message').innerHTML = msg;
						systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
					} else if(xmlStatus == '1') {
						var validateError = req.responseXML.getElementsByTagName("validate_error");
						for(var i = 0; i < validateError.length; i++) {
							var key = "";
							var error = "";
							for(var j = 0; j < validateError[i].childNodes.length; j++) {
								var child = validateError[i].childNodes[j];
								if(child.nodeName == "key") {
									key = child.firstChild.nodeValue;
								}
								if(child.nodeName == "error") {
									error = child.firstChild.nodeValue;
								}
							}
							if(key == "mailaddress") {
								if(error == "required") {
									msg += "メールアドレスは必須項目です。\n";
								}
								if(error == "pattern") {
									msg += "メールアドレスの書式が不正です。\n";
								}
								if(error == "max_length") {
									msg += "メールアドレスは128文字までです。\n";
								}
							}
							if(key == "password") {
								if(error == "required") {
									msg += "パスワードは必須項目です。\n";
								}
							}
							if(key == "handle") {
								if(error == "required") {
									msg += "ハンドル名は必須項目です。\n";
								}
								if(error == "max_length") {
									msg += "ハンドル名は72文字までです。\n";
								}
							}
						}
					} else {
						msg = req.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
					}
					if(xmlStatus != '0') {
						alert(msg);
					}
				}
			}
		}

		var val = "mailaddress=" + document.form1.regist_mailaddress.value;
		val += "&password=" + document.form1.regist_password.value;
		val += "&password2=" + document.form1.regist_password2.value;
		val += "&handle=" + document.form1.regist_handle.value;
		/* HTTPリクエスト実行 */
		req.open("POST", "./cgi/user_regist2.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(val);
	}

	function getInnerHtmlRegistUserInput() {
		var innerHtml = "";
		innerHtml += '<table>';
		innerHtml += '<tr>';
		innerHtml += '<td colspan="2" id="msg_user_regist"></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>メールアドレス&nbsp;※必須</td>';
		innerHtml += '<td><input type="text" name="mailaddress" value="" maxlength="128" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>パスワード&nbsp;※必須</td>';
		innerHtml += '<td><input type="password" name="password" maxlength="12" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>パスワード（確認）&nbsp;※必須</td>';
		innerHtml += '<td><input type="password" name="password2" maxlength="12" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>ハンドル名&nbsp;※必須、72文字まで</td>';
		innerHtml += '<td><input type="text" name="handle" value="" maxlength="72" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td></td>';
		innerHtml += '<td><button type="button" name="user_regist_btn" onclick="registUser();">登録</button></td>';
		innerHtml += '</tr>';
		innerHtml += '</table>';
		return innerHtml;
	}

	function editUser() {
		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					var xmlStatus = req.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
					var msg = "";
					if(xmlStatus == '0') {
						msg = "ユーザ情報を更新しました。";
						updateUser(true, document.form1.mod_handle.value, tmpId);
					} else if(xmlStatus == '1') {
						var validateError = req.responseXML.getElementsByTagName("validate_error");
						for(var i = 0; i < validateError.length; i++) {
							var key = "";
							var error = "";
							for(var j = 0; j < validateError[i].childNodes.length; j++) {
								var child = validateError[i].childNodes[j];
								if(child.nodeName == "key") {
									key = child.firstChild.nodeValue;
								}
								if(child.nodeName == "error") {
									error = child.firstChild.nodeValue;
								}
							}
							if(key == "mailaddress") {
								if(error == "required") {
									msg += "メールアドレスは必須項目です。<br/>";
								}
								if(error == "pattern") {
									msg += "メールアドレスの書式が不正です。<br/>";
								}
								if(error == "max_length") {
									msg += "メールアドレスは128文字までです。<br/>";
								}
							}
							if(key == "handle") {
								if(error == "required") {
									msg += "ハンドル名は必須項目です。<br/>";
								}
								if(error == "max_length") {
									msg += "ハンドル名は72文字までです。<br/>";
								}
							}
						}
					} else {
						msg = req.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
						msg = msg.replace("\n", "<br/>");
					}
					systemMessageClear();
					document.getElementById('system_message').innerHTML = msg;
					systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
				}
			}
		}

		var val = "mailaddress=" + document.form1.mod_mailaddress.value;
		val += "&handle=" + document.form1.mod_handle.value;
		val += "&user_id=" + tmpId;
		/* HTTPリクエスト実行 */
		req.open("POST", "./cgi/user_edit2.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(val);
	}

	function editUserInit() {
		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				var userinfo = null;
				if (req.status == 200) {
					if(req.responseXML.getElementsByTagName("userinfo").length > 0) {
						userinfo = req.responseXML;
					}
				}
				if(userinfo != null) {
					var mailaddress = userinfo.getElementsByTagName("mailaddress")[0].firstChild.nodeValue;
					var handle = userinfo.getElementsByTagName("handle")[0].firstChild.nodeValue;
					document.form1.mailaddress.value = mailaddress;
					document.form1.handle.value = handle;
				}
			}
		}

		/* HTTPリクエスト実行 */
		req.open("GET", "./cgi/getuser.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.send(null);
	}

	function getInnerHtmlEditUserInput() {
		var innerHtml = "";
		innerHtml += '<table>';
		innerHtml += '<tr>';
		innerHtml += '<td colspan="2" id="msg_user_edit"></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>メールアドレス&nbsp;※必須</td>';
		innerHtml += '<td><input type="text" name="mailaddress" value="" maxlength="128" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>ハンドル名&nbsp;※必須、72文字まで</td>';
		innerHtml += '<td><input type="text" name="handle" value="" maxlength="72" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<td></td>';
		innerHtml += '<td><button type="button" name="user_edit_btn" onclick="editUser();">編集</button></td>';
		innerHtml += '</tr>';
		innerHtml += '</table>';
		return innerHtml;
	}

	function editPassword() {
		if(document.form1.newpassword.value != document.form1.newpassword2.value) {
			var msg = "「新しいパスワード」と「新しいパスワード（確認）」が一致しません。<br/>";
			systemMessageClear();
			document.getElementById('system_message').innerHTML = msg;
			systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
			return;
		}
		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					var xmlStatus = req.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
					var msg = "";
					if(xmlStatus == '0') {
						msg = "パスワードを変更しました。";
					} else if(xmlStatus == '1') {
						var validateError = req.responseXML.getElementsByTagName("validate_error");
						for(var i = 0; i < validateError.length; i++) {
							var key = "";
							var error = "";
							for(var j = 0; j < validateError[i].childNodes.length; j++) {
								var child = validateError[i].childNodes[j];
								if(child.nodeName == "key") {
									key = child.firstChild.nodeValue;
								}
								if(child.nodeName == "error") {
									error = child.firstChild.nodeValue;
								}
							}
						}
					} else {
						msg = req.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
						msg = msg.replace("\n", "<br/>");
					}
					systemMessageClear();
					document.getElementById('system_message').innerHTML = msg;
					systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
				}
			}
		}

		var val = "password=" + document.form1.current_password.value;
		val += "&newpassword=" + document.form1.newpassword.value;
		val += "&user_id=" + tmpId;
		/* HTTPリクエスト実行 */
		req.open("POST", "./cgi/user_edit_password2.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(val);
	}

	function editPasswordInit() {
		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				var userinfo = null;
				if (req.status == 200) {
					if(req.responseXML.getElementsByTagName("userinfo").length > 0) {
						userinfo = req.responseXML;
					}
				}
				if(userinfo != null) {
					var mailaddress = userinfo.getElementsByTagName("mailaddress")[0].firstChild.nodeValue;
					document.getElementById("mailaddress").innerHTML = mailaddress;
				}
			}
		}

		/* HTTPリクエスト実行 */
		req.open("GET", "./cgi/getuser.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.send(null);
	}

	function getInnerHtmlEditPasswordInput() {
		var innerHtml = "";
		innerHtml += '<table>';
		innerHtml += '<tr>';
		innerHtml += '<td colspan="2" id="msg_password_edit"></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>メールアドレス</td>';
		innerHtml += '<td id="mailaddress"></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>パスワード</td>';
		innerHtml += '<td><input type="password" name="password" maxlength="12" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>新しいパスワード</td>';
		innerHtml += '<td><input type="password" name="newpassword" maxlength="12" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td>新しいパスワード（確認）</td>';
		innerHtml += '<td><input type="password" name="newpassword2" maxlength="12" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td></td>';
		innerHtml += '<td><button type="button" name="password_edit_btn" onclick="editPassword();">変更</button></td>';
		innerHtml += '</tr>';
		innerHtml += '</table>';
		return innerHtml;
	}

	function leave() {
		if(!document.form1.leave_password.value) {
			var msg = "パスワードを指定してください。<br/>";
			systemMessageClear();
			document.getElementById('system_message').innerHTML = msg;
			systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
			return;
		}
		if(!document.form1.leave_mailaddress.value) {
			var msg = "メールアドレスを指定してください。<br/>";
			systemMessageClear();
			document.getElementById('system_message').innerHTML = msg;
			systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
			return;
		}
		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					var xmlStatus = req.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue;
					var msg = "";
					if(xmlStatus == '0') {
						msg = "退会処理を完了しました。";
						updateUser(false);
					} else {
						msg = req.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
						msg = msg.replace("\n", "<br/>");
					}
					systemMessageClear();
					document.getElementById('system_message').innerHTML = msg;
					systemMessageClearTimer = setInterval('systemMessageClear()', 3000);
				}
			}
		}

		var val = "mailaddress=" + document.form1.leave_mailaddress.value;
		val += "&password=" + document.form1.leave_password.value;
		/* HTTPリクエスト実行 */
		req.open("POST", "./cgi/user_leave2.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(val);
	}

	function leaveInit() {
		if(loginFlg) {
			document.getElementById("mailaddress").style.visibility = "hidden";
			document.getElementById("password").style.visibility = "hidden";
		}
	}

	function getInnerHtmlLeaveInput() {
		var innerHtml = "";
		innerHtml += '<table>';
		innerHtml += '<tr>';
		innerHtml += '<td colspan="2" id="msg_confirm">本当に退会しますか？</td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td colspan="2" id="msg_leave"></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr id="mailaddress">';
		innerHtml += '<td>メールアドレス</td>';
		innerHtml += '<td><input type="text" name="mailaddress" value="" maxlength="128" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr id="password">';
		innerHtml += '<td>パスワード</td>';
		innerHtml += '<td><input type="password" name="password" maxlength="12" style="width:150px;"/></td>';
		innerHtml += '</tr>';
		innerHtml += '<tr>';
		innerHtml += '<td></td>';
		innerHtml += '<td><button type="button" name="leave_btn" onclick="leave();">退会する</button></td>';
		innerHtml += '</tr>';
		innerHtml += '</table>';
		return innerHtml;
	}

	function showRating() {
		window.open('./analyzer2.html', '_blank', 'directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no');
	}

	function trimString(value, length) {
		if(value.length >= length) {
			var newValue = value.substring(0, length-1);
			return newValue+"...";
		}
		return value;
	}

	function autoHiddenProgramList() {
		mStopWatch(autoProgramListHiddenTimer);
		autoProgramListHiddenTimer = null;
		document.getElementById("program").style.visibility = 'hidden';
	}

	function activate() {
		var userReq = xmlHttpRequest();
		userReq.onreadystatechange = function(){
			if (userReq.readyState == 4) {
				if (userReq.status == 200) {
					if(userReq.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue == '0') {
						tmpId = userReq.responseXML.getElementsByTagName("guid")[0].firstChild.nodeValue;
						showUser();
					}
				}
			}
		}

		var val = "user_id=" + (tmpId != null ? encodeURI(tmpId) : "");
		val += "&thread_id=" + (currentThreadId != null ? encodeURI(currentThreadId) : "");
		/* HTTPリクエスト実行 */
		userReq.open("POST", "./cgi/activateuser.php" , true);
		userReq.setRequestHeader("Cache-Control", "no-cache");
		userReq.setRequestHeader("Pragma", "no-cache");
		userReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		userReq.send(val);
	}
	
	function resize() {
		var margin = 5;
		var mainLayerMargin = 20;
		var topMargin = 38;
		if(agentIE) {
			var bottomHeight = document.documentElement.clientHeight < defaultHeight ? 72 : 36;
			document.getElementById('bottom').style.top = document.documentElement.clientHeight - margin - bottomHeight;
			var h = document.documentElement.clientHeight - bottomHeight - mainLayerMargin - topMargin;
			itaH = h > 0 ? h : itaH;
			document.getElementById('wallpaper').style.width  = document.documentElement.clientWidth + "px";
			document.getElementById('wallpaper').style.height = (document.documentElement.clientHeight - 40) + "px";
			resizeBoard('ita', itaX, itaY, '80%', itaH);
		}
		else {
			var bottomHeight = window.innerHeight < defaultHeight ? 72 : 36;
			var h = window.innerHeight - bottomHeight - topMargin;
			itaH = h > 0 ? h : itaH;
			var x = isNaN(itaX) ? itaX : itaX + 'px';
			var y = isNaN(itaY) ? itaY : itaY + 'px';
			var w = isNaN(itaW) ? itaW : itaW + 'px';
			var innerH = itaH - document.getElementById('bottom').clientHeight;
			innerH = isNaN(innerH) ? innerH : innerH + 'px';
			h = isNaN(itaH) ? itaH+5 : (itaH+5) + 'px';
			document.getElementById('wallpaper').style.width = document.documentElement.clientWidth + "px";
			document.getElementById('wallpaper').style.height = (innerHeight - 60) + "px";
			resizeBoard('dummylayer', x, y, '80%', h);
			resizeBoard('ita', x, y, '100%', innerH);
		}
		if(flash) {
			flash.resizeBoard(getBoardSize());
		}
	}


	function getCutPxStringFromNumber(str) {
		var strNum = new String(str);
		if(strNum.toLowerCase().indexOf("px") > 0) {
			return strNum.substring(0, strNum.length - 2);
		}
		return strNum;
	}

	function getBoardSize() {
		var obj = document.getElementById('ita');
		var width = 0;
		if (isIE) {
			width = document.documentElement.scrollLeft + document.documentElement.clientWidth - 5;
		}else{
			width = innerWidth - 5;
		}
		var left = boardMax ? 25 : 130;
		width = width - left;
		var result = new Array(left,
							   getCutPxStringFromNumber(obj.top),
							   width, 
							   getCutPxStringFromNumber(obj.style.height));
		return result.join(",");
	}

	function insertBr(text, num) {
		var result = "";
		var count = 0;
		for (var i=0; i<text.length; i++) {
			var c = text.charAt(i);
			var n = escape(c);
			if (n.length < 4) {
				count++;
			} else {
				if(c.match("[｡-ﾟ]")) {
					count++;
				} else {
					count+=2;
				}
			}
			result += c;
			if(count >= num) {
				result += "<br/>";
				count = 0;
			}
		}
		return result;
	}

	function htmlspecialchars(target) {
		if(target == null) {
			return null;
		}
		var result = new String(target);
		result = result.replace("&", "&amp;");
		result = result.replace("\"", "&quot;");
		result = result.replace("'", "&#39;");
		result = result.replace("<", "&lt;");
		result = result.replace(">", "&gt;");
		return result;
	}

	function changeMode(mode) {
		switch(mode) {
			case 1:
				document.getElementById('mode1_btn').getAttributeNode('class').nodeValue = 'mode1_btn_on';
				document.getElementById('mode2_btn').getAttributeNode('class').nodeValue = 'mode2_btn_off';
				document.getElementById('mode3_btn').getAttributeNode('class').nodeValue = 'mode3_btn_off';
				setMode(true, true);
				break;
			case 2:
				document.getElementById('mode1_btn').getAttributeNode('class').nodeValue = 'mode1_btn_off';
				document.getElementById('mode2_btn').getAttributeNode('class').nodeValue = 'mode2_btn_on';
				document.getElementById('mode3_btn').getAttributeNode('class').nodeValue = 'mode3_btn_off';
				setMode(true, false);
				break;
			case 3:
				document.getElementById('mode1_btn').getAttributeNode('class').nodeValue = 'mode1_btn_off';
				document.getElementById('mode2_btn').getAttributeNode('class').nodeValue = 'mode2_btn_off';
				document.getElementById('mode3_btn').getAttributeNode('class').nodeValue = 'mode3_btn_on';
				setMode(false, true);
				break;
		}
		if(flash != null) {
			flash.changeMode(String(mode));
		}
	}

	function setMode(isBalloo, isMix) {
		if(!isBalloo) {
			// 2ch
			document.form1.input_area.disabled = true;
		} else {
			// balloo
			document.form1.input_area.disabled = false;
			document.form1.submit_btn.disabled = false;
		}
		ballooMode = isBalloo;
		mixModeControl(isMix);
		setCookie("balloo_mode", new String(ballooMode));
	}

	function showFontSizeSelect() {
		var select = document.getElementById('font_size_select');
		select.style.visibility = 'hidden';
		var pos = getPos(document.getElementById('size_img'));
		select.style.position = 'absolute';
		select.style.left = pos.x + 110;
		select.style.top = pos.y + 5;
		select.style.visibility = 'visible';
	}

	function getPos(elm) {
		var target = elm;
		var pos = new function() {
			this.x = 0;
			this.y = 0;
		}
		while(target) {
			pos.x += target.offsetLeft;
			pos.y += target.offsetTop;
			target = target.offsetParent;
		}
		return pos;
	}

	function saveSetting() {
		changeFontSize(tmpFontSize);
		changeFontFamily(document.form1.select_font_family.value);
		changeColorSet(tmpColorSet);
	}

	function closeSettingPanel(ok) {
		if(ok) {
			saveSetting();
		}
		var panel = document.getElementById('panel');
		panel.style.position = 'absolute';
		clearInnerHtml('setting_user_regist');
		clearInnerHtml('setting_user_edit');
		clearInnerHtml('setting_password');
		clearInnerHtml('setting_user_leave');

		// close
		hiddenLayer('setting_color');
		hiddenLayer('setting_type');
		hiddenLayer('setting_user_regist');
		hiddenLayer('setting_user_edit');
		hiddenLayer('setting_password');
		hiddenLayer('setting_user_leave');
		hiddenLayer('panel_btn02');
		hiddenLayer('panel_btn04');
		hiddenLayer('panel_btn05');
		hiddenLayer('panel');
		hiddenLayer('backscreen');
	}

	function clearInnerHtml(id) {
		document.getElementById(id).innerHTML = "";
	}

	function changeSettingTab(num) {
		var settingColor = document.getElementById('setting_color');
		var settingType = document.getElementById('setting_type');
		var settingUserRegist = document.getElementById('setting_user_regist');
		var settingUserEdit = document.getElementById('setting_user_edit');
		var settingPassword = document.getElementById('setting_password');
		var settingUserLeave = document.getElementById('setting_user_leave');

		settingColor.style.visibility = 'hidden';
		settingType.style.visibility = 'hidden';
		settingUserRegist.style.visibility = 'hidden';
		settingUserEdit.style.visibility = 'hidden';
		settingPassword.style.visibility = 'hidden';
		settingUserLeave.style.visibility = 'hidden';

		clearInnerHtml('setting_user_regist');
		clearInnerHtml('setting_user_edit');
		clearInnerHtml('setting_password');
		clearInnerHtml('setting_user_leave');

		switch(num) {
			case 1:
				settingColor.style.top = settingColor.parentNode.style.top + 10;
				settingColor.style.left = settingColor.parentNode.style.left + 110;
				settingColor.style.visibility = 'visible';
				break;
			case 2:
				selectFixedFormMessage(1);
				settingType.style.top = settingType.parentNode.style.top + 10;
				settingType.style.left = settingType.parentNode.style.left + 110;
				settingType.style.visibility = 'visible';
				break;
			case 3:
				settingUserRegist.innerHTML = getInnerHtmlRegistUserInput();
				settingUserRegist.style.top = settingUserRegist.parentNode.style.top + 10;
				settingUserRegist.style.left = settingUserRegist.parentNode.style.left + 110;
				settingUserRegist.style.visibility = 'visible';
				break;
			case 4:
				settingUserEdit.innerHTML = getInnerHtmlEditUserInput();
				editUserInit();
				settingUserEdit.style.top = settingUserEdit.parentNode.style.top + 10;
				settingUserEdit.style.left = settingUserEdit.parentNode.style.left + 110;
				settingUserEdit.style.visibility = 'visible';
				break;
			case 5:
				settingPassword.innerHTML = getInnerHtmlEditPasswordInput();
				editPasswordInit();
				settingPassword.style.top = settingPassword.parentNode.style.top + 10;
				settingPassword.style.left = settingPassword.parentNode.style.left + 110;
				settingPassword.style.visibility = 'visible';
				break;
			case 6:
				settingUserLeave.innerHTML = getInnerHtmlLeaveInput();
				leaveInit();
				settingUserLeave.style.top = settingUserLeave.parentNode.style.top + 10;
				settingUserLeave.style.left = settingUserLeave.parentNode.style.left + 110;
				settingUserLeave.style.visibility = 'visible';
				break;
		}
	}

	function setTmpFontSize() {
		var select = document.form1.select_font_size;
		tmpFontSize = select.options[select.selectedIndex].value;
	}

	function setTmpColor(colorSet) {
		tmpColorSet = colorSet;
	}
	
	function sortDescArray(arg1, arg2){
		if(arg1 == arg2) {
			return 0;
		}else
		if(arg1 > arg2) {
			return -1;
		}else{
			return 1;
		}
	}
	
	function showStatistics(e) {
		var sortedRes = resStatistics.slice(0);
		sortedRes.sort(sortDescArray);
		var tempResStatistics = resStatistics.slice(0);
		var statisticHTML = "<div style='color:#FFFFFF; text-align:center;'>--- 各局の勢い ---</div>";
		for(var i=0;i<sortedRes.length;i++) {
			var chNo = -1;
			var chName = '';
			for(var j=0;j<tempResStatistics.length;j++) {
				if(sortedRes[i] == tempResStatistics[j]) {
					switch(j) {
						case 0:
							chNo = 1;
							break;
						case 1:
							chNo = 3;
							break;
						case 2:
							chNo = 4;
							break;
						case 3:
							chNo = 6;
							break;
						case 4:
							chNo = 8;
							break;
						case 5:
							chNo = 10;
							break;
						case 6:
							chNo = 12;
							break;
					}
					chName = chNamejpLongList[j];
					tempResStatistics[j] = -1;
					break;
				}
			}
			if(chNo >= 0) {
				statisticHTML += "<div class='ch"+chNo+"_statistics'>";
				statisticHTML += "<div class='channel_name_statistics'>"+chName+"</div>";
				statisticHTML += "<div class='res_statistics' id='"+chNo+"ch_res_statistics'>"+sortedRes[i]+"res/分</div>";
				statisticHTML += "</div>";
			}
		}
		document.getElementById("statistics").innerHTML = statisticHTML;
	}

	function round(num, decimalPlace) {
		var result = num;
		var m = Math.pow(10, decimalPlace);
		result = result * m;
		result = Math.round(result);
		result = result / m;
		return result;
	}

	function registFixedFormMessage() {
		var kind = document.form1.selected_kind_no.value;
		var oldId = document.form1.type_message_id.value;
		if(oldId != null && oldId.length > 0) {
			deleteFixedFormMessage(oldId);
		}

		var message = document.form1.type_textarea.value;
		if(message == null || message.length < 1) {
			return;
		}

		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					document.getElementById("type_regist_message").innerHTML = "定型"+kind+"に登録しました。";
					setTimeout('clearInnerHtml("type_regist_message")', 3000);
				}
			}
		}

		var val = "user_id=" + tmpId;
		val += "&kind=" + kind;
		val += "&message=" + encodeURI(message);
		/* HTTPリクエスト実行 */
		req.open("POST", "./cgi/sendcopipe.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(val);
	}

	function deleteFixedFormMessage(id) {
		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status != 200) {
					document.getElementById("type_regist_message").innerHTML = "定型"+kind+"の古いデータの削除に失敗しました。";
					setTimeout('clearInnerHtml("type_regist_message")', 1500);
				}
			}
		}

		var val = "user_id=" + tmpId;
		val += "&id=" + id;
		/* HTTPリクエスト実行 */
		req.open("POST", "./cgi/deletecopipe.php" , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(val);
	}

	function selectFixedFormMessage(kind) {
		clearInnerHtml("type_regist_message");
		clearInnerHtml("type_textarea");
		for(var i = 1; i < 6; i++) {
			document.getElementById('type'+i+'_btn').getAttributeNode('class').nodeValue = 'type'+i+'_btn';
		}
		document.getElementById('type'+kind+'_btn').getAttributeNode('class').nodeValue = 'type'+kind+'_btn_on';

		document.form1.selected_kind_no.value = kind;

		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					var typeId = "";
					var text = "";
					var msgNodes = req.responseXML.getElementsByTagName("message");
					if(msgNodes != null && msgNodes.length > 0) {
						text = msgNodes[0].firstChild.nodeValue;
						typeId = msgNodes[0].getAttributeNode('id').nodeValue;
					}
					document.form1.type_textarea.value = text;
					document.form1.type_message_id.value = typeId;
				}
			}
		}

		var val = "user_id=" + tmpId;
		val += "&kind=" + kind;
		/* HTTPリクエスト実行 */
		req.open("GET", "./cgi/getcopipe.php?"+val , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.send(null);
	}

	function showTypePreview(kind, obj, e) {
		var top = 0;
		var left = 0;
		
		buttonCheangeByID('type'+kind+'_btn', 'images/type'+kind+'_over.gif');
		
		if(agentIE) {
			top = getOffsetTop(obj) - 190;
			left = document.documentElement.clientWidth - 485;
		} else {
			top = new Number(getCutPxStringFromNumber(document.getElementById('dummylayer').style.height)) - 205 + new Number(getCutPxStringFromNumber(document.getElementById("dummylayer").style.top));
			left = window.innerWidth - 485;
		}

		if(!ballooMode) {
			setTypePreview("※2chモードでは使用できません。", "", top, left);
			return;
		} else {
			if(!loginFlg) {
				setTypePreview("※ログインが必要です。", "", top, left);
				return;
			}
		}

		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					var text = "";
					var msgNodes = req.responseXML.getElementsByTagName("message");
					if(msgNodes != null && msgNodes.length > 0) {
						text = msgNodes[0].firstChild.nodeValue;
						text = text.replace(/\n/g, "<br/>");
						text = text.replace(/&#60;/g, "<");
						text = text.replace(/&#62;/g, ">");
					}

					setTypePreview("定型" + kind + "のプレビュー", text, top, left);
				}
			}
		}

		var val = "user_id=" + tmpId;
		val += "&kind=" + kind;
		/* HTTPリクエスト実行 */
		req.open("GET", "./cgi/getcopipe.php?"+val , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.send(null);
	}

	function setTypePreview(title, content, top, left) {
		var prevHtml = "<table width='170px' border='0'><tr height='5px'><td width='5px'><td aligh='center' width='160px'>"+title+"</td><td width='5px'></tr><tr height='140px'><td width='5px'><td aligh='center' width='165px'>"+content+"</td><td width='5px'></tr></table>";
		_typePreviewPopup.showWithHTML(left, top, prevHtml, 3000);
	}

	function closeTypePreview(id, isOn) {
		if(isOn) {
			buttonCheangeByID('type'+id+'_btn', 'images/type0'+id+'_on.gif');
		}else{
			buttonCheangeByID('type'+id+'_btn', 'images/type'+id+'.gif');
		}
		_typePreviewPopup.hidePreview();
	}

	function sendFixedMessage(kind) {
		if(!ballooMode || !loginFlg) {
			return;
		}

		var req = xmlHttpRequest();
		req.onreadystatechange = function(){
			if (req.readyState == 4) {
				if (req.status == 200) {
					var text = "";
					var msgNodes = req.responseXML.getElementsByTagName("message");
					if(msgNodes != null && msgNodes.length > 0) {
						text = msgNodes[0].firstChild.nodeValue;
						if(text != null && text.length > 0) {
							sendMessage(text);
						}
					}

				}
			}
		}

		var val = "user_id=" + tmpId;
		val += "&kind=" + kind;
		/* HTTPリクエスト実行 */
		req.open("GET", "./cgi/getcopipe.php?"+val , true);
		req.setRequestHeader("Cache-Control", "no-cache");
		req.setRequestHeader("Pragma", "no-cache");
		req.send(null);
	}

	function changeBoardArea() {
		boardMax = !boardMax;
		var left = boardMax ? "12px" : "170px";
		var width = boardMax ? "98%" : "80%";
		var visibility = boardMax ? "hidden" : "visible";

		document.getElementById("area_btn").getAttributeNode('class').nodeValue = boardMax ? "min_btn" : "max_btn";
		document.getElementById("head").style.left = left;
		document.getElementById("logo").style.visibility = visibility;
		document.getElementById("date_time").style.visibility = visibility;
		document.getElementById("statistics").style.visibility = visibility;
		itaX = left;
		itaW = width;
		if(agentIE) {
			resizeBoard('ita', left, document.getElementById("ita").style.top, width, document.getElementById('ita').style.height);
		}
		else {
			resizeBoard('dummylayer', left, document.getElementById("dummylayer").style.top, width, document.getElementById('dummylayer').style.height);
			resizeBoard('ita', left, document.getElementById("ita").style, "100%", document.getElementById('ita').style.height);
			document.getElementById("bottom").style.marginLeft = boardMax ? "170px" : "0px";
		}
		if(flash) {
			flash.resizeBoard(getBoardSize());
		}
	}

	function stopAutoScroll(event, obj) {
		var targetPosX = null;
		var scrollMinX = null;

		if(event.offsetX != undefined) {
			// IE,Opera,Safari
			targetPosX = event.offsetX;
			scrollMinX = obj.scrollWidth;
		} else if(event.pageX > obj.clientWidth) {
			// FireFox
			targetPosX = obj.scrollWidth + event.layerX;
			scrollMinX = obj.scrollWidth;
		}

		// スクロールバー上
		if(targetPosX != null && scrollMinX != null) {
			var margin = scrollMaxX - scrollMinX;
			if(margin > 0 && margin < 100
			 && scrollMinX <= targetPosX && targetPosX <= scrollMaxX) {
				scrollControl();
			}
		}
	}

	function stopScrollByWheel(event) {
		if(event.wheelDelta > 0) {
			scrollControl();
		}
	}
	
	function stopScrollByWheelForFirefox(event) {
		if(-event.detail > 0) {
			scrollControl();
		}
	}

	function menuMoveToOpen(divelement) {
		if(menuCtrl) {
			menuCtrl.moveToOpen()
		}
	}
	
	function channelLayerClick(ch, force) {
		if(boardMax || force) {
			channelLayerOverAllFalse();
			if(ch == 1) {
				selectThread(chIdList[0], chNameList[0]+"_");
			}else
			if(ch == 3) {
				selectThread(chIdList[1], chNameList[1]+"_");
			}else
			if(ch == 4) {
				selectThread(chIdList[2], chNameList[2]+"_");
			}else
			if(ch == 6) {
				selectThread(chIdList[3], chNameList[3]+"_");
			}else
			if(ch == 8) {
				selectThread(chIdList[4], chNameList[4]+"_");
			}else
			if(ch == 10) {
				selectThread(chIdList[5], chNameList[5]+"_");
			}else
			if(ch == 12) {
				selectThread(chIdList[6], chNameList[6]+"_");
			}
			_scrollStatus = false;
			document.getElementById("onscroll_btn").style.visibility = "hidden"
			document.getElementById("onscroll_btn").style.position = "absolute"
			document.getElementById("offscroll_btn").style.visibility = "visible"
			document.getElementById("offscroll_btn").style.position = "relative"
		}
	}
	function channelLayerOverAllFalse() {
		channelLayerOver(1, false);
		channelLayerOver(3, false);
		channelLayerOver(4, false);
		channelLayerOver(6, false);
		channelLayerOver(8, false);
		channelLayerOver(10, false);
		channelLayerOver(12, false);
	}

	function channelLayerOver(ch, onOver) {
		if(!boardMax) {
			var offId = toChId(initId);
			var chId = null;
			if(ch == 1) {
				chId = chIdList[0];
			}else
			if(ch == 3) {
				chId = chIdList[1];
			}else
			if(ch == 4) {
				chId = chIdList[2];
			}else
			if(ch == 6) {
				chId = chIdList[3];
			}else
			if(ch == 8) {
				chId = chIdList[4];
			}else
			if(ch == 10) {
				chId = chIdList[5];
			}else
			if(ch == 12) {
				chId = chIdList[6];
			}
			if(offId != null && chId == offId) {
				if(onOver) {
					document.getElementById(offId+'_base').getAttributeNode('class').nodeValue = 'ch'+ch+'_base_on_over';
				}else{
					document.getElementById(offId+'_base').getAttributeNode('class').nodeValue = 'ch'+ch+'_base_on';
				}
			}else{
				if(onOver) {
					document.getElementById(chId+'_base').getAttributeNode('class').nodeValue = 'ch'+ch+'_base_off_over';
				}else{
					document.getElementById(chId+'_base').getAttributeNode('class').nodeValue = 'ch'+ch+'_base_off';
				}
			}
		}
	}
	
	function addRelationNoToText(no) {
		document.form1.input_area.value = ">>"+no+" "+document.form1.input_area.value;
	}

	function onFlashDialog() {
		return _onFLashSettingDialog;
	}
	
	function setFlashDialog(status) {
		_onFLashSettingDialog = status;
	}
	
	function buttonCheangeByID(id, fileName) {
		var targetNode = document.getElementById(id);
		var targetImage = "url("+fileName+")";
		targetNode.style.backgroundImage = targetImage;
	}

	var hiPhoneScrollTimer = null;
	function iPhoneScroll() {
		window.scrollTo(0,1);
		clearTimeout(hiPhoneScrollTimer);
	}
	//iphone
	function init_iphone() {
		hiPhoneScrollTimer = setTimeout(iPhoneScroll,100);

		_typePreviewPopup = new TypePreview(180, 180, 8, '#101010', '#FEFEFE', 85, 10);
		var propertyPanelLayer = document.getElementById('proppanel');

		var fontSize = getCookieValue("font_size");
		var fontFamily = getCookieValue("font_family");
		var colorSet = getCookieValue("color_set");

		ballooMode = true;
		mixModeControl(true);
		setCookie("balloo_mode", new String(true));

		watch();
		// 時計用タイマー起動
		hTimer = mStartWatch(hTimer, "watch()", 1000);

		// スレッド初期化(Cookieから初期表示チャンネルを読み込み)
		initId = getCookieValue("channel");

		// 板リスト初期化
		initBoard();
		// 板リスト自動更新用タイマー起動
		bTimer = mStartWatch(bTimer, "boardUpdate()", 10000);

		// 広告バナー初期化
		initBanner();
		// 広告バナー自動更新用タイマー起動
		// adTimer = mStartWatch(adTimer, "bannerChange()", 30000);
		
		initThread_iphone(initId, false);

		// アクティブユーザ用タイマー起動
		activationTimer = mStartWatch(activationTimer, "activate_iphone()", 60000);
		var statisticsLayer = document.getElementById("statistics");
	}


	function activate_iphone() {
		var userReq = xmlHttpRequest();
		userReq.onreadystatechange = function(){
			if (userReq.readyState == 4) {
				if (userReq.status == 200) {
					if(userReq.responseXML.getElementsByTagName("status")[0].firstChild.nodeValue == '0') {
						tmpId = userReq.responseXML.getElementsByTagName("guid")[0].firstChild.nodeValue;
					}
				}
			}
		}

		var val = "user_id=" + (tmpId != null ? encodeURI(tmpId) : "");
		val += "&thread_id=" + (currentThreadId != null ? encodeURI(currentThreadId) : "");
		/* HTTPリクエスト実行 */
		userReq.open("POST", "./cgi/activateuser.php" , true);
		userReq.setRequestHeader("Cache-Control", "no-cache");
		userReq.setRequestHeader("Pragma", "no-cache");
		userReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		userReq.send(val);
	}
	
	function showRating_iphone() {
		iphoneSubWindow = window.open('../analyzer2.html', 'iphoneSubWin', 'directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no');
	}

	function threadView_iphone(ch, force) {
		if(boardMax || force) {
			channelLayerOverAllFalse();
			if(ch == 1) {
				selectThread(chIdList[0], chNameList[0]+"_");
			}else
			if(ch == 3) {
				selectThread(chIdList[1], chNameList[1]+"_");
			}else
			if(ch == 4) {
				selectThread(chIdList[2], chNameList[2]+"_");
			}else
			if(ch == 6) {
				selectThread(chIdList[3], chNameList[3]+"_");
			}else
			if(ch == 8) {
				selectThread(chIdList[4], chNameList[4]+"_");
			}else
			if(ch == 10) {
				selectThread(chIdList[5], chNameList[5]+"_");
			}else
			if(ch == 12) {
				selectThread(chIdList[6], chNameList[6]+"_");
			}
			_scrollStatus = false;
		}
		setCookie("channel", escape(initId.substring(0, initId.indexOf("_") + 1)));
		iphoneSubWindow = window.open('./thread.html?'+initId, 'iphoneSubWin', 'directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no');
	}

	function threadView_iphone2(ch, force) {
		if(boardMax || force) {
			channelLayerOverAllFalse();
			if(ch == 1) {
				selectThread(chIdList[0], chNameList[0]+"_");
			}else
			if(ch == 3) {
				selectThread(chIdList[1], chNameList[1]+"_");
			}else
			if(ch == 4) {
				selectThread(chIdList[2], chNameList[2]+"_");
			}else
			if(ch == 6) {
				selectThread(chIdList[3], chNameList[3]+"_");
			}else
			if(ch == 8) {
				selectThread(chIdList[4], chNameList[4]+"_");
			}else
			if(ch == 10) {
				selectThread(chIdList[5], chNameList[5]+"_");
			}else
			if(ch == 12) {
				selectThread(chIdList[6], chNameList[6]+"_");
			}
			_scrollStatus = false;
		}
		setCookie("channel", escape(initId.substring(0, initId.indexOf("_") + 1)));
	}

	function scrollBottom_iphone() {
		var targetNode = document.getElementById('boardmain');
		targetNode.scrollTop = targetNode.scrollHeight;
	}
	
	function initThread_iphone(id, isFull){
		// start = new Date();
		if(id == ""){
			errorRes("チャンネルを選択してください。");
			return ;
		}
		threadArray = new Array();
		threadDom = null;
		boardmainScrollval = 0;
		var initThreadreq = xmlHttpRequest();
		initThreadreq.onreadystatechange = function(){
	        if(initThreadreq.readyState == 4){
	            if(initThreadreq.status == 200){
	            	errorCount = 0;
	            	if(isFull) {
						speak = initThreadreq.responseXML.getElementsByTagName("speak");
						threadLen = speak.length;
						targetNode = document.getElementById('boardmain');
						targetNode.style.visibility = "visible"
						tableNode = document.getElementById('tablemain');
						tbody = document.getElementById('tbodymain');
						for(i = 0; i < threadLen; i++){
							if((!ballooMode && !(speak.item(i).getAttribute("location") == '2ch' || speak.item(i).getAttribute("location") == 'system_2ch'))
								|| (ballooMode && !mixMode && (speak.item(i).getAttribute("location") == '2ch' || speak.item(i).getAttribute("location") == 'system_2ch'))) {
								continue;
							}
							newTrNode = document.createElement("tr");
							newAttrWidhtLeft  = document.createAttribute("width");
							newAttrExpLeftId  = document.createAttribute("expID");
							newAttrWidhtRight = document.createAttribute("width");
							newAttrValign = document.createAttribute("valign");
							newAttrStyle = document.createAttribute("class");
							newAttrAlignLeftToRightTd  = document.createAttribute("align");
							newAttrWidhtLeft.value  ='5%';
							newAttrExpLeftId.value  = speak.item(i).getAttribute("no");
							newAttrWidhtRight.value ='95%';
							newAttrValign.value  ='top';
							newAttrStyle.value = 'left_no';
							newAttrAlignLeftToRightTd.value = 'left';

							if(ballooMode) {
								newTextLeftNode = document.createTextNode(speak.item(i).getAttribute("no"));
							}else{
								newTextLeftNode = document.createTextNode(speak.item(i).getAttribute("originalNum"));
							}
							newTdLeftNode  = document.createElement("td");
							newTdRightNode = document.createElement("td");
							newTdLeftNode.setAttributeNode(newAttrStyle);
							newTdLeftNode.setAttributeNode(newAttrWidhtLeft);
							newTdLeftNode.setAttributeNode(newAttrValign);
							newTdLeftNode.setAttributeNode(newAttrExpLeftId);
							
							newTdRightNode.setAttributeNode(newAttrWidhtRight);
							newTdRightNode.setAttributeNode(newAttrAlignLeftToRightTd);
							newTdLeftNode.appendChild(newTextLeftNode);
							// 改行をbrタグに置換
							// 指定文字列をアンカータグに変換
							if(speak.item(i).getAttribute("location") == '2ch') {
								str = "ID:" + speak.item(i).getAttribute("who") + "<br/>";
								str += speak.item(i).childNodes[0].nodeValue;
							}else
							if(speak.item(i).getAttribute("location") == 'balloo'){
								str = "<STRONG>";
								str += "ID:" + speak.item(i).getAttribute("who") + "<br/>";
								str += speak.item(i).childNodes[0].nodeValue + "</STRONG>";
							}else{
								str = speak.item(i).childNodes[0].nodeValue;
							}
							str = str.replace(/\n/g, "<br/>");
							str = str.replace(/&#60;/g, "<");
							str = str.replace(/&#62;/g, ">");
							threadArray.push(new dat(str, speak.item(i).getAttribute("no"), speak.item(i).getAttribute("timestamp"), speak.item(i).getAttribute("who"), speak.item(i).getAttribute("originalNum"), speak.item(i).getAttribute("originalID")));
							newTdRightNode.innerHTML = str;
							
							newTrNode.appendChild(newTdLeftNode);
							newTrNode.appendChild(newTdRightNode);
							tbody.appendChild(newTrNode);
						}
						//DEBUG
						threadLen = threadArray.length;
						
						font_color = getCookieValue("font_color");
						if(font_color != "undefined" && font_color != ""){
							changeFontColor(font_color);
						}else{
							font_color ="#000000";
						}
						
						bg_color = getCookieValue("bg_color");
						if(bg_color != "undefined" && bg_color != ""){
							changeBgColor(bg_color);
						}else{
							bg_color = "#FFFFFF";
						}

			            targetNode.scrollTop = targetNode.scrollHeight;
						document.title = "Balloo.iPhone - ";
						window.opener.currentThreadId = initThreadreq.responseXML.getElementsByTagName("thread").item(0).getAttribute("serial");

						tTimer = mStartWatch(tTimer, "threadUpdate_iphone('" + id + "')", 5000);
						window.opener.activate_iphone();
	            	}else{
						currentThreadId = initThreadreq.responseXML.getElementsByTagName("thread").item(0).getAttribute("serial");
						activate_iphone();
	            	}
				} else {
		            if(initThreadreq.status == 400){
		            	// 引数lastnoが不正
		            	errorRes_iphone("スレッドを取得できませんでした。");
		            }else if(initThreadreq.status == 404){
		            	// スレッドXMLファイルがない
		            	errorRes_iphoneerrorRes_iphone("スレッドが見つかりませんでした。");
		            }else{
		            	// そのほかのエラー
		            	errorRes_iphone("スレッドの初期化に失敗しました。");
		            }
					errorCount++;
					if(errorCount > 11) {
						mStopWatch(tTimer);
						tTimer = null;
		            	errorCount = 0;
					}
				}

	        }
//			scrollBottom_iphone();
	    }

	    /* HTTPリクエスト実行 */
	    reqTime = new Date();
	    initThreadreq.open("GET", "./cgi/getthread.php?thread_id=" + id + "&lastno=0" , true);
	    initThreadreq.setRequestHeader("Cache-Control", "no-chace");
	    initThreadreq.setRequestHeader("Pragma", "no-chace");
	    initThreadreq.send(null);
	}

	function initThread_iphone2(id, isFull){
		// start = new Date();
		if(id == ""){
			errorRes("チャンネルを選択してください。");
			return ;
		}
		threadView_iphone2(id, isFull)
		threadArray = new Array();
		threadDom = null;
		boardmainScrollval = 0;
		var initThreadreq = xmlHttpRequest();
		initThreadreq.onreadystatechange = function(){
	        if(initThreadreq.readyState == 4){
	            if(initThreadreq.status == 200){
	            	errorCount = 0;
	            	if(isFull) {
						speak = initThreadreq.responseXML.getElementsByTagName("speak");
						threadLen = speak.length;
						targetNode = document.getElementById('boardmain');
						targetNode.style.visibility = "visible"
						document.getElementById('closebutton').style.visibility = "visible";
						tableNode = document.getElementById('tablemain');
						tbody = document.getElementById('tbodymain');
						for(i = 0; i < threadLen; i++){
							if((!ballooMode && !(speak.item(i).getAttribute("location") == '2ch' || speak.item(i).getAttribute("location") == 'system_2ch'))
								|| (ballooMode && !mixMode && (speak.item(i).getAttribute("location") == '2ch' || speak.item(i).getAttribute("location") == 'system_2ch'))) {
								continue;
							}
							newTrNode = document.createElement("tr");
							newAttrWidhtLeft  = document.createAttribute("width");
							newAttrExpLeftId  = document.createAttribute("expID");
							newAttrWidhtRight = document.createAttribute("width");
							newAttrValign = document.createAttribute("valign");
							newAttrStyle = document.createAttribute("class");
							newAttrAlignLeftToRightTd  = document.createAttribute("align");
							newAttrWidhtLeft.value  ='5%';
							newAttrExpLeftId.value  = speak.item(i).getAttribute("no");
							newAttrWidhtRight.value ='95%';
							newAttrValign.value  ='top';
							newAttrStyle.value = 'left_no';
							newAttrAlignLeftToRightTd.value = 'left';

							newTextLeftNode = document.createTextNode(speak.item(i).getAttribute("originalNum"));
							newTdLeftNode  = document.createElement("td");
							newTdRightNode = document.createElement("td");
							newTdLeftNode.setAttributeNode(newAttrStyle);
							newTdLeftNode.setAttributeNode(newAttrWidhtLeft);
							newTdLeftNode.setAttributeNode(newAttrValign);
							newTdLeftNode.setAttributeNode(newAttrExpLeftId);
							
							newTdRightNode.setAttributeNode(newAttrWidhtRight);
							newTdRightNode.setAttributeNode(newAttrAlignLeftToRightTd);
							newTdLeftNode.appendChild(newTextLeftNode);
							// 改行をbrタグに置換
							// 指定文字列をアンカータグに変換
							if(speak.item(i).getAttribute("location") == '2ch' || speak.item(i).getAttribute("location") == 'balloo') {
								str = "　　ID:" + speak.item(i).getAttribute("who") + "<br/>";
								str += speak.item(i).childNodes[0].nodeValue;
//							}else
//							if(speak.item(i).getAttribute("location") == 'balloo'){
//								str = "<STRONG>";
//								str += "ID:" + speak.item(i).getAttribute("who") + "<br/>";
//								str += speak.item(i).childNodes[0].nodeValue + "</STRONG>";
							}else{
								str = speak.item(i).childNodes[0].nodeValue;
							}
							str = str.replace(/\n/g, "<br/>");
							str = str.replace(/&#60;/g, "<");
							str = str.replace(/&#62;/g, ">");
							threadArray.push(new dat(str, speak.item(i).getAttribute("no"), speak.item(i).getAttribute("timestamp"), speak.item(i).getAttribute("who"), speak.item(i).getAttribute("originalNum"), speak.item(i).getAttribute("originalID")));
							newTdRightNode.innerHTML = str;
							
							newTrNode.appendChild(newTdLeftNode);
							newTrNode.appendChild(newTdRightNode);
							tbody.appendChild(newTrNode);
						}
						//DEBUG
						threadLen = threadArray.length;
						
						font_color = getCookieValue("font_color");
						if(font_color != "undefined" && font_color != ""){
							changeFontColor(font_color);
						}else{
							font_color ="#000000";
						}
						
						bg_color = getCookieValue("bg_color");
						if(bg_color != "undefined" && bg_color != ""){
							changeBgColor(bg_color);
						}else{
							bg_color = "#FFFFFF";
						}

			            targetNode.scrollTop = targetNode.scrollHeight;
						document.title = "Balloo.iPhone - ";
						initThreadreq.responseXML.getElementsByTagName("thread").item(0).getAttribute("serial");

						tTimer = mStartWatch(tTimer, "threadUpdate_iphone('" + initId + "')", 5000);
						currentThreadId = initThreadreq.responseXML.getElementsByTagName("thread").item(0).getAttribute("serial");
						activate_iphone();
	            	}else{
						currentThreadId = initThreadreq.responseXML.getElementsByTagName("thread").item(0).getAttribute("serial");
						activate_iphone();
	            	}
				} else {
		            if(initThreadreq.status == 400){
		            	// 引数lastnoが不正
		            	errorRes_iphone("スレッドを取得できませんでした。");
		            }else if(initThreadreq.status == 404){
		            	// スレッドXMLファイルがない
		            	errorRes_iphone("スレッドが見つかりませんでした。");
		            }else{
		            	// そのほかのエラー
		            	errorRes_iphone("スレッドの初期化に失敗しました。");
		            }
					errorCount++;
					if(errorCount > 11) {
						mStopWatch(tTimer);
						tTimer = null;
		            	errorCount = 0;
					}
				}

	        }
//			scrollBottom_iphone();
	    }

	    /* HTTPリクエスト実行 */
	    reqTime = new Date();
	    initThreadreq.open("GET", "./cgi/getthread.php?thread_id=" + initId + "&lastno=-30" , true);
	    initThreadreq.setRequestHeader("Cache-Control", "no-chace");
	    initThreadreq.setRequestHeader("Pragma", "no-chace");
	    initThreadreq.send(null);
	}
	
	function hideThread_iphone2(){
		document.getElementById('boardmain').style.visibility = "hidden";
		document.getElementById('closebutton').style.visibility = "hidden";
		mStopWatch(tTimer);
		tTimer = null;
	}

	function errorRes_iphone(errorres){
			targetNode = document.getElementById('boardmain');
			tableNode = document.getElementById('tablemain');
			tbody = document.getElementById('tbodymain');
			newTrNode = document.createElement("tr");
			newAttrWidhtLeft  = document.createAttribute("width");
			newAttrWidhtRight = document.createAttribute("width");
			newAttrValign = document.createAttribute("valign");
			newAttrWidhtLeft.value  ='5%';
			newAttrWidhtRight.value ='95%';
			newAttrValign.value  ='top';
			newTextLeftNode = document.createTextNode("");
			newTdLeftNode  = document.createElement("td");
			newTdRightNode = document.createElement("td");
			newTdLeftNode.setAttributeNode(newAttrWidhtLeft);
			newTdLeftNode.setAttributeNode(newAttrValign);
			newTdRightNode.setAttributeNode(newAttrWidhtRight);
			newTdLeftNode.appendChild(newTextLeftNode);
			newTdRightNode.innerHTML = "<font color=\"red\">" + errorres + "</font>";
			newTrNode.appendChild(newTdLeftNode);
			newTrNode.appendChild(newTdRightNode);
			tbody.appendChild(newTrNode);
			targetNode.scrollTop = targetNode.scrollHeight;
			tableNode.appendChild(tbody);
		}

	/* スレッド表示 */
	function showThread_iphone() {
    	// speak = xmlhttp.responseXML.getElementsByTagName("speak");
    	// len = speak.length;
		if(threadLen < threadArray.length){
			// speak = xmlhttp.responseXML.getElementsByTagName("speak");
			targetNode = document.getElementById('boardmain');
			tableNode = document.getElementById('tablemain');
			tbody = document.getElementById('tbodymain');
			if(scrollFlg){
				targetNode.scrollTop = targetNode.scrollHeight;
			}
			// 取得したレス数
			// len = speak.length;
			// threadLen += len;
			// 現在表示されているのレス数
			// trLength = targetNode.getElementsByTagName("tr").length;
			len = threadArray.length;
			showTime = parseInt(threadArray[threadLen].time);
			for(i = threadLen; i < len; i++){
				if(showTime < parseInt(threadArray[i].time)){
					break;
				}
				
				newTrNode = document.createElement("tr");
				newAttrWidhtLeft  = document.createAttribute("width");
				newAttrExpLeftId  = document.createAttribute("expID");
				newAttrWidhtRight = document.createAttribute("width");
				newAttrValign = document.createAttribute("valign");
				newAttrAlignLeftToRightTd  = document.createAttribute("align");
				newAttrStyleRightTd = document.createAttribute("style");
				newAttrWidhtLeft.value  ='5%';
				newAttrExpLeftId.value  = threadArray[i].no;
				newAttrWidhtRight.value ='95%';
				newAttrValign.value  ='top';
				newAttrAlignLeftToRightTd.value = 'left';
				//TODO
				//FONT SIZE FIX!!
				//
				newAttrStyleRightTd.value = 'font-size:8pt;';
				//
				//
				threadLen++;
				if(prevOriginalThreadID) {
					if(threadArray[i].originalTID != prevOriginalThreadID) {
						prevOriginalThreadID = threadArray[i].originalTID;
					}
				}else{
					prevOriginalThreadID = threadArray[i].originalTID;
				}
				newTextLeftNode = document.createTextNode(threadArray[i].originalNo);
				newTdLeftNode  = document.createElement("td");
				newTdRightNode = document.createElement("td");
				newTdLeftNode.setAttributeNode(newAttrWidhtLeft);
				newTdLeftNode.setAttributeNode(newAttrValign);
				newTdLeftNode.setAttributeNode(newAttrExpLeftId);
				newTdRightNode.setAttributeNode(newAttrWidhtRight);
				newTdRightNode.setAttributeNode(newAttrAlignLeftToRightTd);
				newTdRightNode.setAttributeNode(newAttrStyleRightTd);
				newTdLeftNode.appendChild(newTextLeftNode);

				newTdRightNode.innerHTML = threadArray[i].res;
				newTrNode.appendChild(newTdLeftNode);
				newTrNode.appendChild(newTdRightNode);
				tbody.appendChild(newTrNode);
			}
			// スレッドが1000を越えたら先頭から削除
			// sumHeight = targetNode.scrollHeight;
			tbodyLen = tbody.getElementsByTagName("tr").length - 1000;
			if(tbodyLen > 0){
				for(i = 0; i < tbodyLen; i++){
					tbody.removeChild(tbody.firstChild);
					threadLen--;
					threadArray.shift();
				}
			}
			
			if(scrollFlg){
				scHeight = targetNode.scrollHeight - targetNode.scrollTop;
				if(scHeight > 0){
					sc = scHeight / 10;
					scTimeout = mStartWatch(scTimeout, "scrollThread(" + sc + ")", 100);
				}
			}
			
		}
	}
	