// DomContentLoaded
$(function(){
	
	updated = false;
	updated_id = null;
	
	newPost = $("#newpost");
	newComment = $("#updateArea");
	
	inputArea = $("#newInputArea");
	inputText = inputArea.find("span.inputText input");
	inputBtn  = inputArea.find("span.inputBtn input");
	
	dummy = $("#dummyImage");
	errBox = $("#errorMessage");
	
	newTextArea = $("#update_text");
	newDateArea = $("#update_date");
	
	/* 未回答チェック */
	
	var unAnswered = $("#unAnswered");
	
	if ( unAnswered.size() > 0) {
		updated = true;
		updated_id = unAnswered.val();
		successPostEvent(updated_id);
	};
		
	/* 新規投稿 */
	
	newPost.bind("submit", function(){
		return false;
	});
	
	inputText.bind("keydown", sendNewPostKeyDown);
	inputBtn.bind("click", sendNewPost);
});


/* 新規投稿イベント */

function sendNewPostKeyDown(e) {
	if ( e.keyCode == 13 ) {
		sendNewPost();
	}
}

function sendNewPost() {
	
	var errmes = "";
	
	// unBind
	inputBtn.unbind("click", sendNewPost);
	inputText.unbind("keydown", sendNewPostKeyDown);
	
	// 空文字だったらreturn
	if(inputText.val()=='') return false;
	
	// エラー隠す
	errBox.fadeOut("slow");
	
	options = {
		success: function(data){
			data = data.replace(/<.+>/, "");
			
			if (!isNaN(data)) {
				successPostEvent(data);
				$("#content .userBox p.deleteBtnContainer .hide_note_num:first").val(data);
				inputText.val("");
			} else {
				disablePostForm(false);
				showError(__vals.error_default);
			}
			
			inputBtn.bind("click", sendNewPost);
			inputText.bind("keydown", sendNewPostKeyDown);
		},
		error  : function(){
			
			//失敗
			if ( inputText.val().length > 140 ) {
				errmes = __vals.error_wordover;
			} else {
				errmes = __vals.error_default;
			}
			
			disablePostForm(false); // 判定後に入れないとダメらしい
			showError(errmes);
			$("#js_timer").hide();
			
			inputBtn.bind("click", sendNewPost);
			inputText.bind("keydown", sendNewPostKeyDown);
		}
	};
	
	disablePostForm(true);
	
	var today = new Date();
	
	// 2010.00.00 00:00
	var dispDate = 
		today.getFullYear() + "." + 
		zeroSup(today.getMonth()  , 2) + "." + 
		zeroSup(today.getDate()   , 2) + " " + 
		zeroSup(today.getHours()  , 2) + ":" + 
		zeroSup(today.getMinutes(), 2);
	
	// 入力エリアの発言内容をコピー、投稿時刻をセット
	newTextArea.html(inputText.val().replace(/</g,"&lt;").replace(/>/g,"&gt;"));
	newDateArea.html(dispDate);
	
	//js=trueオプションをfieldsetに設定
	newPost.find("#NoteJs").val("true");
	
	//フォーム送信
	newPost.ajaxSubmit(options);
	
	return false;
}

/* エラーメッセージの表示 */

function showError(message) {
	
	errBox.html(message);
	errBox.fadeIn("slow");
}

/* 新規投稿時の待機処理 */

function successPostEvent(data){
	
	// 投稿内容を追加、表示
	newComment.find("div.commentBoxText").html('<span class="searchText"><img src="'+ __webroot +'images/text_baloon_search.gif" alt="探し中です" width="129" height="29" /></span><span class="searchLoading"><img src="'+ __webroot +'images/timer1.gif" alt="ローディング" /></span>');
	newComment.fadeIn("slow");
	
	disablePostForm(true);
	$("#js_timer").hide();
	
	if ( updated == false ) {
		updated_id = data.replace(/<.+>$/, ""); // デバッグ文除去
		updated = true;
	}
	
	// 回答チェック発動
	newPost.everyTime( __vals.time_botreply , checkBotReply );
}


/* BOTからの回答チェック */
	
function checkBotReply() {
	
	if ( updated == true && updated_id != null ) {
		// 回答チェックフォームをsubmit
		
		// 現在時刻をセット(IE対策)
		var response = $.get(
			__webroot + "javascripts/?func=get_bot_reply&note_id="
			+ updated_id + "&time="+(new Date).getTime(), 
			function(data) {
			// 通信成功
			data = data.replace(/<.+>$/, "");
			if ( !isNaN(data) ) {
				// タイマー停止
				$("#newpost").die();
				updated    = false;
				updated_id = null;
				++updated_count; // 更新件数に+1
				reloadThread(Number(data)+1); // スレッド再描画
				disablePostForm(false);
				// 更新件数をリセット
				$.get(__webroot + "javascripts/?func=get_notes_count", function(data){
					updated_count = parseInt(data.replace(/<.+>/,""));
					$("#updateMessageWrapper > *").hide();
					$("#updateCount").html(parseInt(data.replace(/<.+>/,"")));
				});
			}
		});
	}
};

// 入力エリアの有効を切り返る
function disablePostForm(bool) {

	inputBtn.disabled  = bool;
	inputText.disabled = bool;
	
	if (!bool) {
		dummy.hide();
		inputArea.show();
	} else {
		inputArea.hide();
		dummy.show();
	}
	
}

// ゼロ埋め
function zeroSup(val,dig) {
	var len = String(val).length;
	var supVal = val;
	for (var i=len; i < dig; i++) {
		supVal = String(0) + String(supVal);
	}
	
	return supVal;
}
