/* 
 * Copyright (c) MindFree co., ltd.
 * Licensed under the MIT
 * Author: Kazunori Tokuda
 */
 
(function($) {
	if ( location.href != domain ) {
		var goHash = location.href.replace(domain, '');
		if ( !/^\#/.test(goHash) ) {
			location.href = domain + '#/' + goHash;
			return false;
		}
	}
	
	var b = $('body'),
		cvsReplaceImg = $('<img src="/common/images/topicpath.png" id="topicpath" />'),
		cvsHolder = $('<div id="cvsHolder"/>'),
		cvs = document.createElement('canvas'),
		loading = $('<div class="ajaxLoading"/>'),
		grayLayer = $('<div class="grayout"/>'),
		newsPrevBox, newsPrevBoxContents, newsPrevBoxClose;
	cvs.id = 'topicpathColorPickrCanvas';
	b.append(
		loading.hide(),
		grayLayer.hide()
	);
	
	// globalNav
	$('#global ul').each(function() {
		var $this = $(this);
		$this
			.hide().width(0)
				.parent()
				.hover(function() {
					$this
						.show()
						.css('zIndex', 105)
						.animate({
							width: 600
						}, {
							duration: 500,
							easing: 'easeOutBounce',
							queue: false
						});
				}, function() {
					$this
						.css('zIndex', 100)
						.animate({
							width: 0
						}, {
							duration: 500,
							easing: 'easeInOutCirc',
							queue: false,
							complete: function() {
								$this.hide();
							}
						});
				});
	});
	
	// スロット
	// 背景ずらすやつ
	$.fn.bgAnim = function(options) {
		var $this = this,
			bgPosX = bgPosY = 0,
			getBgPos = function() {
				var bgPosDef = $this.css('backgroundPosition');
				if ( bgPosDef ) {
					var bgPos = bgPosDef.split(' '); // bgPos[0] = X, bgPos[1] = Y
					bgPosX = bgPos[0].replace('px', '');
					bgPosY = bgPos[1].replace('px', '');
				} else { // for IE
					bgPosX = $this.css('backgroundPositionX').replace('px', '');
					bgPosY = $this.css('backgroundPositionY').replace('px', '');
				}
			},
			endFlg = false,
			rateX = rateY = 0,
			conf = $.extend({
				top: null,
				left: null,
				rateX: 0,
				rateY: 10,
				speed: 30,
				callback: null
			}, options);
			
			rateX = conf.rateX;
			rateY = conf.rateY;
			
			(function() {
				getBgPos();
				if ( bgPosY == conf.top || bgPosX == conf.left ) {
					endFlg = true;
				}
				if ( !endFlg ) {
					$this.css({
						backgroundPosition: (bgPosX - rateX) + 'px ' + (bgPosY - rateY) + 'px'
					});
					setTimeout(arguments.callee, conf.speed);
				} else {
					if ( conf.callback && typeof conf.callback == 'function' )
						conf.callback.call($this);
				}
			})();
	}
	// ランダムにゴールを決めるやつ
	function slotNumber() {
		return Math.floor(Math.random() * 10) * 30;
	}
	
	var multiEndFlg = 0,
		equalFlg = false,
		nearMissFlg = false,
		ends = [],
		result = $('<div id="result"/>'),
		returnMultiple = function() {
			var randomInt = Math.floor(Math.random(2) * 10),
				multiple;
			if ( randomInt <= 2 ) {
				multiple = 1;
			} else if ( randomInt > 2 && randomInt <= 6 ) {
				multiple = 2;
			} else {
				multiple = 3;
			}
			return multiple;
		}
	b.append(result);
		
	// 全然あたらないよ！
	if ( Math.floor(Math.random() * 100 ) == 80 ) { // 1000 , 50 にもどす
	//if ( 5 == 5 ) {
		var equalNumber = slotNumber();
		for ( var i=0; i<4; i++ ) {
			ends.push( - ( ( 300 * returnMultiple() ) + equalNumber) );
		}
		equalFlg = true;
	} else {
		var sNum = [];
		for ( var i=0; i<4; i++ ) {
			var num = slotNumber();
			ends.push( - ( ( 300 * returnMultiple() ) + num) );
			sNum.push(num);
		}
		if ( sNum[0]==sNum[1] && sNum[0]==sNum[2] && sNum[0]==sNum[3] ) {
			equalFlg = true;
		}
	}
	
	/*if ( existCookie() ) {
		for ( var i = 0; i<4; i++ ) {
			$('#c'+i).addClass('n8');
		}
		HoshizoranoCanvas();
	} else {*/
		for ( var i = 0; i<4; i++ ) {
			$('#c'+i)
				// the number sliding that couter
				.addClass('n' + Math.floor(Math.random() * 10))
				.bgAnim({
					top: ends[i],
					callback: function() {
						// <del>万が一</del>百が一当たった場合は…
						if ( ++multiEndFlg == 4 ) {
							if ( equalFlg ) {
								result
									.css('opacity', 0)
									.delay(500)
									.text('特別な背景でお楽しみください')
									.show()
									.fadeTo('normal', .7)
									.delay(3000)
									.fadeOut();
									
								// 背景を夜空に☆ミ
								HoshizoranoCanvas();
								//setCookie();
							} else {
								result
									.css('opacity', 0)
									.delay(500)
									.text('残念！ハズレだよ')
									.show()
									.fadeTo('normal', .7)
									.delay(3000)
									.fadeOut();
							}
						}
						return this.fadeTo(100, .3).fadeTo(400, 1);
					}
				});
		}
	//}
	
	// トップのニュース表示ボックス
	$.fn.newsArchivePreview = function(condition) {
		if ( condition ) {
			newsPrevBox = $([
				'<div id="newsPrevBox">',
					'<div id="newsPrevBoxClose">×</div>',
					'<div id="newsPrevBoxHead"></div>',
					'<div id="newsPrevBoxContents"></div>',
				'</div>'
			].join('')).hide();
			b.append(newsPrevBox);
			newsPrevBoxClose = $('#newsPrevBoxClose');
			newsPrevBoxContents = $('#newsPrevBoxContents');
			newsPrevBoxClose.click(function() {
				grayLayer.hide();
				newsPrevBox.hide();
			});
		}
		
		var entryListPos = function() {
			var entryListPos = $('div.entrylist').offset();
			newsPrevBox.css({
				top: entryListPos.top,
				left: entryListPos.left,
				zIndex: 5000,
				height: 140
			}).show();
		}
		
		this.each(function() {
			var _href = this.href;
			//entryListPos();
			$(this).click(function() {
				loading.show();
				newsPrevBoxContents.html('');
				$.ajax({
					url: _href,
					type: 'GET',
					dataType: 'html',
					success: function(html) {
						if ( _gaq ) { // for GA
							_gaq.push(['_trackPageview', _href]);
						}
						grayLayer
							.show()
							.one('click', function() {
								grayLayer.hide();
								newsPrevBox.hide();
							});
						entryListPos();
						var insertContents = $('div.single', html).html();
						newsPrevBoxContents
							.html(
								'<div class="newsPrevBoxContentsInner">' +
									insertContents +
								'</div>'
							);
							
						var contentsHeight = $('div.newsPrevBoxContentsInner', newsPrevBoxContents).attr('offsetHeight');
						loading.hide();
						if ( contentsHeight > 140 ) {
							newsPrevBox.animate({
								height: contentsHeight + 40
							}, 600, 'easeInOutCirc');
						}
					},
					error: function(html) {
					
					}
				});
				
				return false;
			});
		});
	}
	if ( b.hasClass('home') ) {
		$('div.news ul a').newsArchivePreview(true);
	}
	
	// 残タスク：history → bbqで実装
	// 戻るも進むも、同じ動作でいいよね
	// URL取得して移動で
	// 要ファンクション
	$.fn.verticalGlide = function(hashChange) {
		var $this = this,
			main = $('body div.main'),
			glideEase = 'easeInOutCirc',
			verticalGliding = false,
			xhr = null;
		
		if ( hashChange ) {
			$(window)
				.bind('hashchange', function(e) {
					newsPrevBox.hide();
					if ( !location.hash ) {
						verticalGlide(domain);
					} else {
						verticalGlide(location.hash.replace('#', ''));
					}
				})
			if ( location.hash && location.hash != '#/' ) $(window).trigger('hashchange');
		}
		
		function verticalGlide(url) {
			if ( verticalGliding ) return false;
			if ( !$.browser.msie ) {
				if ( $('span.pathbg canvas') && $('span.pathbg canvas').length > 0 ) {
					cvsHolder.append(cvs);
					$('span.pathbg').append(cvsReplaceImg);
				}
			}
			grayLayer.hide();
			verticalGliding = true;
			// loading...
			// this is sample...
			main.css({
				height: main.attr('offsetHeight')
			});			
			loading.show();
			$('body div.mainInner').css({
				position: 'absolute',
				top: 0
			});
			var loadingURL = /\/$/.test(url) ? url : url;
			xhr = $.ajax({
				url: loadingURL,
				type: 'GET',
				dataType: 'html',
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert('リクエストされたページは存在しないためトップへ移動します');
					xhr.abort();
					loading.hide();
					verticalGliding = false;
					location.hash = '#/';
					// verticalGlide(domain) && http://mindfree.jp/#/
				},
				success: function(html) {
/*
					if ( _gaq ) { // for GA
						_gaq.push(['_trackPageview', loadingURL]);
					}
*/
					
					loading.hide();
					var div = $('<div>'+html+'</div>');
					var containerContents = $('div.container', div).css({
						position: 'absolute',
						top: 0,
						left: -10000
					});
					var title = html.match(/\<title\>([^\<]+)\<\/title\>/) ? RegExp.$1 : '';
					
					try {
						document.title = title;
					} catch(e) {}
					
					b.append(containerContents);
					var mainContents = $('div.mainInner', containerContents);
					if ( mainContents.hasClass('mindfree') ) {
						b.addClass('mindfree');
					} else {
						b.removeClass('mindfree');
					}
					mainContents.css({
						position: 'absolute',
						top: - mainContents.attr('offsetHeight')
					}).attr('id', 'loading');
					
						// other browsers
					main.append(mainContents);
					containerContents.remove();
					// div.mainの高さを変える
					main.animate({
						height: $('#loading').attr('offsetHeight')
					}, 600, glideEase);
					
					var _loading = $('#loading'),
						_mainInner = $('div.mainInner');
					// 同時に読み込んだコンテンツをメインに移動する
					_loading.animate({
						top: 0
					}, 600, glideEase);
					_loading.prev().animate({
						top: _loading.attr('offsetHeight')
					}, 600, glideEase, function() {
						$(this).removeAttr('class').remove();
						_loading.attr('id', '');
						verticalGliding = false;
						main.height('auto');
						_mainInner.css({
							position: 'static'
						});
						
						if ( _mainInner.hasClass('home') ) {
							$('div.mainInner div a')
								.filter(function() {
									return !/\/log\/\d+/.test(this.href);
								})
								.verticalGlide();
							$('div.news ul a').newsArchivePreview();
						} else {
							if ( !$.browser.msie ) {
								$('span.pathbg img').replaceWith(cvs);
							}
							$('a', _mainInner)
								.filter(function() {
									var _href = this.href;
									if ( /^http/.test(_href) && _href.indexOf(domain) == -1 ) {
										return false;
									} else {
										return true;
									}
								})
								.verticalGlide();
						}
						if ( _mainInner.hasClass('member') ) {
							memberShow();
						}
						if ( $("#amourList").length ) {
							amourList();
						}
						// callback and execute the JS bind
					});
				}/*,
				error: function() {
					return false;
				}*/
			});
		}
			
		$this.each(function() {
			$(this)
				.filter(function() {
					return !/twitter\.com|yahoo|jrc|google|akaihane|facebook\.com|javascript|recruit_entry|mailto/.test(this.href);
				})
				.filter(function() {
					return !$(this).hasClass("noUseAjaxLink");
				})
				.filter(function() {
					return !$(this).parent().parent().hasClass("amourPagenav");
				})
				.attr('href', $(this).attr('href').match(/^\./)
					? $(this).attr('href').replace(/^\./, '#') : '#' + $(this).attr('href'))
				.click(function() {
					var loadingHash = $(this).attr('href').replace('#', '');
					location.hash = this.hash;
					
					if ( grayLayer.is(':visible') ) {
						grayLayer.hide();
					}
					return false;
				});
		});
	}
	$('a')
		.filter(function() {
			return !/\/log\/\d+$/.test(this.href);
		})
		.verticalGlide(true);
		
	b.append([
		'<a class="techyan" href="http://techrelease.mindfree.co.jp/" target="_blank">',
			'<img src="/common/images/techre.gif" alt="Tech Release">',
		'</a>'
	].join(''))

	// 気球がふわふわするやつ
	var balooonA = $('<div id="balooonA"/>'),
		balooonB = $('<div id="balooonB"><a href="http://twitter.com/mindfree_ccp" target="_blank">mindfree_ccp</a></div>'),
		balooonC = $('<div id="balooonC"/>'),
		fuwaEase = 'easeInSine';
	$('body .frameFooter').append(
		balooonA, balooonB, balooonC
	);
	fuwa(balooonA, 3, 800);
	fuwa(balooonB, 7, 700);
	fuwa(balooonC, 5, 650);
	function fuwa(t, s, d) {
		t.animate({
			top: t.position().top - s
		}, d, fuwaEase, function() {
			fuwa2(t, s, d); // fuwa2とあわせて再帰的にループする
		});
	}
	function fuwa2(t, s, d) {
		t.animate({
			top: t.position().top + s
		}, d-100, fuwaEase, function() {
			fuwa(t, s, d);
		});
	}
	// バルーンCはクリックするとするするスクロール
	balooonC.click(function() {
		var _scrollTarget = $.support.boxModel
			? navigator.appName.match(/Opera/)
				? 'html'
				: 'html,body'
			: 'body';
		$(_scrollTarget).animate({
			scrollTop: $('#funyan').offset().top
		}, 600, 'easeInOutCirc');
	});
	
	
	// トピックパスがカラーピッカーになるやつ
	// まさかトピックパスがカラーピッカーになるなんて…！
	function imgLoadingComplete(img, callback) {
		(function() {
			if ( $(img).width() > 0 && $(img).height() > 0 ) {
				callback();
			} else {
				setTimeout(arguments.callee, 50);
			}
		})();
	}
	function topicPathColorPicker() {
		// ここはもともとHTMLに書き出して取得する
		var img = $('<img src="/common/images/topicpath.png" id="topicpath" />'),
			ctx = cvs.getContext('2d');
			
		b.append(img);
		// トピックパス領域に入ったときだけ表示する虫眼鏡のようなやつ
		b.append([
			'<div id="sampleColorBox">',
				'<div id="sampleColor"/>',
				'<div class="arrow">',
					'<div class="line8"/>',
					'<div class="line7"/>',
					'<div class="line6"/>',
					'<div class="line5"/>',
					'<div class="line4"/>',
					'<div class="line3"/>',
					'<div class="line2"/>',
					'<div class="line1"/>',
				'</div>',
			'</div>'
		].join(''));
		var sampleColorBox = $('#sampleColorBox').hide(),
			setColorBoxPos = function(e) {
				sampleColorBox.css({
					top: e.pageY -56,
					left: e.pageX -17
				});
			};
		
		imgLoadingComplete(img.get(0), function() {
			var image = img.get(0);
			cvs.width = image.width;
			cvs.height = image.height;
			ctx.drawImage(image, 0, 0);
			// append
			//$('body').append(cvs);
			/*if ( $('span.pathbg').length ) {
				$('span.pathbg img').replaceWith(cvs);
			}*/
			$('#topicpath').remove();
			b.append(cvsHolder);
			cvsHolder.append(cvs);
			
			var cvsPos = $(cvs).offset();
			function getCVSPos(e) {
				cvsPos = $(cvs).offset();
				return {
					x: e.pageX - cvsPos.left,
					y: e.pageY - cvsPos.top
				}
			}
			$(cvs).hover(
				function(e) {
					$('div.topicPath, span.icon')
						.stop(true, true)
						.fadeTo(100, 0, function() {
							$(this).css('visibility', 'hidden');
						});
					sampleColorBox.stop(true, true).fadeIn();
					setColorBoxPos(e);
				},
				function() {
					$('div.topicPath, span.icon')
						.stop(true, true)
						.fadeTo(100, 1, function() {
							$(this).css('visibility', 'visible');
						});
					sampleColorBox.stop(true, true).fadeOut();
				}
			).mousemove(function(e) {
				setColorBoxPos(e);
				var cp = getCVSPos(e),
					D = ctx.getImageData(cp.x, cp.y, 1, 1).data,
					rgb = 'rgb(' + D[0] + ',' + D[1] + ',' + D[2] + ')';
					
				$('#sampleColor').css('backgroundColor', rgb);
				$(this).click(function() {
					b.css('backgroundColor', rgb);
				});
			});
		});
		
	}
	if ( $.support.opacity ) {
		topicPathColorPicker();
	}
	
	// メンバーショー
	function memberShow() {
		var member = $('#member');
		$('span', member).each(function() {
			var $this = $(this),
				id = $this.attr('id').replace('t_', ''),
				offset = $this.position(),
				pos = {};
				
			if ( $this.hasClass('left') ) {
				pos.top = offset.top - 236;
				pos.left = offset.left - 50;
			} else
			if ( $this.hasClass('leftbelow') ) {
				pos.top = offset.top + 60;
				pos.left = offset.left - 40
			} else
			if ( $this.hasClass('rightbelow') ) {
				pos.top = offset.top + 40;
				pos.left = offset.left - 222;
			} else {
				pos.top = offset.top - 236;
				pos.left = offset.left - 222;
			}
			var card = $('#' + id).css({
						top: pos.top,
						left: pos.left
					})
					.hover(
						function() {
							card.show();
						},
						function() {
							card.hide();
						}
					);
			$(this).hover(
				function() {
					card.show();
				},
				function() {
					card.hide();
				}
			);
		});
	}
	
	function amourList() {
		var itemList = $("#itemList"),
			amourDetails = $("div.amourDetails"),
			anchors = $("a", itemList),
			pageNavAnchors = $("div.amourDetail div.amourPagenav a");
			displayAmourDetail = function(elm) {
				var target = elm.hash,
					$target = $(target);
				amourDetails.each(function() { $elm.hide(); });
				$("div.amourDetail:visible").each(function() {
					$(this).stop(true, true).fadeOut("fast");
				});
				$target.stop(true, true).fadeIn("fast");
				$("p.back a", target).one("click", function() {
					$target.fadeOut("fast");
					return false;
				});
			}
			
		anchors.click(function() {
			displayAmourDetail(this);
			return false;
		});
		pageNavAnchors.click(function() {
			if ( this.className === "list") {
				$(this).parents("div.amourDetail:visible").stop(true, true).fadeOut();
			} else {
				displayAmourDetail(this);
			}
			return false;
		});
	}
	
	// Thanks to YusukeNakanishi
	// http://yusukenakanishi.com/
	function HoshizoranoCanvas() {
		if ( !$.support.leadingWhitespace ) return false;
		var bgMenu = $([
			'<div id="bgMenu">',
				'<a href="javascript:void(0)" id="canvasHide">普通の背景</a>',
				'<a href="javascript:void(0)" id="canvasShow">星空が見たい</a>',
			'</div>'
		].join(''));
		var canvasArea = $('<canvas id="canvasArea"/>');
		var cloud = $('<div id="cloud"/>');
		$('div.container').before(
			canvasArea.css('opacity', 0),
			cloud.css('opacity', 0),
			bgMenu
		);
		$('#canvasHide').click(function() {
			canvasArea.fadeTo('normal', 0);
			$('#bgMenu').addClass('normal');
		});
		$('#canvasShow').click(function() {
			canvasArea.fadeTo('normal', .8);
			$('#bgMenu').removeClass('normal');
		});
		
		var windowHeight = document.height * 1.5;
		var windowWidth = document.width * 2;
		
		canvasArea.attr({
			height: windowHeight,
			width: windowWidth
		});
		
		var ctx = document.getElementById('canvasArea').getContext('2d');
		
		// 背景のグラデーション
		var lingrad = ctx.createLinearGradient(0,0,0,windowHeight);
		lingrad.addColorStop(0, '#030617');
		lingrad.addColorStop(0.6, '#030617');
		lingrad.addColorStop(1, '#372021');
	   
		ctx.fillStyle = lingrad;  // グラデーションを塗りとストロークのスタイルに割り当て
		ctx.fillRect(0,0,windowWidth,windowHeight); // 図形を描く
		ctx.restore(); // 初期状態に戻す
		ctx.save(); // 再び保存
		
		// 1pxと2pxの星
		function smallStarCreate(starNumber, starSize) {
			for(var i=0; i<starNumber; i++) {
				ctx.beginPath();
				var starLeft = Math.floor(Math.random()*windowWidth) + 1,
					starTop = Math.floor(Math.random()*windowHeight) + 1,
					colorVal01 =  Math.floor(Math.random()*106) + 150,
					colorVal02 =  Math.floor(Math.random()*106) + 150,
					opacityVal =  (Math.floor(Math.random()*11)) / 10;
				ctx.fillStyle = "rgba(" + colorVal01 + ", " + colorVal02 + ", " + 255 + ", " + opacityVal + ")";
				ctx.fillRect(starLeft, starTop, starSize, starSize);
				ctx.fill();
			}
		}
		smallStarCreate(20000, 1);
		smallStarCreate(1500, 2);
		ctx.restore();
		ctx.save();
		
		// 3pxと4pxの星
		function bigStarCreate(starNumber, starSize) {
			for(var i=0; i<starNumber; i++) {
				ctx.beginPath();
				var starLeft = Math.floor(Math.random()*windowWidth) + 1,
					starTop = Math.floor(Math.random()*windowHeight) + 1,
					colorVal01 =  Math.floor(Math.random()*106) + 150,
					colorVal02 =  Math.floor(Math.random()*106) + 150,
					opacityVal =  (Math.floor(Math.random()*11)) / 10,
					colorVal =  Math.floor(Math.random()*151),
					radgrad = ctx.createRadialGradient(starLeft,starTop,0,starLeft,starTop,starSize);
				radgrad.addColorStop(0, 'rgba(255, 255, 255, 1)');
				radgrad.addColorStop(1, "rgba(" + colorVal01 + ", " + colorVal02 + ", " + 255 + ", " + opacityVal + ")");
				ctx.fillStyle = radgrad;
				ctx.arc(starLeft, starTop, starSize, 0, Math.PI * 2, true);
				ctx.fill();
			}
		}
		bigStarCreate(100, 2);
		bigStarCreate(10, 3);
		ctx.restore();
		ctx.save();
		
		canvasArea.fadeTo(1500, .8);
		cloud.fadeTo(1500, .9);
	}
	
})(jQuery);

