/*======================================================
初期設定
======================================================*/
//読み込むフォームのhtml
var file = "form.html";
//フォーム全体のid名
var formContentsID = "#contact";
//form要素のid名
var formID = "#mailform";
//オーバーレイするレイヤーの透明度（0〜1）
var overlayOpacity = 1;
//オーバーレイするレイヤーの背景色
var overlayColor = "#35a8d7";
//オーバーレイするレイヤーの背景イメージとポジション
var overlayImage = "url(images/bg.jpg) repeat-x left center";
//確認画面で複数の項目を区切る文字
var separator = ", ";

//確認画面を表示中かどうかのフラグ
var isConfirm;

/*======================================================
ドキュメント読み込み後の処理
======================================================*/
$(document).ready(function(){
	//選択枠を隠す
	$('a').focus(function(e){this.blur()});
});

/*======================================================
オーバーレイフォームを開く
======================================================*/
function showform(){
	
	//確認画面表示中フラグをfalseに
	isConfirm = false;

	//オーバーレイ用要素を追加
	$("body").append('<div id="overlayForm"></div>');

	//背景とフォーム読み込み用要素を追加
	$("#overlayForm")
		.append('<div id="overlayBg"></div>')
		.append('<div id="formcontents"></div>');

	//オーバーレイのCSSを設定
	$("#overlayForm")
		.css("position", "fixed")
		.css("display","none")
		.css("overflow","hidden");

	//オーバーレイの配置を更新
	overlayPosition();

	//背景のCSSを設定
	$("#overlayBg")
		.css("width", "100%")
		.css("height", "100%")
		.css("background", overlayColor + " " + overlayImage)
		.css("opacity", overlayOpacity)
		.css("position", "absolute")
		.css("left", "0")
		.css("top", "0")
		.css("overflow","hidden");

	//背景クリックでフォームを閉じる
	//$("#overlayBg").click(closeform);

	//フェードインしてフォームを読み込み
	$("#overlayForm").fadeIn(500,function(){
		$("#formcontents").load("./" + file + " " + formContentsID , null, onLoaded);
	});
}

/*======================================================
フォームの読み込み完了後の処理
======================================================*/
function onLoaded(){

  	//ボタンエリアに「normal」クラスを追加し、ボタンのラベルを書き変える
	$("div.buttonArea", $(this))
		.addClass("normal")
		.find('button').html("送信内容を確認");

	//読み込んだフォームのCSSを設定（画面下に配置）
	$(this).css("position", "absolute")
	.css(centerposition(this))
	.css("top", $(window).height() + $(window).scrollTop() + "px");

	//画面下からフレームインする
	$(this).animate(centerposition(this),1000,"easeOutExpo");
}

/*======================================================
センターへ配置
======================================================*/
function centerposition(obj){
	var position = new Object();
	position["left"] = ($(window).width() - $(obj).outerWidth())/2; 
	position["top"] = ($(window).height() - $(obj).outerHeight())/2;
	position["marginLeft"] = 0;
	position["marginTop"] = 0;
	return position;
}

/*======================================================
オーバーレイの配置を更新
======================================================*/
function overlayPosition(){
	$('#overlayForm')
		.css('left', "0")
		.css('top', "0")
		.css('width', $(window).width() + "px")
		.css('height', $(window).height() + "px")
	$('#test').html($(document).width());
	if($("#formcontents").length){
		$("#formcontents").css(centerposition($("#formcontents")));
	}
}

/*======================================================
スクロール、リサイズ時の処理
======================================================*/
$(window).scroll(overlayPosition);
$(window).resize(overlayPosition);

