/**
 * SOYOU
 * 
 * @copyright	2010 RaNa design associates, inc.
 * @link		http://kaelab.ranadesign.com/
 * @version 	1.0
 * @date		2011-06-22
 */
(function($) {

	$(function() {

		// ローカルナビのうち他のカテゴリのものを非表示にする。
		// → slideUp/Downに変更。
		// → [module] 開閉式ダイアログ へ統合
		$("#nav-local .arrow").toggleDialog({
			trigger: "> a",
			target: ".sub"
		}).find(".noArrow").find(".sub").show();

		// 初期オープン
		var category = $("body")[0].className;
		var localNav = $("#nav-local").find("." + category);
		localNav.find(".sub").slideToggle(0, function() {
			localNav.toggleClass("opened");
		});

		// IE6でのポール見切れ対策。
		if ($.browser.msie && $.browser.version < 7) {
			$("#area-pole").height($("#wrapper").height());
		} else {
			// [module] 開閉式ダイアログ
			// IE6ではポール高さ、フッター位置がずれるため、非対応。
			$(".mod-dialog").toggleDialog({
				trigger: ".q, .toggle",
				target: ".a"
			}).find(".toggle").show().end()
			.find(".q").css("cursor", "pointer");
		}
		
		// ページトップヘ
		var pagetop = $("#gif-pagetop");
		pagetop.floater({
			marginTop: 300,
			marginBottom: 75,
			down: function() {
				pagetop.css("backgroundImage", "url(/img/anime/b_img06.gif)");
			},
			up: function() {
				pagetop.css("backgroundImage", "url(/img/anime/b_img05.gif)");
			},
			suspended: function() {
				pagetop.css("backgroundImage", "url(/img/anime/b_img06.gif)");
			}
		}).transfer()

		// 生活情報トップ(マップ)
		var mapNav = $(".nav-map");
		mapNav.children("li").click(function(event) {
			mapNav.stop(true).fadeOut(200);
			$(".region").stop(true).fadeIn().find(".nav-region").eq($(this).index()).stop(true).fadeIn();
			event.preventDefault();
		});
		$(".mod-map").click(function(event) {
			if ($(event.target).hasClass("mod-map") || $(event.target).hasClass("region")) {
				$(".region", this).add(".nav-region").stop(true).fadeOut(200);
				mapNav.stop(true).fadeIn();
				event.preventDefault();
			}
		});

		// Googleマップ用リンク対応
//		$("a[href$=曹友会]").each(function() {
//			this.href = decodeURI(this.href).replace(" 曹友会", "");
//		});

		// 改行コード変換
		var plain = $(".plain");
		plain.html(plain.text().replace(/\n/g, "<br>"));


		// ランダムアニメGIF
		$(".mod-gifNav").setAnime();
		
		// newアイコンの表示切替
		$(".new").toggleNew();
	});
	
	
	/**
	 * プラグイン（専用）
	 */
	$.fn.setAnime = function() {
		this.each(function() {
			var img = new Image();
			img.src = "/img/anime/a_img0" + (Math.floor(Math.random() * 5) + 1) + ".gif";
			$(this).append(img);
		});
		return this;
	};

	// [module] 開閉式ダイアログ
	$.fn.toggleDialog = function(options) {
		var config = {
				speed: 500,
				trigger: ".trigger",
				target: ".target",
				state: "opened"
			};

		$.extend(config, options);
		this.each(function() {
			var self = $(this);
			// reset
			self.find(config.target).slideUp(0);
			
			// click
			self.find(config.trigger).click(function(event) {
				$(this).siblings(config.target).slideToggle(config.speed, function() {
					self.toggleClass(config.state);
				});
				event.preventDefault();
			});
		});
		return this;
	};

	// newアイコンの表示切替
	// 投稿日より30日を越えるとアイコンを非表示に。
	$.fn.toggleNew = function(options) {
		this.each(function() {
			var entryDate = new Date($(this).data("entrydate")),
				now = new Date();

			if (Math.floor((now - entryDate) / 1000 / 60 / 60 / 24) > 30) {
				$(this).hide();
			}

		});
		return this;
	};

})(jQuery);

/**
 * アニメ用
 */