// Cookie management
function setCookie() {
	document.cookie = 'MFHOSHIZORA=ON;path=/';
}
function existCookie() {
	if ( /MFHOSHIZORA\=[^\;]+/.test(document.cookie) )
		return true;
	else
		return false;
}
	
// iframeから呼ばれるfunction
// exValidationのスクロール拡張
function scrollToError(offset) {
	var iframePos = jQuery('#contact').offset(),
		scrollTarget = jQuery.support.boxModel
			? navigator.appName.match(/Opera/) ?
				'html' : 'html,body'
			: 'body';
	jQuery(scrollTarget).animate(
		{
			scrollTop: offset + iframePos.top - 20
		},
		{
			easing: jQuery.easing.easeInOutCirc ? 'easeInOutCirc' : 'swing',
			duration: 500
		}
	);
}
// iframeのtopまでスクロールする
function setTop() {
	var iframePos = jQuery('#contact').offset(),
		scrollTarget = jQuery.support.boxModel
			? navigator.appName.match(/Opera/) ?
				'html' : 'html,body'
			: 'body';
	jQuery(scrollTarget).animate(
		{
			scrollTop: iframePos.top - 20
		},
		{
			easing: jQuery.easing.easeInOutCirc ? 'easeInOutCirc' : 'swing',
			duration: 500
		}
	);
}
// iframeの高さをiframe内コンテンツの高さにあわせる
function setHeight(height, first) {
	var iframe = jQuery('#contact');
	if ( first ) {
		iframe.height(height + 60);
	} else {
		iframe.height(height);
	}
	// BBSのリロードでバグるのでWebkitは一回のみ
	if ( $.browser.webkit && /bbs/.test(location.href) ) return false;
	(function() {
		try {
			if ( iframe[0].contentWindow.document.height >= iframe.height() ) {
				iframe.height(iframe[0].contentWindow.document.height);
			} else {
				setTimeout(arguments.callee, 200);
			}
		} catch(e) {
			setTimeout(arguments.callee, 200);
		}
	})();
}
// トップに戻る
function backHome() {
	location.hash = '#/';
}
