/* =====================================================================
*
*   GENKI_GOLF | COMMON.js
*
* =================================================================== */

/*----------------------------------------------------------------------
	GLOBAL OBJECT
----------------------------------------------------------------------*/
if ( typeof GGOLF == "undefined" ) GGOLF = {};
if( typeof( console ) == "undefined" ) {
	console = {
		log : function( i_arg ){}
	}
}

GGOLF.isIE = !!( jQuery.browser.msie );
GGOLF.isIE6 = !!( jQuery.browser.msie && parseInt( jQuery.browser.version ) == 6 );
GGOLF.isIE7 = !!( jQuery.browser.msie && parseInt( jQuery.browser.version ) == 7 );

/*----------------------------------------------------------------------
	UTILS
----------------------------------------------------------------------*/

//簡易画像プリローダー
//string時の拡張子チェックをつける
GGOLF.ImagePreload = (function(){
	
	//プリロード本体
	function preLoad(i_imgString) {
		$("<img />").attr("src", i_imgString);
	}
	
	//Objectを再帰的に走査してプリロード
	function recursiveLoad(i_obj) {
		for(var key in i_obj) {
			if(typeof i_obj[key] == "object" && !(i_obj[key] instanceof Array)) {
				recursiveLoad(i_obj[key]);
			} else {
				preLoad(i_obj[key]);
			}
		}
	}
	
	//関数本体
	return function(i_loadTarget){
		if( typeof i_loadTarget == "string" ) {
			preLoad(i_loadTarget);
		} else if ( typeof i_loadTarget == "object" ) {
			if(i_loadTarget instanceof Array) {
				for(var i = 0; i < i_loadTarget.length; i++) {
					preLoad(i_loadTarget[i]);
				}
			} else {
				recursiveLoad(i_loadTarget);
			}
		}
	}
	
})();

/*----------------------------------------------------------------------
	jQuery PLUGINS
----------------------------------------------------------------------*/

//エリアセレクト
(function(){
	
	$.fn.GGAreaSelect = function() {
	
		console.log("エリア選択");
		
		return this.each(function(){
		
			var $hiddenArea = $(this).find("input.jSelectedArea");
			var $hiddenPref = $(this).find("input.jSelectedPref");
			
			var $handles = $(this).find(".jAreaSelectNav a");
			var $slaves = $(this).find(".prefSelectNav");
			
			
			//初期
			var initialAreaVal = $hiddenArea.val();
			var initialPrefVal = $hiddenPref.val();
			
			
			//Area
			$handles.bind("click", function(){
				var targetID = $(this).attr("href");
				var $target = $(targetID)
				
				var areaValue = $(this).attr("rel");
				
				$hiddenArea.val(areaValue);
				$hiddenPref.val("");
				
				$handles.each(function(){
					$(this).removeClass("selected");
				});	
				
				$slaves.hide();
				
				if($target.length) {
					$target.show();
				}
				
				$(this).addClass("selected");
				
				return false;
			});
			
			//Pref
			$(".prefSelectNav a").bind("click", function(){
			
				var prefValue = $(this).attr("rel");
				$hiddenPref.val(prefValue);
				
				var $siblings = $(this).parent().siblings();
				$siblings.each(function(){
					$("#jAreaDisplay").find("a").removeClass("selected");
				});
				
				$(this).addClass("selected");
				return false;
			});
			
			$slaves.hide();
			
			
			if(initialAreaVal) {
				$handles.filter("a[rel='" + initialAreaVal + "']").click();
                $slaves.find("a[rel='" + initialPrefVal + "']").click();
			}
			
		});
		
	}
	
})();