(function($) {

	$(function() {
		// ヘッダーアニメ
		startHeader();
		// フッターアニメ
		startFooter();
		// マガジンスクワット
		startSquat();
	});
	
	// ヘッダーアニメ
	function startHeader() {
			// ヘリコプター
		var onHelicopter = function() {
				var dis = Math.floor(Math.random() * ($(document).width() - $("#gif-helicopter").width()));
				$("#gif-helicopter").animate({
					left: dis
				}, {
					duration: dis * 15,
					easing: "easeOutCubic",
					complete: function() {
						dropParachute();
						setTimeout(outHelicopter, Math.floor((Math.random() * 2 + 1) * 1000));
					}
				});
			},
			outHelicopter = function() {
				$("#gif-helicopter").animate({
					left: $(window).width()
				}, {
					duration: $(window).width() * 10,
					easing: "easeInCubic",
					complete: function() {
						$(this).css("left", $(this).width() * -1);
						setTimeout(onHelicopter, Math.floor((Math.random() * 4 + 1) * 2000));
					}
				});
			},
			dropParachute = function() {
				var gif = $("<div>", { "class": "gif-parachute" }),
					img = $("<img>", { src: "/img/anime/b_img04.gif" });
				gif.css({
						left: $("#gif-helicopter").offset().left + 50,
						top: 30
					}).append(img).appendTo("body").drop();
			};
		$.fn.drop = function() {
			var self = this;
			$("img", this).animate({
				top: $(document).height()
			}, {
				duration: $(document).height() * 10,
				easing: "easeInCubic",
				complete: function() {
					$(this).remove();
				}
			});
		};
		// 初期化
		$(window).resize(function() {
			$(".mod-gifHeader").width($(this).width());
		}).resize();
		// 始動
		$("#gif-helicopter").find("img").wiggle();
		setTimeout(onHelicopter, 1500);
	}
	
	// フッターアニメ
	function startFooter() {
		var contentsWidth = 0;
		// 初期化
		$(window).resize(function() {
			$(".mod-gifFooter").width($(this).width());
			// アニメを止める位置とかける時間の基準値として使う
			contentsWidth = ($(document).width() - $("#area-pole").width() - $("#area-container").width());
		}).resize();
		// 音楽隊
		$("#gif-brassband").animate({
			right: contentsWidth / 2
		}, {
			duration: contentsWidth * 50,
			easing: "linear",
			complete: function() {
				$("img", this).data("stop", true);
			}
		}).find("img").wiggle({ volume: 1, speed: 200 });
		// 戦車
		$("#gif-tank").animate({
			left: contentsWidth / 2
		}, {
			duration: contentsWidth * 75,
			easing: "easeOutCirc",
			complete: function() {
//				$("img", this).data("stop", true);
			}
		}).find("img").wiggle({ volume: 1, speed: 100 });
	}
	
	// マガジンスクワット
	function startSquat() {
		var imgpath = "/img/anime/a_img06_",
			imgext = ".gif",
			i = 0,
			speed = 800;
		setTimeout(function() {
			$("#gif-squat").find("img").attr("src", imgpath + (i ^= 1) + imgext);
			$("#area-topMagazine").css("marginTop", i * 7);
			setTimeout(arguments.callee, speed);
		}, 200);
	}
	
})(jQuery);


/**
 * プラグイン（汎用）
 */
(function($) {

	$.fn.extend({
		
		// [gif] ふわふわ
		wiggle: function(options) {
			var config = $.extend({
					speed: 500,
					top: 0,
					volume: 4
				}, options),
				self = this,
				t = 0;

			// 停止スイッチ
			self.data("stop", false);

			(function() {
				if (self.data("stop")) {
					return false;
				}
				self.animate({
					top: (t ^= 1) * config.volume + config.top
				}, {
					duration: config.speed,
					complete: arguments.callee
				});
			})();
			return this;
		},
		
		// ページ内遷移
		transfer: function(options) {
			var config = {
					speed: 1000,
					easing: "swing"
				},
				self = this;
			
			$.extend(config, options);
			this.click(function(event) {
				$("html, body").stop(true).animate({
					scrollTop: 0
				}, {
					duration: config.speed,
					easing: config.easing
				});
				event.preventDefault();
			});
			return this;
		}
		
	});

})(jQuery);

/**
 * floater
 * 
 * @category	jQuery plugin
 * @license 	http://www.opensource.org/licenses/mit-license.html  MIT License
 * @copyright	2010 RaNa design associates, inc.
 * @author		keisuke YAMAMOTO <keisukey@ranadesign.com>
 * @link		http://kaelab.ranadesign.com/
 * @version 	1.1.2
 * @date		Jun 10, 2011
 *
 * コンテンツをスクロールに追従させ、ドキュメントの上下に接着させるプラグイン。
 *
 * [オプション]
 * marginTop:	  上の余白
 * marginBottom:  下の余白
 * wait:		  0～1(初期値 0.5)。0はナビが通り過ぎるまで待つ。1はナビの末端が出るとすぐ動きだす。
 * speed:		  アニメーションにかける時間。
 * easing:		  イージング
 * fixed:		  trueでposition: fixedに切り替え。初期値はfalse。
 *
 */

(function($) {

	$.fn.extend({

		floater: function(options) {
			var config = {
				marginTop: 0,
				marginBottom: 0,
				wait: 0.5,	// 0-1
				speed: 3000,
				speedAccel: 1000,	// 傾き。
				speedBase: 4000,	// 切片。
				velocity: "variable",  // or fixed
				easing: "swing",
				fixed: false,
				down: function() {},
				up: function() {},
				suspended: function() {}
			};
			$.extend(config, options);
			config.wait = $(this).outerHeight() - $(window).height() * config.wait;
			config.marginTop = parseInt(config.marginTop, 10) || 0;
			config.marginBottom = parseInt(config.marginBottom, 10) || 0;

			$(this).each(function() {
				var self = $(this),
					y0 = $(window).scrollTop();	// 初期位置を基準座標として設定

				if (config.fixed === true) {
					self._fixed(config);
					return true;
				}

				self.css("position", "absolute");

				$(window).scroll(function() {
					var y = $(window).scrollTop(),	// 移動後の座標取得
						w = $(window).height(),
						d = $(document).height(),
						h = self.outerHeight() + config.marginTop + config.marginBottom;

					// 状態判定
					y < y0 ? config.up() : config.down();

					if (Math.abs(y - self.offset().top) < config.wait) {
						return;
					}

					self.stop(true).animate({
						top: (d - h) * y / (d - w) + config.marginTop
					}, {
						duration: config.speed,
						easing: config.easing,
						complete: config.suspended
					});

					// 基準座標を変更
					y0 = y;

				}).scroll();
			});

			return this;
		},
		
		_fixed: function(config) {
			if ($.browser.msie && $.browser.version < 7) {
				$(this).css("position", "absolute");
				this[0].style.cssText = "top: expression(documentElement.scrollTop + " + config.marginTop + " + 'px')";
				document.body.style.background = "url(null) fixed";
			} else {
				$(this).css("position", "fixed").css("top", config.marginTop);
			}
		}
		
	});

})(jQuery);