/*======================================================
入力フォーム画面から確認画面へ変更
======================================================*/
function comfirm(){

	//フォーム内容のチェック（エラーがあれば中止）
	if(!validate($(formObject))){
		return;
	}

	//入力フォーム画面をいったんフェードアウトして隠し、内容を更新
	$("#formcontents").css(centerposition($("#formcontents"))).animate({opacity:"0", marginLeft:"-100px"},400,"easeOutExpo",function(){

		//確認画面用タイトル追加（元のタイトルを隠す）
		$("h3", $(this)).addClass("normal");
		$("h3", $(this)).clone(true)
			.removeClass("normal")
			.addClass("confirm")
			.html("送信内容の確認")
			.insertAfter("#formcontents h3");
	
		//確認画面用のボタンを追加（元のボタンを隠す）
		$("div.buttonArea", $(this)).clone(true)
			.removeClass("normal")
			.addClass("confirm")
			.html('<button type="button" id="returnButton">内容を修正</button><button type="send" id="sendButton">この内容で送信</button>')
			.insertAfter("#formcontents div.buttonArea");
		$("#returnButton").css("background","#ccc");
		$("#returnButton").click(returnForm);
	
		//フォームの内容を確認画面用に切り替える
		$("input, textarea, select", $(formID)).each(function(i){

			//フォーム項目にすべて「nomal」クラスを付加する
			$(this).addClass("normal");

			//フォームの値を格納する変数
			var valueStr;

			//valueの型や値による処理分岐
			if(!$(this).val()) {
				//valueが偽だった場合
				var valueStr = "";
			} else if($(this).val() instanceof Array){
				//valueが配列だった場合
				var valueArray = $(this).val();
				for (i=0; i<valueArray.length; i++){
					if(valueStr){
						valueStr =  valueStr + separator + valueArray[i];
					} else {
						valueStr = valueArray[i];
					}
				}
			} else {
				//それ以外
				valueStr = $(this).val();
			}

			//フォームのタイプによる処理分岐
			//フォームの要素を隠してvalueをp要素として配置
			if($(this).attr("type") == "radio") {
				//ラジオボタンの場合
				var thisID = $(this).attr("id");
				$("label[for=" + thisID + "]", $(formID)).addClass("normal");
				if($(this).prop("checked")) {
					$(this).after('<p class="confirm">'+ valueStr +'</p>');
				}
			} else if($(this).attr("type") == "checkbox") {
				//チェックボックスの場合
				var thisID = $(this).attr("id");
				$("label[for=" + thisID + "]", $(formID)).addClass("normal");
				if($(this).prop("checked")) {
					$(this).after('<p class="confirm">'+ valueStr +'</p>');
				}
			} else if(this.tagName == "SELECT") {
				//選択リストの場合
				$(this).after('<p class="confirm">'+ valueStr +'</p>');
			} else if(this.tagName == "TEXTAREA") {
				//テキストエリアの場合
				valueStr = valueStr.replace(/\r\n/g, "<br />");
				valueStr = valueStr.replace(/(\n|\r)/g, "<br />");
				$(this).after('<p class="confirm">'+ valueStr +'</p>');
			} else {
				//それ以外（テキストフィールドなど）
				$(this).after('<p class="confirm">'+ valueStr +'</p>');
			}
		});

		//「nomal」クラスのオブジェクトをすべて隠す
		$(".normal", $(this)).hide();
		//「confirm」クラスのオブジェクトをすべて表示
		$(".confirm", $(this)).show();

		//値を格納した段落のCSSを設定
		$("p.confirm", $(this))
			.css("line-height","1.6")
			.css("display","inline");

		//値が複数ある場合の処理（区切り文字の追加）
		$(".field").each(function(i){
			$("p.confirm:not(:last)" ,$(this)).each(function(j){
				$(this).append(separator);
			});
		});

		//確認画面をフェードイン
		$(this).css(centerposition(this)).css("margin-left","100px").animate({opacity:"1", marginLeft: "0"},400,"easeOutExpo");
		
		//確認画面表示中フラグをtrueに
		isConfirm = true;
	});
	
}

