(function($) {
	/*
	 * yuga.js 0.7.1 - 優雅なWeb制作のためのJS
	 *
	 * Copyright (c) 2009 Kyosuke Nakamura (kyosuke.jp)
	 * Licensed under the MIT License:
	 * http://www.opensource.org/licenses/mit-license.php
	 *
	 * Since:     2006-10-30
	 * Modified:  2009-01-27
	 *
	 */
	
	$(function() {
		//$.yuga.selflink();
		$.yuga.rollover();
		$.yuga.scroll();
	});

	//---------------------------------------------------------------------

	$.yuga = {
		// URIを解析したオブジェクトを返すfunction
		Uri: function(path){
			var self = this;
			this.originalPath = path;
			//絶対パスを取得
			this.absolutePath = (function(){
				var e = document.createElement('span');
				e.innerHTML = '<a href="' + path + '" />';
				return e.firstChild.href;
			})();
			//絶対パスを分解
			var fields = {'schema' : 2, 'username' : 5, 'password' : 6, 'host' : 7, 'path' : 9, 'query' : 10, 'fragment' : 11};
			var r = /^((\w+):)?(\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/.exec(this.absolutePath);
			for (var field in fields) {
				this[field] = r[fields[field]];
			}
			this.querys = {};
			if(this.query){
				$.each(self.query.split('&'), function(){
					var a = this.split('=');
					if (a.length == 2) self.querys[a[0]] = a[1];
				});
			}
		},
		//現在のページと親ディレクトリへのリンク
		selflink: function (options) {
			var c = $.extend({
				selfLinkAreaSelector:'body',
				selfLinkClass:'current',
				parentsLinkClass:'parentsLink',
				postfix: '_cr',
				changeImgSelf:true,
				changeImgParents:true
			}, options);
			$(c.selfLinkAreaSelector+((c.selfLinkAreaSelector)?' ':'')+'a[href]').each(function(){
				var href = new $.yuga.Uri(this.getAttribute('href'));
				var setImgFlg = false;
				if ((href.absolutePath == location.href) && !href.fragment) {
					//同じ文書にリンク
					$(this).addClass(c.selfLinkClass);
					setImgFlg = c.changeImgSelf;
				} else if (0 <= location.href.search(href.absolutePath)) {
					//親ディレクトリリンク
					$(this).addClass(c.parentsLinkClass);
					setImgFlg = c.changeImgParents;
				}
				if (setImgFlg){
					//img要素が含まれていたら現在用画像（_cr）に設定
					$(this).find('img').each(function(){
						this.originalSrc = $(this).attr('src');
						this.currentSrc = this.originalSrc.replace(new RegExp('('+c.postfix+')?(\.gif|\.jpg|\.png)$'), c.postfix+"$2");
						$(this).attr('src',this.currentSrc);
					});
				}
			});
		},
		//ロールオーバー
		rollover: function(options) {
			var c = $.extend({
				hoverSelector: '.over, .allover img',
				groupSelector: '.overgroup',
				postfix: '_on'
			}, options);
			//ロールオーバーするノードの初期化
			var rolloverImgs = $(c.hoverSelector).filter(isNotCurrent);
			rolloverImgs.each(function(){
				this.originalSrc = $(this).attr('src');
				this.rolloverSrc = this.originalSrc.replace(new RegExp('('+c.postfix+')?(\.gif|\.jpg|\.png)$'), c.postfix+"$2");
				this.rolloverImg = new Image;
				this.rolloverImg.src = this.rolloverSrc;
			});
			//グループ内のimg要素を指定するセレクタ生成
			var groupingImgs = $(c.groupSelector).find('img').filter(isRolloverImg);

			//通常ロールオーバー
			rolloverImgs.not(groupingImgs).hover(function(){
				$(this).attr('src',this.rolloverSrc);
			},function(){
				$(this).attr('src',this.originalSrc);
			});
			//グループ化されたロールオーバー
			$(c.groupSelector).hover(function(){
				$(this).find('img').filter(isRolloverImg).each(function(){
					$(this).attr('src',this.rolloverSrc);
				});
			},function(){
				$(this).find('img').filter(isRolloverImg).each(function(){
					$(this).attr('src',this.originalSrc);
				});
			});
			//フィルタ用function
			function isNotCurrent(i){
				return Boolean(!this.currentSrc);
			}
			function isRolloverImg(i){
				return Boolean(this.rolloverSrc);
			}

		},
		//ページ内リンクはするするスクロール
		scroll: function(options) {
			//ドキュメントのスクロールを制御するオブジェクト
			var scroller = (function() {
				var c = $.extend({
					easing:100,
					step:30,
					fps:60,
					fragment:''
				}, options);
				c.ms = Math.floor(1000/c.fps);
				var timerId;
				var param = {
					stepCount:0,
					startY:0,
					endY:0,
					lastY:0
				};
				//スクロール中に実行されるfunction
				function move() {
					if (param.stepCount == c.step) {
						//スクロール終了時
						setFragment(param.hrefdata.absolutePath);
						window.scrollTo(getCurrentX(), param.endY);
					} else if (param.lastY == getCurrentY()) {
						//通常スクロール時
						param.stepCount++;
						window.scrollTo(getCurrentX(), getEasingY());
						param.lastY = getEasingY();
						timerId = setTimeout(move, c.ms); 
					} else {
						//キャンセル発生
						if (getCurrentY()+getViewportHeight() == getDocumentHeight()) {
							//画面下のためスクロール終了
							setFragment(param.hrefdata.absolutePath);
						}
					}
				}
				function setFragment(path){
if (path.search(/#header$/) > -1) return;
					location.href = path
				}
				function getCurrentY() {
					return document.body.scrollTop  || document.documentElement.scrollTop;
				}
				function getCurrentX() {
					return document.body.scrollLeft  || document.documentElement.scrollLeft;
				}
				function getDocumentHeight(){
					return document.documentElement.scrollHeight || document.body.scrollHeight;
				}
				function getViewportHeight(){
					return (!$.browser.safari && !$.browser.opera) ? document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight : window.innerHeight;
				}
				function getEasingY() {
					return Math.floor(getEasing(param.startY, param.endY, param.stepCount, c.step, c.easing));
				}
				function getEasing(start, end, stepCount, step, easing) {
					var s = stepCount / step;
					return (end - start) * (s + easing / (100 * Math.PI) * Math.sin(Math.PI * s)) + start;
				}
				return {
					set: function(options) {
						this.stop();
						if (options.startY == undefined) options.startY = getCurrentY();
						param = $.extend(param, options);
						param.lastY = param.startY;
						timerId = setTimeout(move, c.ms); 
					},
					stop: function(){
						clearTimeout(timerId);
						param.stepCount = 0;
					}
				};
			})();
			$('a[href^=#]:not(a[href=#]), area[href^=#]:not(area[href=#])').not('a[href=#], area[href=#]').live('click',function(){
				this.hrefdata = new $.yuga.Uri(this.getAttribute('href'));
				var target = $('#'+this.hrefdata.fragment);
				if (target.length == 0) target = $('a[name='+this.hrefdata.fragment+']');
				if (target.length) {
					scroller.set({
						endY: target.offset().top,
						hrefdata: this.hrefdata
					});
					return false;
				}
			});
		}
	};
	
	$(function(){
		
		/*Slider*/	
		var itemWigth = 387;
		var itemSize = $("#slider-inner li").size();
		var i = 0;
		
		//読み込み時設定
		$("#slider-icon").html("<ol></ol>");
		for(i; i<itemSize; i++){
			$('ol','#slider-icon').append('<li><img src="/common/images/icon_slider_off.png" width="14" height="14" /></li>');
		};
		$.support.localStorage = false;
		if(('localStorage' in window) && window['localStorage']!== null)
		$.support.localStorage = true;
		
		var activeSet = "";
		
		if($.support.localStorage){
			var activeSet = localStorage['pickupActive'];
			activeSet = parseInt(activeSet);
		}
		if(activeSet){
			$('li:eq('+activeSet+')',"#slider-icon").addClass('active');
			$("#slider-icon").data('viewNum',activeSet);
			$("#slider-inner li:lt("+activeSet+")").appendTo("#slider-inner ul");
			$("#slider-inner li:last").prependTo("#slider-inner ul");	
			$("#slider-inner li:last").prependTo("#slider-inner ul");
		}else{
			$('li:first',"#slider-icon").addClass('active');
			$("#slider-icon").data('viewNum',0);
			$("#slider-inner li:last").prependTo("#slider-inner ul");	
			$("#slider-inner li:last").prependTo("#slider-inner ul");
		}
		
		$("#slider-inner li").removeClass();
		
		$("#slider-inner").css("width",itemWigth*itemSize+"px");
		$("#slider-inner li img").css("width",itemWigth-12 + "px");
		$("#slider-inner").css("margin-left","-"+itemWigth+"px");
		
		$("#slider-inner li:eq(2)").addClass('active').css({
			float: "left",
			margin: "0 0 0 -165px",
			zoom: 1,
			zIndex: 10
		}).find('figure').css({
			width: "470px"
		}).find('figcaption').css({
			width: "450px"
		}).end().find('img').css({
			width: "470px",
			height: "313px"
		});
		
		$("#slider-inner li:eq(3)").css({
			marginLeft: "-165px"
		});
		
		$("#slider-right-btn,#slider-left-btn").show();
		
		
		//←ボタン
		$("#slider-left-btn").live('click',function(){
			$("#slider-right-btn,#slider-left-btn").hide();
			$('li',"#slider-icon").removeClass('active');
			$('li','#slider-inner').removeClass('active');
			var x = $("#slider-icon").data('viewNum');
			if(x===0){
				$('li:last',"#slider-icon").addClass('active');
				$("#slider-icon").data('viewNum',itemSize-1);
				if($.support.localStorage){
					localStorage['pickupActive'] = itemSize-1;
				}
			}else{
				y = x-1;
				$('li:eq('+y+')',"#slider-icon").addClass('active');
				$("#slider-icon").data('viewNum',y);
				if($.support.localStorage){
					localStorage['pickupActive'] = y;
				}
			}
			
			$("#slider-inner li:eq(1)").css({
				zIndex: 10
			}).animate({
				marginTop: "0px",
				marginLeft: "-165px"
			},"slow","swing").find('figure').animate({
				width: "470px"
			},"slow","swing").find('figcaption').animate({
				width: "450px"
			},"slow","swing").end().find('img').animate({
				width: "470px",
				height: "313px"
			},"slow","swing",function(){
				$("#slider-inner li:eq(1)").addClass('active')
			});
			
			$("#slider-inner li:eq(2)").css({
				zIndex: 2
			}).animate({
				marginTop: "30px",
				marginLeft: "-165px",
				zIndex: 1
			},"slow","swing").find('figure').animate({
				width: "375px"
			},"slow","swing").find('figcaption').animate({
				width: "355px"
			},"slow","swing").end().find('img').animate({
				width: "375px",
				height: "250px"
			},"slow","swing");
			
			$("#slider-inner li:eq(3)").animate({
				marginLeft: "0px"
			},"slow","swing");
			
			$("#slider-inner").animate({
				marginLeft : parseInt($("#slider-inner").css("margin-left"))+itemWigth+"px"
			},"slow","swing", 
			function(){
				$("#slider-inner").css("margin-left","-"+itemWigth+"px")
				$("#slider-inner li:last").prependTo("#slider-inner ul");
				$("#slider-right-btn,#slider-left-btn").show();
			});
		});
		//→ボタン
		$("#slider-right-btn").live('click',function(){
			$("#slider-right-btn,#slider-left-btn").hide();
			$('li',"#slider-icon").removeClass('active');
			$('li','#slider-inner').removeClass('active');
			var x = $("#slider-icon").data('viewNum');
			if(x===itemSize-1){
				$('li:first',"#slider-icon").addClass('active');
				$("#slider-icon").data('viewNum',0);
				if($.support.localStorage){
					localStorage['pickupActive'] = 0;
				}
			}else{
				y = x+1;
				$('li:eq('+y+')',"#slider-icon").addClass('active');
				$("#slider-icon").data('viewNum',y);
				if($.support.localStorage){
					localStorage['pickupActive'] = y;
				}
			}
			
			$("#slider-inner li:eq(3)").css({
				zIndex: 10
			}).animate({
				marginTop: "0px",
				marginLeft: "-165px"
			},"slow","swing").find('figure').animate({
				width: "470px"
			},"slow","swing").find('figcaption').animate({
				width: "450px"
			},"slow","swing").end().find('img').animate({
				width: "470px",
				height: "313px"
			},"slow","swing",function(){
				$("#slider-inner li:eq(3)").addClass('active')
			});
			
			$("#slider-inner li:eq(2)").css({
				zIndex: 1
			}).animate({
				marginTop: "30px",
				marginLeft: "0px"
			},"slow","swing").find('figure').animate({
				width: "375px"
			},"slow","swing").find('figcaption').animate({
				width: "355px"
			},"slow","swing").end().find('img').animate({
				width: "375px",
				height: "250px"
			},"slow","swing");
			
			$("#slider-inner li:eq(4)").animate({
				marginLeft: "-165px"
			},"slow","swing");
			
			$("#slider-inner li:eq(5)").animate({
				marginLeft: "0px"
			},"slow","swing");
			
			$("#slider-inner").animate({
				marginLeft : parseInt($("#slider-inner").css("margin-left"))-itemWigth+"px"
			},"slow","swing" , 
			function(){
				$("#slider-inner").css("margin-left","-"+itemWigth+"px")
				$("#slider-inner li:first").appendTo("#slider-inner ul");
				$("#slider-right-btn,#slider-left-btn").show();
			});
		});
		
		
		$('li','#works-entries').live('mouseenter',function(){
			var hrefLink = $(this).find('a').attr('href');
			$(this).append('<a href="'+hrefLink+'" class="hover-flame"></a>');		
		}).live('mouseleave',function(){
			$('.hover-flame').remove();
		});
		
		$('li','.recommended').live('mouseenter',function(){
			var hrefLink = $(this).find('a').attr('href');
			$(this).append('<a href="'+hrefLink+'" class="hover-flame"></a>');		
		}).live('mouseleave',function(){
			$('.hover-flame').remove();
		});
		
		/*entry images scroll*/
		var entryImageWidht = 0;
		$('li','.entry-images').each(function(){
			entryImageWidht += $(this).width() + 10;
		});
		if(entryImageWidht < 728){$('.entry-images').css('overflow-x','hidden')}
		$('ul','.entry-images').width(entryImageWidht);
		
		/*serch*/
		$(':submit','#cse-search-form').live('submit click',function(){
			if($(':text','#cse-search-form').val() === ''){
				$('span','#cse-search-form').remove();
				$('#cse-search-form').append('<span>検索語句を入力してください</span>');
				return false;
			};
		});
		$(':text,span','#cse-search-form').live('click focus blur',function(){
			$('span','#cse-search-form').remove();
		});
		
		/*Grid*/
		var $container = $('#grid');
		$container.imagesLoaded(function(){
		  $container.masonry({
			itemSelector : '.itemBox',
			columnWidth : 240
		  });
		});
		
		/*BigLink*/
		$('li','#slider-inner').biglink();
		$('.biglink','#top-entry').biglink();
		$('footer','#top-entry').biglink();
		$('dl','.side-nav').biglink();
		$('li','ul.entries').biglink();
		$('dl','.interview-block').biglink();
		$('dl','.interview-block02').biglink();
		$('li','#hatebu-entory-block').biglink();
		
		/*accordion*/
		$('dt a','.category').live('click',function(e){
			$(e.target).parent('dt').next().stop(true,true).slideToggle('slow',function(){
				$(this).prev().toggleClass('active');
			});
			return false;
		});
		
		$('.pager').find('a:not([href*=#])').smarthistory({
			defaultData: $('html').html(),
			target: function() {
				return $(this).attr('href')
			},
			before: function() {
				// ajax前の処理
			},
			change: function(html) {
				$('#main').fadeOut('fast', function() {
					$(this).html( $(html).find("#main")).fadeIn();
					$('title').text($(html).find("title"));
					$($.browser.safari ? 'body' : 'html').animate({scrollTop:0}, 640, 'swing');
				});
			}
		});
		/*lightbox*/
		$('a.lightbox').lightBox({
			fixedNavigation:false,
			imageLoading: '/common/images/lightbox-ico-loading.gif',
			imageBtnClose: '/common/images/lightbox-btn-close.gif',
			imageBtnPrev: '/common/images/lightbox-btn-prev.gif',
			imageBtnNext: '/common/images/lightbox-btn-next.gif',
			imageBlank: '/common/images/lightbox-blank.gif'
		});
	});
	
	$.fn.biglink = function(){
		$(this).css({cursor:"pointer"})
		.live('click',function(){
			window.location.href = $(this).find('a').attr('href');
		});
	}

	$.fn.smarthistory = function(opt) {
		if ( !('pushState' in history) ) {
			return this;
		}
		
		opt = $.extend({
			target: '',
			defaultData: '',
			cache: true,
			before: function() {},
			change: function() {}
		}, opt);
		
		window.addEventListener('popstate', function(event) {
			var state = event.state || {};
			var data = state.data;
			if (data) {
				opt.change(data, event);
			}
			else {
				history.replaceState({data: opt.defaultData}, null, null);
				//window.location.reload();
			}
		},false);
		var cache = {};
		
		return this.live('click', function(event) {
			event.preventDefault();
			var $elem = $(this);
			var target = $.isFunction(opt.target) ? opt.target.call(this) : opt.target;
			var href = $elem.attr('href');
			opt.before.call(this);
			
			if (opt.cache && target in cache) {
				opt.change(cache[target]);
				history.pushState({data: cache[target]}, href, href);
			}
			else {
				$.get(target)
					.done(function(data) {
						opt.change(data);
						history.pushState({data: data}, href, href);
						if (opt.cache) {
							cache[target] = data;
						}
				})
				.fail(function() {
					location.href = target;
				});
			}
		});
	}
	
	$.hatebuList = function(){
		Hatena.BookmarkWidget.url   = "http://mtl.recruit.co.jp/blog/";
		Hatena.BookmarkWidget.title = "エントリー";
		Hatena.BookmarkWidget.sort  = "";
		Hatena.BookmarkWidget.width = 230;
		Hatena.BookmarkWidget.num   = 10;
		Hatena.BookmarkWidget.theme = "notheme";
		Hatena.BookmarkWidget.load();
	}

})(jQuery);