//チェックボックスの見た目入れ替え
//TODO : inputの渡し方を確認
(function(){
	
	var preLoadFlag = false;
	var checkboxImages = {
		on : "/content/images/common/parts/icon/checkbox-on.png",
		off : "/content/images/common/parts/icon/checkbox-off.png"
	}
	
	jQuery.fn.GGCustomCheckBox = function(i_options) {
		
		//プリロード
		if(typeof GGOLF.ImagePreload == "function" && !preLoadFlag) {
			GGOLF.ImagePreload(checkboxImages);
			preLoadFlag = true;
		}
		
		return this.each(function(){
			
			/*----------------------------------------------------------------------
				INIT
			----------------------------------------------------------------------*/
			var $this = $(this);
			
			//input:checkboxでなければ処理を中断
			if( $this.get(0).tagName != "INPUT" ) return;
			if( !$this.is(":checkbox") ) return;
			
			var name = $this.attr("name");
			var value = $this.attr("value");
			var cbxString;
			var hdnString;
			
			//既に選択状態で遷移してきた場合に対応
			
			if($(this).attr("checked")) {
				cbxString = '<a href="#" rel="' + value + '" class="jImageCheckbox selected"><img src="/content/images/common/parts/icon/checkbox-on.png" /></a>';
				hdnString = '<input type="hidden" value="' + value + '" name="' + name + '" />';
			} else {
				cbxString = '<a href="#" rel="' + value + '" class="jImageCheckbox"><img src="/content/images/common/parts/icon/checkbox-off.png" /></a>';
				hdnString = '<input type="hidden" value="0" name="' + name + '" />';
			}
			
			//代替要素を作成
			var $holder = $('<span class="jImageCheckboxSet"></span>');
			var $hidden = $(hdnString);
			var $imgCheckbox = $(cbxString);
			
			
			//要素を入れ替え : display:noneのままJSから操作できるなら、元々あるcheckboxを活かした方が良い
			$this.after($holder);
			$this.remove();
			$holder
				.append($imgCheckbox)
				.append($hidden);
			
			
			/*----------------------------------------------------------------------
				Activation
			----------------------------------------------------------------------*/
			$imgCheckbox.bind("click", function(){
				
				var $img = $(this).find("img");

                // チェックボックスが無効の場合は何もしない
                // 個別のページでimg srcをこの値に置き換えていた場合はチェックボックス無効状態とみなす
                if ($img.attr("src") === "/content/images/common/parts/icon/checkbox-none.png") {
                    return false;
                }
				
				if($(this).hasClass("selected")) {
					// ■チェックボックスの同期
					if ($(this).parents('table').hasClass('staticEachHoleTable')) {
					
						
						var holeNum = ~~($('#HolenumSelected>thead>tr>th.holenum.selected>span.holeNo').html());
						var scoreRecordId = ~~($('#HolenumSelected>thead>tr>th.holenum.selected>input[name=scoreRecordID]').val());
						var index;
						$('#HolenumSelected tr:nth-child(2)>th:not(:first)').each(function(n) {
							if (~~($(this).find('span.holeNo').html()) == holeNum &&
								~~($(this).find('input[name=scoreRecordID]').val()) == scoreRecordId) {
								index = n;
							}
						});
						$('#RoundScoreSection table.jsScoreUpdateTable>tbody>tr:nth-child(8) td').eq(index).find('a').click();
						
						/*
						//エラー回避のため要素の存在をチェック : SW
						if($(this).parents('table').find('thead>tr>th>.holeName>span>a').length) {
							var targ = $(this).parents('table').find('thead>tr>th>.holeName>span>a').html();
							if (targ) {
								var hole_num = ~~(targ.match(/[0-9]{1,2}$/)) + 1;
								$('#RoundScoreSection table.jsScoreUpdateTable>tbody>tr:nth-child(8) td:nth-child('+hole_num+') a').eq(0).click();
							}
						}
						*/
					
					
						
					} else {
					
					
						//エラー回避のため要素の存在をチェック : SW
						if($('#ShotTrackSection table.staticEachHoleTable>thead>tr>th>.holeName>span>a').length) {
							var targ = $('#ShotTrackSection table.staticEachHoleTable>thead>tr>th>.holeName>span>a').html();
							if (targ) {
								var hole_num = $(this).parents('td').index();
								if (targ.match(/[0-9]{1,2}$/) == hole_num) {
									$('#ShotTrackSection table.staticEachHoleTable>tbody>tr:first>td:last img').eq(0).attr('src', checkboxImages.off).parents('a.selected').removeClass('selected');
								}
							}
						}
						
						
						
					}
					
					$(this).removeClass("selected");
					$hidden.attr("value", "0");
					$img.attr("src", checkboxImages.off);
					
					
					
				} else {
					// ■チェックボックスの同期
					if ($(this).parents('table').hasClass('staticEachHoleTable')) {
					
						var holeNum = ~~($('#HolenumSelected>thead>tr>th.holenum.selected>span.holeNo').html());
						var scoreRecordId = ~~($('#HolenumSelected>thead>tr>th.holenum.selected>input[name=scoreRecordID]').val());
						var index;
						$('#HolenumSelected tr:nth-child(2)>th:not(:first)').each(function(n) {
							if (~~($(this).find('span.holeNo').html()) == holeNum &&
								~~($(this).find('input[name=scoreRecordID]').val()) == scoreRecordId) {
								index = n;
							}
						});
						$('#RoundScoreSection table.jsScoreUpdateTable>tbody>tr:nth-child(8) td').eq(index).find('a').click();
						
						/*
						//エラー回避のため要素の存在をチェック : SW
						if($(this).parents('table').find('thead>tr>th>.holeName>span>a').length) {
							
							var targ = $(this).parents('table').find('thead>tr>th>.holeName>span>a').html();
							if (targ) {
								var hole_num = ~~(targ.match(/[0-9]{1,2}$/)) + 1;
								$('#RoundScoreSection table.jsScoreUpdateTable>tbody>tr:nth-child(8) td:nth-child('+hole_num+') a').eq(0).click();
							}
							
						}
						*/
					
						
						
					} else {
					
						
						//エラー回避のため要素の存在をチェック : SW
						if($('#ShotTrackSection table.staticEachHoleTable>thead>tr>th>.holeName>span>a').length) {
							
							var hole_num = $(this).parents('td').index();
							var targ = $('#ShotTrackSection table.staticEachHoleTable>thead>tr>th>.holeName>span>a').html();
							if (targ) {
								if (targ.match(/[0-9]{1,2}$/) == hole_num) {
									$('#ShotTrackSection table.staticEachHoleTable>tbody>tr:first>td:last img').eq(0).attr('src', checkboxImages.on).parents('a').addClass('selected');
								}
							}
							
						}
						
					}
					
					$(this).addClass("selected");
					$hidden.val($(this).attr("rel"));
					$img.attr("src", checkboxImages.on);
					
				}
				
				return false;
				
			});
			
		});
		
	}
	
})();


