/**
 * フッター共通：ユーザ評価アンケート
 *
 * メイン処理
 *
 * @create 10/09/30
 * @last_update 10/10/06
 * @version 1.1
 */
var FooterUserAssessmentLog = {
	// local valiables
	ajax_url     : '/footer_enquete/log/log_page_eval',
	php_url      : '/footer_enquete/footer_enquete.php',
	counter_url  : '/footer_enquete/footer_counter_check.php',
	pretext_url  : '/footer_enquete/footer_counter_pretext.php',
	all_form     : ["q1", "q2", "q3", "q4", "q5"],  // 仕様上許可された全フォーム数（5個）
	divId        : "footer_user_assessment",
	formId       : "footer_user_log",
	c_dir        : null,            // コンテンツを表示しているディレクトリ
	refDiv       : null,            // アンケート表示するDIVのDOM保存
	data         : null,            // アンケート定義データ
	enqLog       : null,            // 使用されるアンケートのログ形式(A: Urchin, B:Urchin+PHP)
	enqReadtext  : null,            // 使用されるアンケートのリード文
	enqCaption   : null,            // 使用されるアンケートのキャプション
	prefix       : null,            // input系のidのprefix
	errorId      : null,            // 各inputのエラー表示用ID
	buttonId     : null,            // 送信ボタンID
	textareaIds  : [],              // TextareaのIDリスト
	textareaIdCounter       : null, // Textareaのカウンター表示用ID
	textareaIdsCounter_max  : null, // Textareaの入力上限文字数
	textareaSizeOver        : {},   // Textareaの入力上限を超えたフラグ
	form_data      : {},            // フォームデータ一覧
	ajax_log       : {},            // Ajax送信用
	php_log        : {},            // PHPへの送信用
	def_validation : {},            // Validationで使用するデータ
	tmpl_base               : null, // 全体テンプレート
	tmpl_thanks             : null, // 送信後のテンプレート
	tmpl_radio_check_select : null, // radio,chebkbox,select用のテンプレート
	tmpl_textarea           : null, // Textarea用のテンプレート
	divHeight               : null, // userAssessmentの高さを保存
	COUNTER_CHECK_OK        : "counter_check_ok",
	counter_is_max          : null,
	sid                     : null,
	pre_text                : null,
	text_prefix             : "FooterUserEnqueteData_",
	intervalId              : null,
	submit_flg              : false,
	sitecatalyst_log 		: [],	// サイトカタリスト用データ
	data_name				: null,	// data.name
	// Initialize
	init : function() {
		if (!this.checkBrowser()) return;
		this.refDiv            = $(this.divId);
		this.prefix            = this.formId + "_";
		this.errorId           = this.formId + "_error_";
		this.buttonId          = this.formId + "_button";
		this.textareaIdCounter = this.formId + "_counter_";
		// Return when refDiv is null
		//if (this.refDiv === null) return;
		this.c_dir = this.getCurrentDir();
		this.data = FooterUserAssessmentLogData.data;
		this.textareaIdsCounter_max = new Array();
		if (this.isCounterMax()) return;
		this.main();
	},

	// Browser Check
	checkBrowser : function() {
		var ua = navigator.userAgent.toLowerCase();
		if(/applewebkit[\/\s](\d+)/.test(ua)){
			//Safari 2 under
			var wkv = parseInt(RegExp.$1);
			if (wkv < 500)
				return false;
		}
		return true;
	},

	// Counter Check
	isCounterMax : function() {
		new Ajax.Request(
			this.counter_url,
			{
				method       : "get",
				asynchronous : false,
				onComplete   : function(request) {
					this.counter_is_max = request.responseText == this.COUNTER_CHECK_OK ? false : true;
				}.bindAsEventListener(this, false)
			}
		);
		return this.counter_is_max;
	},

	// Main
	main : function() {
		var d = null;
		var html = "";
		for (var i = 0; i < this.data.length; i += 1) {
			d = this.data[i];
			this.data_name = d.name;
			// 表示チェック
			if ( this.checkDir( d.inc_dirs, d.exc_dirs ) ) {
				// テンプレートをセット
				this.setHtmlTemplate();
				// アンケートの情報をセット
				this.ajax_url = this.ajax_url + d.name + ".html";
				this.enqLog = d.log;
				this.enqReadtext = d.read_text;
				this.enqCaption  = d.caption;
				for ( var j = 0; j < d.questions.length; j += 1 ) {
					// Validation要素
					this.def_validation[d.questions[j].q_name] = {
						"type" : d.questions[j].type,
						"must" : d.questions[j].must,
						"len"  : Object.isUndefined(d.questions[j].area_size) ? 0 : d.questions[j].area_size
					};
					// アンケート項目の抽出
					html += this.factoryHtml( d.questions[j] );
				}
				// アンケートHTML全体を出力
				this.printUserLogHtml(html, d);
				// textareaの入力監視設定
				for (var i = 0; i < this.textareaIds.length; i++) {
					Event.observe($(this.textareaIds[i]), "keyup", this.onKeyUpTextarea.bindAsEventListener( this ));
				}
				// Formの監視設定
				//Form.EventObserver(this.formId, changeFormEvent);
				// Submit監視設定
				Event.observe($(this.buttonId), "click", this.onSubmit.bindAsEventListener( this ));
				this.divHeight = $(this.formId).offsetHeight - 40;
				return;
			}
		}
	},

	// 現在のディレクトリ取得
	getCurrentDir : function() {
		var path = location.href;
		// location.hrefからスキーマ、ホスト名、ポート番号、クエリ文字、#を取り除く
		path = path.replace( new RegExp( location.protocol + "//" + location.hostname), "" );
		path = path.replace( ":80", "" );
		path = path.replace( location.hash, "" );
		path = path.replace( location.search, "" );
		if (path.lastIndexOf("/") === path.length - 1) {
			path += "index.html";
		}
		return path;
	},

	// ディレクトリチェック
	checkDir : function( inc_dirs, exc_dirs ) {
		// 404 ページが表示される場合の例外処理
		if ($("contenttop") && $("contenttop").innerHTML == "404 Not Found") return false;
		if (this.checkIncludeDir(inc_dirs) && this.checkExcludeDir(exc_dirs)) {
			//alert("OK : "+this.dir);
			return true;
		} else {
			//alert("NG : "+this.dir);
			return false;
		}
	},

	// 含むディレクトリチェック
	checkIncludeDir : function( inc_dirs ) {
		var re = null;
		for (var i = 0; i < inc_dirs.length; i += 1) {
			if (inc_dirs[i] == "") continue;
			re = new RegExp("^" + inc_dirs[i]);
			if (this.c_dir.match(re)) {
				return true;
			}
		}
		return false;
	},

	// 除外ディレクトリチェック
	checkExcludeDir : function( exc_dirs ) {
		var re = null;
		for (var i = 0; i < exc_dirs.length; i += 1) {
			if (exc_dirs[i] == "") continue;
			re = new RegExp("^" + exc_dirs[i]);
			if (this.c_dir.match(re)) {
				return false;
			}
		}
		return true;
	},

	// 各種アンケートHTML生成用factoryメソッド
	factoryHtml : function( question ) {
		switch( question.type ) {
		case "radio":
			return this.factoryRadio( question );
			break;
		case "select":
			return this.factorySelect( question );
			break;
		case "checkbox":
			return this.factoryCheckbox( question );
			break;
		case "textarea":
			return this.factoryTextarea( question );
			break;
		}
	},

	// RadioボタンパターンのHTML生成
	factoryRadio : function( question ) {
		var r_html = "";
		var replace = null;
		var t_radio = '<span class="q_sbox"><input type="radio" name="#{q_name}" value="#{q_value}" id="' + this.prefix + '#{q_id}"><label for="' + this.prefix + '#{q_id}">#{q_view}</label></span>　';
		// radio template
		var radio_tmpl = new Template( t_radio );
		$H(question.q).each(function (pair) {
			replace = {
				q_name : question.q_name,
				q_id : question.q_name + pair.key,
				q_value : pair.key,
				q_view  : pair.value
			};
			r_html += radio_tmpl.evaluate( replace );
		});
		return this.getBlockHtmlFromTempl(question, r_html, true);
	},

	// プルダウンメニューのHTML生成
	factorySelect : function( question ) {
		var s_html = "";
		var t_select = '<select name="#{q_name}"id="' + this.prefix + '#{q_id}"><option value="">---1つ選択してください---</option>#{options}</select>';
		// select template
		var select_tmpl = new Template( t_select );
		$H(question.q).each(function (pair) {
			s_html += '<option value="' + pair.key + '">' + pair.value + '</option>';
		});
		var replace = {
			q_name : question.q_name,
			q_id : question.q_name,
			options  : s_html
		};
		s_html = select_tmpl.evaluate( replace );
		return this.getBlockHtmlFromTempl(question, s_html, false);
	},

	// CheckboxのHTML生成
	factoryCheckbox : function( question ) {
		var c_html = "";
		var replace = null;
		var t_checkbox = '<span class="q_sbox"><input type="checkbox" name="#{q_name}" value="#{q_value}" id="' + this.prefix + '#{q_id}"><label for="' + this.prefix + '#{q_id}">#{q_view}</label></span>　';
		// checkbox template
		var checkbox_tmpl = new Template( t_checkbox );
		$H(question.q).each(function (pair) {
			replace = {
				q_name : question.q_name,
				q_id : question.q_name + pair.key,
				q_value : pair.key,
				q_view  : pair.value
			};
			c_html += checkbox_tmpl.evaluate( replace );
		});
		return this.getBlockHtmlFromTempl(question, c_html, false);
	},

	// 設問ブロックのHTML生成(radio, checkbox, select)
	getBlockHtmlFromTempl : function (question, html, isRadio) {
		var left_t = "", right_t = "";
		if (isRadio) {
			left_t = question.left_t;
			right_t = question.right_t;
		}
		// question block template
		var block_tmpl = new Template (this.tmpl_radio_check_select);
		replace = {
			question_title : question.question_t,
			error_id       : this.errorId + question.q_name,
			left           : '<span class="q_sbox">' + left_t + '</span>',
			input          : html,
			right          : '<span class="q_sbox">' + right_t + '</span>',
			caption        : question.caption
		};
		return block_tmpl.evaluate( replace );
	},

	// TextareaのHTML生成
	factoryTextarea : function( question ) {
		var area_id = this.prefix + question.q_name;
		this.textareaIds.push(area_id);
		this.textareaSizeOver[area_id] = true;
		this.textareaIdsCounter_max[question.q_name] = question.area_size;
		var block_tmpl = new Template (this.tmpl_textarea);
		var replace = {
			question_title : question.question_t,
			counter_id     : this.textareaIdCounter + question.q_name,
			counter_len    : this.getTextareaCharLength(question.area_size),
			area_size      : question.area_size,
			error_id       : this.errorId + question.q_name,
			name           : question.q_name,
			rows           : question.area_rows,
			id             : area_id,
			caption        : question.caption == "" ? "" : question.caption + "<br>"
		};
		return block_tmpl.evaluate( replace );
	},

	// Textareaの文字数カウント
	onKeyUpTextarea : function (evtObj) {
		var target = Event.element(evtObj);
		var q_name = target.id.split('_');
		var counterid = this.textareaIdCounter + q_name[3];
		//alert($(counterid));
		//var len1 = this.textareaIdsCounter_max[q_name[3]];
		//alert(len1);
		//var len2 = target.value.length;
		//alert(len2);
		//var len = len1 - len2;
		var len = this.textareaIdsCounter_max[q_name[3]] - target.value.length;
		if (len < 0) {
			// 文字数オーバーしている時は-1をかけて+にする
			$(counterid).innerHTML = this.getTextareaCharLengthOver(len * -1);
			this.textareaSizeOver[target.id] = false;
		} else {
			$(counterid).innerHTML = this.getTextareaCharLength(len);
			this.textareaSizeOver[target.id] = true;
		}
	},

	// 設問HTML書き出し
	printUserLogHtml : function( html, d ) {
		var tmpl = new Template(this.tmpl_base),
		replace = {
			form_id   : this.formId,
			button_id : this.buttonId,
			read_text : d.read_text,
			caption   : d.caption,
			body      : html
		};
		this.refDiv.innerHTML = tmpl.evaluate(replace);
	},

	// 送信ボタンを押された
	onSubmit : function () {
		// 連打対策
		if (this.submit_flg) return false;
		var f_data = $(this.formId).serialize({ hash : true });
		this.getFormData(f_data);
		// チェックと送信
		if (this.validation()) {
			// 連打対策
			if (!this.submit_flg) this.submit_flg = true;
			// 外部スクリプト読み込み
			var m = document.createElement('script');
			m.src = '/js/common/lib/mcrypt.js';
			document.body.appendChild(m);
			var b = document.createElement('script');
			b.src = '/js/common/lib/base64.js';
			document.body.appendChild(b);
			this.intervalId = setInterval(this.checkObject.bind(this), 100);
		}
	},

	// Object読み込みチェック
	checkObject : function () {
		if (typeof(blowfish) == "object" && typeof(base64) == "object") {
			clearInterval(this.intervalId);
			this.getPreText();
			this.makePostData();
			this.postUserLog();
		}
	},

	// pre_text取得
	getPreText : function () {
		new Ajax.Request(
			this.pretext_url,
			{
				method       : "get",
				asynchronous : false,
				onComplete   : function(request) {
					var json;
					eval("json="+request.responseText);
					this.sid      = json.sid;
					this.pre_text = json.key;
				}.bindAsEventListener(this, false)
			}
		);
	},

	// Formのデータを取得する。
	// 項目が未入力の場合は空の要素を入れている（後でValidateで使うため）
	getFormData : function (f_data) {
		var temp = "";
		$H(this.def_validation).each (function (v) {
			if (f_data[v.key] == null || f_data[v.key].value == "") {
				this.form_data[v.key] = "";
			} else {
				temp = Object.isArray(f_data[v.key]) ?  f_data[v.key].join('') : f_data[v.key];
				this.form_data[v.key] = temp.replace(/^[\s　]+|[\s　]+$/g, '');
				//this.form_data[v.key] = Object.isArray(f_data[v.key]) ?  f_data[v.key].join('') : f_data[v.key];
			}
		}, this);
	},

	// FormデータからPostするためのQueryStringを生成
	makePostData : function () {
		var all = [], val = "", php_val = "", isTextarea = false, id = [];
		this.ajax_log = Object.clone(this.form_data);
		$A(this.all_form).each (function (a) {
			if (Object.isUndefined(this.form_data[a])) {
				this.php_log[a] = "";
			} else {
				isTextarea = $A(this.textareaIds).find (function (val, i) {id = val.split('_'); return a == id[3];}) ? true : false;
				if (isTextarea) {
					if (this.form_data[a] == "") {
						val   = 0;
						php_val = "";
					} else {
						val = 1;
						var usr = {
							data : this.text_prefix + this.form_data[a],
							key : this.pre_text, mode : "cbc", round : 16,
							iv : blowfish.mkIV(), pchar : "\0"
						};
						var temp = blowfish.encrypt(usr);
						php_val = base64.encode(temp);
					}
				} else {
					val     = this.form_data[a] == "" ? "none" : this.form_data[a];
					php_val = this.form_data[a];
				}
				all.push(val);
				this.ajax_log[a] = val;
				this.php_log[a]  = php_val;
			}
		}, this);
		this.ajax_log[this.c_dir] = all.join("__");
		this.ajax_log["ALL"]      = all.join("__");
		this.php_log["dir"]       = this.c_dir;
		this.php_log["sid"]       = this.sid;
		//以下サイトカタリスト用追加
		this.sitecatalyst_log[0]  = "CRP_ENQ";//固定値
		this.sitecatalyst_log[1]  = this.data_name;
		this.sitecatalyst_log[2]  = this.ajax_log["ALL"];
		this.sitecatalyst_log[3]  = this.c_dir;
	},

	// 入力チェック
	validation : function () {
		var isError = false;
		// 必須チェック
		$H(this.def_validation).each (function (v) {
			if (v.value.must && this.form_data[v.key] == "") {
				this.printError(v, true);
				isError = true;
			} else {
				this.printError(v, false);
			}
		}, this);
		// Textarea文字数チェック
		$H(this.textareaSizeOver).each (function (ta) {
			if (ta.value == false) {
				isError = true;
			}
		});
		return isError ? false : true;
	},

	// エラー文言表示
	printError : function (v, isError) {
		if (isError) {
			var msg = "";
			if (v.value.type == "textarea") {
				msg = '　※<span class="red01">入力してください</span>';
			} else {
				msg = '　※<span class="red01">選択してください</span>';
			}
			$(this.errorId + v.key).innerHTML = msg;
		} else {
			$(this.errorId + v.key).innerHTML = '';
		}
	},

	// Postの制御
	postUserLog : function( res ) {
		//サイトカタリスト追加
		this.doSitecatalyst();
		if (this.enqLog == "B") {
			// PHP
			this.doAjax("post", this.php_url, this.php_log, true);
		} else {
			this.printThanksHtml();
		}
	},

	// ajax
	doAjax : function (req_method, req, param, isEnd) {
		var query = $H(param).toQueryString();
		new Ajax.Request(
			req,
			{
				method     : req_method,
				parameters : req_method == "get"  ? query : "",
				postBody   : req_method == "post" ? query : "",
				onSuccess  : isEnd ? this.printThanksHtml.bind(this) : function(request){},
				on403      : req_method == "post" ? this.print403.bind(this) : function(request){}
			}
		);
	},

	doSitecatalyst : function() {
		s.linkTrackVars = "prop26,eVar26";
		s.prop26 = s.eVar26 = this.sitecatalyst_log.join("_");
		s.tl( $(this.buttonId), 'o', s.prop26 );
	},

	// ThanksHTML書き出し(Callback)
	printThanksHtml : function() {
		var tmpl = new Template(this.tmpl_thanks),
		replace = {
			form_id  : this.formId,
			height   : this.divHeight,
			question : "ご回答ありがとうございました。"
		};
		this.refDiv.innerHTML = tmpl.evaluate(replace);
	},

	// Post時にPHPが不正文字列を取得して403エラーを返してきた(Callback)
	print403 : function() {
		var tmpl = new Template(this.tmpl_thanks),
		replace = {
			form_id  : this.formId,
			height   : this.divHeight,
			question : "不正なデータが送信されました。<br>ページをリロードしてから再送信してください。"
		};
		this.refDiv.innerHTML = tmpl.evaluate(replace);
	},

	// Textareaの入力可能文字数
	getTextareaCharLength : function (len) {
		return ' <font color="blue">あと' + len + '文字入力可能です</font>';
	},

	// Textareaの入力可能文字数(文字数制限オーバー)
	getTextareaCharLengthOver : function (len) {
		return ' <span class="red01">入力可能文字数の上限を' + len + '文字超えています</span>';
	},
//			'<input type="image" src="/images/footer/btn_submit.gif" alt="送信" align="middle" id="#{button_id}">' +

	// HTMLテンプレートの設定
	setHtmlTemplate : function () {
		this.tmpl_base =
			'<form id="#{form_id}" action="javascript:void(0);" onsubmit="return false;">' +
			'<div id="q_boxMain"><div class="q_box"><div class="wrap"><div class="section">' +
			'<div class="q_read">' +
			'<p class="txt"><strong>#{read_text}</strong></p>' +
			'</div>' +
			'#{body}' +
			'<div class="acenter">' +
			'<input type="submit" alt="送信" align="middle" id="#{button_id}" value="送信">' +
			'</div>' +
			'<div class="q_read">' +
			'<p class="txt">#{caption}</p>' +
			'</div>' +
			'</div></div></div></div>' +
			'</form>';

		this.tmpl_radio_check_select =
			'<div class="q_Item"><table class="q_footer">' +
			'<tr><td><strong class="txt">#{question_title}</strong><span id="#{error_id}" class="txt"></span></td></tr>' +
			'<tr><td>' +
			'<p class="txt q_Itembox">#{left}#{input}#{right}</p>' +
			'</td></tr><tr><td>' +
			'<p class="txt">#{caption}</p>' +
			'</td></tr>' +
			'</table></div>';

		this.tmpl_textarea =
			'<div class="q_Item"><table class="q_footer">' +
			'<tr><td><strong class="txt">#{question_title}(#{area_size}文字以内)</strong> ' + 
			'<span id="#{counter_id}" class="txt">#{counter_len}</span><span id="#{error_id}" class="txt"></span></td></tr>' +
			'<tr><td>' +
			'<p class="txt"><textarea name="#{name}" rows="#{rows}" id="#{id}" cols="85"></textarea></p>' +
			'</td></tr><tr><td>' +
			'<p class="txt">#{caption}※<span class="red01">いただいたご意見に関するこちらからの返信は行いませんので、個人情報の記入はご遠慮ください。</span></p>' +
			'</td></tr>' +
			'</table></div>';

		this.tmpl_thanks =
			'<form name="#{form_id}"><div id="q_boxMain"><div class="q_box"><div class="wrap"><div class="section">' +
			'<table class="txt q_footer"><tr height="#{height}"><td><strong>#{question}</strong></td>' +
			'</tr><tr><td>&nbsp;</td></tr></table></div></div></div></div></form>';
	}
}

Event.observe( window, "load", FooterUserAssessmentLog.init.bindAsEventListener( FooterUserAssessmentLog ));