/*======================================================
確認画面から入力フォーム画面へ戻る
======================================================*/
function returnForm(){

	//確認画面をいったんフェードアウトして隠し、内容を更新
	$("#formcontents").css(centerposition($("#formcontents"))).animate({opacity:"0", marginLeft: "100px"},400,"easeOutExpo",function(){

		//「nomal」クラスのオブジェクトをすべて表示
		$(".normal", $(this)).show();
		//「confirm」クラスのオブジェクトをすべて削除
		$(".confirm", $(this)).remove();

		//入力フォーム画面をフェードイン
		$(this).css(centerposition(this)).css("margin-left","-100px").animate({opacity:"1", marginLeft: "0"},400,"easeOutExpo");

		//確認画面表示中フラグをfalseに
		isConfirm = false;
	});
}


/*======================================================
閉じる
======================================================*/
function closeform(){
	$("#overlayForm").fadeOut(250,function(){$(this).remove()});

}











/*======================================================
初期設定
======================================================*/
var overlayOpacity = 0.8;
var overlayColor = "#000";

//確認画面で複数の項目を区切る文字
var separator = ", ";

var file = "form.html";
var formContentsID = "#contact";
var formObject;


/*======================================================
ドキュメント読み込み後の処理
======================================================*/
$(document).ready(function(){

	//選択枠を隠す
	$('a').focus(function(e){this.blur()});

});

/*======================================================
閉じる
======================================================*/
function closeform(){
	$("#overlayForm").fadeOut(250,function(){$(this).remove()});

}

/*======================================================
センターへ配置
======================================================*/
function centerposition(obj){
	var position = new Object();
	position["left"] = ($(window).width() - $(obj).outerWidth())/2 + $(window).scrollLeft(); 
	position["top"] = ($(window).height() - $(obj).outerHeight())/2 + $(window).scrollTop();
	position["marginLeft"] = 0;
	position["marginTop"] = 0;
	return position;
}

/*======================================================
オーバーレイの配置を更新
======================================================*/
function overlayPosition(){
	$('#overlayForm')
		.css('left', "0")
		.css('top', "0")
		.css('width', $(document).width() + "px")
		.css('height', $(document).height() + "px")
	$('#test').html($(document).width());
	if($("#formcontents").length){
		$("#formcontents").stop(false, true).animate(centerposition($("#formcontents")),"fast");
	}
}

/*======================================================
スクロール、リサイズ時の処理
======================================================*/
$(window).scroll(overlayPosition);
$(window).resize(overlayPosition);

/*======================================================
オーバーレイフォームを開く
======================================================*/
function showform(){

	//オーバーレイ用要素を追加
	$("body").append('<div id="overlayForm"></div>');

	//背景とフォーム読み込み用要素を追加
	$("#overlayForm")
		.append('<div id="overlayBg"></div>')
		.append('<div id="formcontents"></div>');

	//オーバーレイのCSSを設定
	$("#overlayForm")
		.css("position", "absolute")
		.css("display","none")
		.css("overflow","hidden");

	//オーバーレイの配置を更新
	overlayPosition();

	//背景のCSSを設定
	$("#overlayBg")
		.css("width", "100%")
		.css("height", "100%")
		.css("background", overlayColor)
		.css("opacity", overlayOpacity)
		.css("position", "absolute")
		.css("left", "0")
		.css("top", "0")
		.css("overflow","hidden");

	//背景クリックでフォームを閉じる
	//$("#overlayBg").click(closeform);

	//フェードインしてフォームを読み込み
	$("#overlayForm").fadeIn(500,function(){$("#formcontents").load("./" + file + " " + formContentsID ,null,onLoaded)});
}

/*======================================================
フォームの読み込み完了後の処理
======================================================*/
function onLoaded(){

	formObject = $("#mailform");

	//ボタンエリアを書き変える
	$("div.buttonArea", $(this))
		.addClass("normal")
		.html('<button type="button" id="confirmButton">送信内容を確認</button>');
	//ボタンで確認画面を表示するように設定
	$("#confirmButton").click(comfirm);


	//読み込んだフォームのCSSを設定（画面下に配置）
	$(this).css("position", "absolute")
	.css(centerposition(this))
	.css("top", $(window).height() + $(window).scrollTop() + "px");

	//画面下からフレームインする
	$(this).animate(centerposition(this),500,"easeOutExpo");
}