/*----------------------------------------------------------------------
	TOOLTIP MANAGED
----------------------------------------------------------------------*/

(function(){

	var tooltipIconTypes = {
	
		"age" : "年代",
		"golftype" : "ゴルファータイプ",
		"score" : "スコア",
		"score-avg" : "スコア平均",
		"pat" : "スコアパット",
		"targetscore" : "目標スコア",
		"bestscore" : "ベストスコア",
		"club-driver" : "ドライブ",
		"driver-best" : "ベストドライブ",
		"club-ball" : "持ち球",
		"club-trajectory" : "弾道",
		"pref" : "都道府県",
		"comment" : "コメント",
		"medal-doracon-private" : "当日ベストドライブ",
		"medal-doracon-golfcourse" : "ゴルフ場ベストドライブ",
		"medal-doracon-private-total" : "個人通算ベストドライブ",
		"medal-score-golfcourse" : "ゴルフ場ベストスコア",
		"medal-score-private-total" : "個人通算ベストスコア",
		"driver-yd" : "ベストドライブを出した時の 飛距離",
		"driver" : "ベストドライブを出した時の クラブ"
		
	}
	
	$.fn.GGIconToolTip = function(){
		
		this.each(function(){
			
			var typeKey = String($(this).attr("src")).replace(/.*\/(.+)\..*/, "$1");
			$(this).attr("title", tooltipIconTypes[typeKey]);
			$(this).css("cursor", "pointer");
			$(this).easyTooltip();
			
		});
		
	};
	
})();