/*======================================================
入力フォーム画面から確認画面へ変更
======================================================*/
function comfirm(){

	//フォーム内容のチェック（エラーがあれば中止）
	if(!validate($(formObject))){
		return;
	}

	//入力フォーム画面をいったんフェードアウトして隠し、内容を更新
	$("#formcontents").css(centerposition($("#formcontents"))).animate({opacity:"0", marginLeft:"-100px"},400,"easeOutExpo",function(){

		//確認画面用タイトル追加（元のタイトルを隠す）
		$("h3", $(this)).addClass("normal");
		$("h3", $(this)).clone(true)
			.removeClass("normal")
			.addClass("confirm")
			.html("送信内容の確認")
			.insertAfter("#formcontents h3")
			.hide();
	
		//確認画面用のボタンを追加（元のボタンを隠す）
		$("div.buttonArea", $(this)).clone(true)
			.removeClass("normal")
			.addClass("confirm")
			.html('<button type="button" id="returnButton">内容を修正</button><button type="send" id="sendButton">この内容で送信</button>')
			.insertAfter("#formcontents div.buttonArea")
			.hide();
		$("#returnButton").css("background","#ccc");
		$("#returnButton").click(returnField);
	

		//フォームの内容を確認画面用に切り替える
		$("input, textarea, select", $(formObject)).each(function(i){

			//フォーム項目にすべて「nomal」クラスを付加する
			$(this).addClass("normal");

			//フォームの値を格納する変数
			var valueStr;

			//valueの型や値による処理分岐
			if(!$(this).val()) {
				//valueが偽だった場合
				var valueStr = "";
			} else if($(this).val() instanceof Array){
				//valueが配列だった場合
				var valueArray = $(this).val();
				for (i=0; i<valueArray.length; i++){
					if(valueStr){
						valueStr =  valueStr + separator + valueArray[i];
					} else {
						valueStr = valueArray[i];
					}
					//alert(valueStr);
				}
			} else {
				//それ以外
				valueStr = $(this).val();
			}

			//フォームのタイプによる処理分岐
			//フォームの要素を隠してvalueをp要素として配置
			if($(this).attr("type") == "radio") {
				//ラジオボタンの場合
				var thisID = $(this).attr("id");
				$("label[for=" + thisID + "]", $(formObject)).addClass("normal");
				if($(this).prop("checked")) {
					$(this).after('<p class="confirm">'+ valueStr +'</p>');
				}
			} else if($(this).attr("type") == "checkbox") {
				//チェックボックスの場合
				var thisID = $(this).attr("id");
				$("label[for=" + thisID + "]", $(formObject)).addClass("normal");
				if($(this).prop("checked")) {
					$(this).after('<p class="confirm">'+ valueStr +'</p>');
				}
			} else if(this.tagName == "SELECT") {
				$(this).after('<p class="confirm">'+ valueStr +'</p>');
			} else if(this.tagName == "TEXTAREA") {
				valueStr = valueStr.replace(/\r\n/g, "<br />");
				valueStr = valueStr.replace(/(\n|\r)/g, "<br />");
				$(this).after('<p class="confirm">'+ valueStr +'</p>');
			} else if($(this).attr("type") != "hidden") {
				$(this).after('<p class="confirm">'+ valueStr +'</p>');
			}

		});

		//「nomal」クラスのオブジェクトをすべて隠す
		$(".normal", $(this)).hide();
		//「confirm」クラスのオブジェクトをすべて表示
		$(".confirm", $(this)).show();

		//値を格納した段落のCSSを設定
		$("p.confirm", $(this))
			.css("line-height","1.6")
			.css("display","inline");

		//値が複数ある場合の処理（区切り文字の追加）
		$(".field").each(function(i){
			$("p.confirm:not(:last)" ,$(this)).each(function(j){
				$(this).append(separator);
			});
		});

		//確認画面をフェードイン
		$(this).css(centerposition(this)).css("margin-left","100px").animate({opacity:"1", marginLeft: "0"},400,"easeOutExpo");
	});
	
}