/*----------------------------------------------------------------------
	LOADING VIEW
----------------------------------------------------------------------*/
GGOLF.fullCoverLoadView = (function(){

	var ctr;
	var $cover = $([
		'<div id="Loading">',
			'<div class="img"><img width="32" height="32" alt="loading" src="/content/images/common/parts/loading/loader-black-tr.gif"></div>',
		'</div>'
	].join(""))
	
	return {
		
		setup : function() {
			ctr = GGOLF.fullCoverLoadView;
			$("body").append($cover);
			$cover.hide();
		},
		
		show : function() {
			$cover.fadeIn("fast");
		},
		
		hide : function() {
			$cover.fadeOut("fast");
		}
		
	}
	
})();

GGOLF.mapCoverLoadView = (function(){
	
	var ctr;
	var $coveredTarget;
	var $cover = $([
		'<div id="MapLoading">',
			'<div class="icon"><img width="32" height="32" src="/content/images/common/parts/loading/loader-black-tr.gif"></div>',
			'<div class="text"><img width="74" height="20" alt="通信中です" src="/content/images/common/parts/loading/text.png"></div>',
		'</div>'
	].join(""));
	
	return {
		
		setup : function(i_mapId) {
			ctr = GGOLF.mapCoverLoadView;
			$coveredTarget = $(i_mapId);
			$coveredTarget.prepend($cover);
			
			//ローダー本体の縦サイズ : 62px
			var mapHeight = $coveredTarget.find(".boxInner").height() + 20;
			var iconMarginTop = (mapHeight - 62) / 2;
			
			$cover.css("height", mapHeight);
			$cover.find(".icon").css("margin-top", iconMarginTop + "px");
			$cover.hide();
		},
		
		show : function() {
			$cover.fadeIn("fast");
		},
		
		hide : function() {
			$cover.fadeOut("fast");
		}
		
	}
	
})();

// チェックボックスの状態を操作します
// 通常のinputのチェックボックスではなく
// jImageCheckboxSet > jImageCheckbox となっているチェックボックスを対象とします
GGOLF.checkBoxController = (function(){

	return {
		isChecked : function($checkBox) {
			var isChecked = false;
			
			if ($checkBox.find('input[type=hidden]').eq(0).val() == "1") {
				isChecked = true;
			}
			
			return isChecked;
		},
		
		checke : function($checkBox) {
			$checkBox.find('img').eq(0).attr('src', "/content/images/common/parts/icon/checkbox-on.png");
			$checkBox.find('input[type=hidden]').eq(0).val(1);
			$checkBox.find('a.jImageCheckbox').addClass('selected');
		},

		unchecke : function($checkBox) {
			$checkBox.find('img').eq(0).attr('src', "/content/images/common/parts/icon/checkbox-off.png");
			$checkBox.find('input[type=hidden]').eq(0).val(0);
			$checkBox.find('a.jImageCheckbox').removeClass('selected');
		},
		
		disable : function($checkBox) {
			$checkBox.find('img').eq(0).attr('src', "/content/images/common/parts/icon/checkbox-none.png");
			$checkBox.find('input[type=hidden]').eq(0).val(0);
			$checkBox.find('a.jImageCheckbox').removeClass('selected');
		}
	};
	
})();


// ソーシャル連携接続
// 日記編集画面、ラウンド履歴編集画面から呼び出されることを想定しています
GGOLF.socialConnectPopup = (function(){

	return {
		
		open : function(url) {
			var settings = "menubar=no, status=yes, scrollbars=yes, resizable=yes, toolbar=no";
			var w = 800;
			var h = 450;
			if (window.screen.width > w) {
				settings += ", left=" + (window.screen.width - w) * 0.5;
			} else {
				w = window.screen.width;
			}
			settings += ", width=" + w;
			
			if (window.screen.height > h) {
				settings +=", top=" + (window.screen.height - h) * 0.5;
			} else {
				h = window.screen.height;
			}
			settings += ", height=" + h;
			
			return window.open(url, "AuthWin", settings );
		},
		
		// 接続が完了した際に画面を更新して接続完了状態の表示を行います
		complete : function(socialConnectType) {
			var $checkBox;
			
			// publishSetting 3: 公開, 2 : フレンドまで公開, 1: 非公開
			var publishSetting = $('input.jPublishSettingRadioButton:radio:checked').val();
			
			// 表示を更新します
			if (socialConnectType == "twitter") {
				// twitter接続が完了した場合
				$(".jSocialConnectTwitter").hide();
				
				$checkBox = $(".jPostTwitterCheckbox");
				
				if (publishSetting === "3") {
					// 連携完了した直後に投稿するチェックがONの状態にします
					GGOLF.checkBoxController.checke($checkBox);
				} else {
					// 公開設定が「公開」でない場合、チェックできない状態にします
					GGOLF.checkBoxController.disable($checkBox);
				}
				
				$checkBox.show();
			} else if (socialConnectType == "facebook") {
				// facebook接続が完了した場合
				$(".jSocialConnectFacebook").hide();
				
				$checkBox = $(".jPostFacebookCheckbox");
				
				if (publishSetting === "3") {
					// 連携完了した直後に投稿するチェックがONの状態にします
					GGOLF.checkBoxController.checke($checkBox);
				} else {
					// 公開設定が「公開」でない場合、チェックできない状態にします
					GGOLF.checkBoxController.disable($checkBox);
				}
				
				$checkBox.show();
			}
		}
	};
	
})();


/*----------------------------------------------------------------------
	IE6 ATTENTION
----------------------------------------------------------------------*/

GGOLF.attentionIE6 = function() {
	
	var tplStr = [
		'<div class="attentionIE">',
			'<span class="ft12">お客様のブラウザはInternet Explorer6です。</span><br />',
			'<strong>最新のブラウザのダウンロードをおすすめします</strong>',
			'<div class="spec">',
				'<img src="/content/images/index/ie8.gif" class="flR" alt="Windows Internet Explorer 8" />',
				'<p>お使いのブラウザでは『元気！ゴルフ』が正しく動作しない場合がございますので、<br />',
				'最新のブラウザのダウンロードをおすすめします。<br /><br />',
				'<img src="/content/images/common/parts/icon/triangle-green.gif" width="5" height="7" alt="" /> <a href="http://www.microsoft.com/ja-jp/windows/products/winfamily/ie/function/default.aspx">最新のブラウザをダウンロードする</a></p>',
			'</div>',
		'</div>'
	].join("");
	
	var $target = $("#Main");
	$target.prepend($(tplStr));
	
}

/*----------------------------------------------------------------------
	DOMREADY
----------------------------------------------------------------------*/

$(function(){

	$(".jTooltipIcon").GGIconToolTip();
	
	//チェックボックスのデフォルトを保ちたいところは.staticを付与しておく
	$("input:checkbox").not(".static").GGCustomCheckBox();
	$("#jAreaNavSet").GGAreaSelect();
	

	
	$(".jSubmitConfirm").bind("click", function(){
		var confirmation = confirm("保存してよろしいですか？");
		if(!confirmation) return false;
	});
	
	GGOLF.fullCoverLoadView.setup();
	GGOLF.mapCoverLoadView.setup("#MapWrapp");
	
	if(GGOLF.isIE6) GGOLF.attentionIE6();
});