/*======================================================
確認画面から入力フォーム画面へ戻る
======================================================*/
function returnField(){

	//確認画面をいったんフェードアウトして隠し、内容を更新
	$("#formcontents").css(centerposition($("#formcontents"))).animate({opacity:"0", marginLeft: "100px"},400,"easeOutExpo",function(){

		//「nomal」クラスのオブジェクトをすべて表示
		$(".normal", $(this)).show();
		//「confirm」クラスのオブジェクトをすべて削除
		$(".confirm", $(this)).remove();

		//入力フォーム画面をフェードイン
		$(this).css(centerposition(this)).css("margin-left","-100px").animate({opacity:"1", marginLeft: "0"},400,"easeOutExpo");
	});
}

/*======================================================
データのチェック用（エラーがあればfalseを返す）
======================================================*/
function validate(form){

	//警告表示があれば消す
	if($("p.att", $(form)).length){
		$("p.att", $(form)).remove();
	}

	//エラー表示の要素を削除
	$(".required", $(".errorField")).each(function(i){
		if(this.tagName == "INPUT" || this.tagName == "TEXTAREA" || this.tagName == "SELECT"){
			$(this).unwrap();
		}
	});

	//エラーのクラスをすべて削除
	$(".errorField").each(function(i){
		$(this).removeClass("errorField");
	});

	//エラーチェック
	$(".required").each(function(i){
		if(this.tagName == "INPUT" || this.tagName == "TEXTAREA" || this.tagName == "SELECT") {
			if($(this).attr("type") == "text" || $(this).attr("type") == "password" || this.tagName == "TEXTAREA"){
				//text、password、textareaの場合
				if($(this).val() == ""){
					$(this).wrap('<div class="errorField"></div>');
				}
			} else if(this.tagName == "SELECT"){
				//selectの場合
				if(!$(this).val()){
					$(this).wrap('<div class="errorField"></div>');
				}
			}
		} else {
			//チェックボックスの場合
			var checked = 0;
			$("input", $(this)).each(function(j) {
				if($(this).prop("checked")){
					++checked;
				}
			});
			if(checked == 0){
				$(this).addClass('errorField');
			}
		}
	});

	//E-mailの評価
	if($("input[name=email]", $(form)).val() != "" && !$("input[name=email]", $(form)).val().match(/^([a-zA-Z0-9])+([a-zA-Z0-9¥._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9¥._-]+)+$/)){
			$("input[name=email]", $(form)).wrap('<div class="errorField"></div>');
	}

	//エラーの項目に警告を追加する
	$(".errorField").each(function(i){
		$(this).css("position","relative").css("overflow","visible");
		if($("input" ,$(this)).attr("name") == "email" && $("input" ,$(this)).val() != "") {
			$(this).append('<p class="att">E-mailが正しくありません</p>');
		} else {
			$(this).append('<p class="att">必須項目です</p>');
		}
		$(this).css("display","inline-block");
		var attWidth = $(this).width();
		$(this).css("display","block");
		$("p.att", $(this))
			.css("position","absolute")
			.css("left", attWidth + 5 + "px")
			.css("top","0")
			.css("display","none")
			.css("white-space","nowrap");
	});
	
	//警告のCSSを設定
	$("p.att", $(form))
		.css("font-size","93%")
		.css("background","#000")
		.css("color","#fff")
		.css("marginTop","-1px")
		.css("border-radius","5px")
		.css("-webkit-border-radius","5px")
		.css("-moz-border-radius","5px")
		.css("padding","2px 5px")
		.fadeIn(200);

	//エラーがあればfalse、なければtrueを返す
	if($(".errorField").length){
		return false;
	}else{
		return true;
	}
}
