/*
 * yuga.js 0.6.3 - 優雅なWeb制作のためのJS
 *
 * Copyright (c) 2007 Kyosuke Nakamura (kyosuke.jp)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Since:     2006-10-30
 * Modified:  2008-07-07
 *
 * jQuery 1.2.6
 * ThickBox 3.1
 */

/*
 * [使用方法] XHTMLのhead要素内で次のように読み込みます。
 
<link rel="stylesheet" href="css/thickbox.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<script type="text/javascript" src="js/yuga.js" charset="utf-8"></script>

 */


(function($) {

	$(function() {
		// $.yuga.selflink();
		$.yuga.rollover();
		// $.yuga.externalLink();
		//$.yuga.thickbox();
		//$.yuga.scroll();
		//$.yuga.tab();
		//$.yuga.stripe();
		//$.yuga.css3class();
		//$.yuga.popup();
		//$.yuga.dropDownMenu();
		//$.yuga.inputKeyword();
	});

	//---------------------------------------------------------------------

	$.yuga = {
		// URIを解析したオブジェクトを返すfunction
		Uri: function(path){
			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]]; 
			}
		},
		//親要素を探す
		searchParent: function(o, t){
			var p = o.parent();
			return (p[0].tagName.toLowerCase() == t.toLowerCase() ? p : arguments.callee(p, t));
		},
		//getを配列に
		getRequest: function(){
			  if(location.search.length > 1) {
				var get = new Object();
				var ret = location.search.substr(1).split("&");
				for(var i = 0; i < ret.length; i++) {
				  var r = ret[i].split("=");
				  var p = r[1].split("#");
				  get[r[0]] = p[0];
				  
				}
				return get;
			  } else {
				return false;
			  }
		},
		//現在のページと親ディレクトリへのリンク
		selflink: function (options) {
			var c = $.extend({
				selfLinkClass:'current',
				parentsLinkClass:'parentsLink',
				postfix: '_cr'
			}, options);
			$('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 = true;
				} else if (0 <= location.href.search(href.absolutePath)) {
					//親ディレクトリリンク
					$(this).addClass(c.parentsLinkClass);
					setImgFlg = true;
				}
				if (setImgFlg){
					//img要素が含まれていたら現在用画像（_cr）に設定
					$(this).find('img').each(function(){
						this.originalSrc = $(this).attr('src');
						this.currentSrc = this.originalSrc.replace(/(\.gif|\.jpg|\.png)/, c.postfix+"$1");
						$(this).attr('src',this.currentSrc);
					});
				}
			});
		},
		//ロールオーバー
		rollover: function(options) {
			var c = $.extend({
				hoverSelector: '.hover',
				groupSelector: '.itemGrp',
				postfix: '-over'
			}, options);
			//ロールオーバーするノードの初期化
			$(c.hoverSelector).filter(isNotCurrent).each(function(){
				this.originalSrc = $(this).attr('src');
				this.rolloverSrc = this.originalSrc.replace(/(\.gif|\.jpg|\.png)$/, c.postfix+"$1");
				this.rolloverImg = new Image;
				this.rolloverImg.src = this.rolloverSrc;
			});
			//グループ内のimg要素を指定するセレクタ生成
			var inGroup = new Array();
			$.each(c.groupSelector.split(/,\s?/g), function(i, n){
				inGroup.push(n + ' ' + c.hoverSelector.replace(/,\s?/g, ', '+ n +' '));
			});
			var inGroupSelector = $(inGroup.join(', '));
			//通常ロールオーバー
			$(c.hoverSelector).not(inGroupSelector).filter(isNotCurrent).hover(function(){
				$(this).attr('src',this.rolloverSrc);
			},function(){
				$(this).attr('src',this.originalSrc);
			});
			//グループ化されたロールオーバー
			$(c.groupSelector).hover(function(){
				$(this).find('img').filter(c.hoverSelector).filter(isNotCurrent).each(function(){
					$(this).attr('src',this.rolloverSrc);
				});
			},function(){
				$(this).find('img').filter(c.hoverSelector).filter(isNotCurrent).each(function(){
					$(this).attr('src',this.originalSrc);
				});
			});
			//フィルタ用function
			function isNotCurrent(i){
				return Boolean(!this.currentSrc);
			}
		},
		//外部リンクは別ウインドウを設定
		externalLink: function(options) {
			var c = $.extend({
				windowOpen:true,
				externalClass: 'externalLink'
			}, options);
			var e = $('a[href^="http://"]');
			if (c.windowOpen) {
				e.click(function(){
					window.open(this.href, '_blank');
					return false;
				});
			}
			e.addClass(c.externalClass);
		},
		//画像へ直リンクするとthickboxで表示(thickbox.js利用)
		thickbox: function() {
			try {
				tb_init('a[@href$=".jpg"]:not(.thickbox), a[@href$=".gif"]:not(.thickbox), a[@href$=".png"]:not(.thickbox)');
			} catch(e) {
			}	
		},
		//ページ内リンクはするするスクロール
		scroll: function(options) {
			//ドキュメントのスクロールを制御するオブジェクト
			var scroller = (function() {
				var c = $.extend({
					easing:100,
					step:30,
					fps:60
				}, 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) {
						//スクロール終了時
						window.scrollTo(getCurrentX(), param.endY);
					} else if (param.lastY == getCurrentY()) {
						//通常スクロール時
						param.stepCount++;
						window.scrollTo(getCurrentX(), getEasingY());
						param.lastY = getEasingY();
						timerId = setTimeout(move, c.ms); 
					}
				}
				function getCurrentY() {
					return document.body.scrollTop  || document.documentElement.scrollTop;
				}
				function getCurrentX() {
					return document.body.scrollLeft  || document.documentElement.scrollLeft;
				}
				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^=#], area[href^=#]').not('a[href=#], area[href=#]').each(function(){
				this.hrefdata = new $.yuga.Uri(this.getAttribute('href'));
			}).click(function(){
				var target = $('#'+this.hrefdata.fragment);
				if (target.length) {
					scroller.set({
						endY: target.offset().top
					});
					return false;
				}
			});
		},
		//タブ機能
		tab: function(options) {
			var c = $.extend({
				tabNavSelector:'.tabInterface',
				activeTabClass:'active'
			}, options);
			
			var get = new $.yuga.getRequest();
			
			$(c.tabNavSelector).each(function(){
				var tabNavList = $(this).find('a[href^=#], area[href^=#]');
				var tabBodyList;
				tabNavList.each(function(){
					this.hrefdata = new $.yuga.Uri(this.getAttribute('href'));
					var selecter = '#'+this.hrefdata.fragment;
					if (tabBodyList) {
						tabBodyList = tabBodyList.add(selecter);
					} else {
						tabBodyList = $(selecter);
					}
					$(this).unbind('click');
					$(this).click(function(){

						tabNavList.parent().removeClass(c.activeTabClass);
						$(this).parent().addClass(c.activeTabClass);
						tabBodyList.fadeOut(100);
						$(selecter).fadeIn(100);
						return false;
					});
				});
				tabBodyList.hide();
				if(get["tab"]){
					tabNavList.filter(':lt(' + get["tab"] + ')').trigger('click');
				}else{
					tabNavList.filter(':first').trigger('click');
				}
			});
		},
		//奇数、偶数を自動追加
		stripe: function(options) {
			var c = $.extend({
				oddClass:'odd',
				evenClass:'even'
			}, options);
			$('ul, ol').each(function(){
				//JSでは0から数えるのでevenとaddを逆に指定
				$(this).children('li:odd').addClass(c.evenClass);
				$(this).children('li:even').addClass(c.oddClass);
			});
			$('table, tbody').each(function(){
				$(this).children('tr:odd').addClass(c.evenClass);
				$(this).children('tr:even').addClass(c.oddClass);
			});
		},
		//css3のクラスを追加
		css3class: function() {
			//:first-child, :last-childをクラスとして追加
			$('body :first-child').addClass('firstChild');
			$('body :last-child').addClass('lastChild');
			//css3の:emptyをクラスとして追加
			$('body :empty').addClass('empty');
		},
		// popup
		popup: function() {
			var propup = function(o) {
				o.url = (typeof o.url == 'undefined') ? './' : o.url;
				o.width = (typeof o.width == 'undefined') ? screen.width/2 : o.width;
				o.height = (typeof o.height == 'undefined') ? screen.height/2 : o.height;
				if((o.width<=1)&&(o.width>0)){o.width*=screen.width}
				if((o.height<=1)&&(o.height>0)){o.height*=screen.height}
				o.xpos = (typeof o.xpos == 'undefined') ? (screen.width/2)-(o.width/2) : o.xpos;
				o.ypos = (typeof o.ypos == 'undefined') ? (screen.height/2)-(o.height/2) : o.ypos;
				o.xoffset = (typeof o.xoffset == 'undefined') ? 0 : o.xoffset;
				o.yoffset = (typeof o.yoffset == 'undefined') ? 0 : o.yoffset;
				o.name = (typeof o.name == 'undefined') ? 'propup' : o.name;
				o.scrollbars = (typeof o.scrollbars == 'undefined') ? 'no' : o.scrollbars;
				o.resizable = (typeof o.resizable == 'undefined') ? 'no' : o.resizable;
				o.status = (typeof o.status == 'undefined') ? 'no' : o.status;
				o.locat = (typeof o.locat == 'undefined') ? 'no' : o.locat;
				o.toolbar = (typeof o.toolbar == 'undefined') ? 'no' : o.toolbar;
			 
				if(o.xpos == "left"){o.xpos=0;}
				if(o.xpos == "right"){o.xpos = screen.width-o.width;}
				
				if(o.ypos == "top"){o.ypos=0;}
				if(o.ypos == "bottom"){o.ypos = screen.height-o.height;}
				
				o.xpos += o.xoffset
				o.ypos += o.yoffset
			 
				var scrollbarstext = 'scrollbars = '+o.scrollbars+",";
				var resizabletext = 'resizable = '+o.resizable+",";
				var statustext = 'status = '+o.status+",";
				var locationtext = 'location = '+o.locat+",";
				var toolbartext = 'toolbar = '+o.toolbar+",";
			 
				features = scrollbarstext+resizabletext+statustext;
				features = features + locationtext+toolbartext;
				features = features + 'width = '+o.width+',height = '+o.height;
				features = features + ',top = ' + o.ypos;
				features = features + ',left = ' + o.xpos;
					
				var win = null;
				win = window.open(o.url, o.name, features);
			}

			$('a.popup').click(function(){
				return propup({url:this.href,width:620,height:650,name:'popup',scrollbars:'yes',resizable:'yes'});
			});

			function winOpen(url) {
				var w = window.open(url,'popup','width=620,height=650,scrollbars=1,resizable=1');
				w.focus();
				return false;
			};

		},
		// ドロップダウンメニュー	
		dropDownMenu: function(options){
			var c = $.extend({
				hideSelector:'#globalNavi ul.inner',
				ulSelector:'#globalNavi > ul > li',
				activeClass:'active'
			}, options);
			$(c.hideSelector).css({display: "none"}); // Opera Fix

			$(c.ulSelector).each(function(){					  
				$(this).hover(function(){
					$(this).addClass(c.activeClass);
					if($(this).find('ul:first').css("display") == "none"){
						$(this).find('ul:first').css({visibility: "visible",display: "none"}).slideDown(250);
					}				
				},function(){
					if(!$(this).find('ul').is(".inner")){
						$(this).removeClass(c.activeClass);
					}
					$(this).find('ul:first').slideUp(200,function(){
						$(this).parent().removeClass(c.activeClass);
					});
				});
			});
		},
		// キーワードとかでるやつ
		inputKeyword: function(options){
			var c = $.extend({
				keyword:'Keyword',
				inputSelector:'#q'
			}, options);
			$(c.inputSelector).css({color: "#ccc"}).val(c.keyword);
			$(c.inputSelector).blur(function(){
				if(this.value==''){
					this.value= c.keyword;
					$(this).css({color: "#ccc"});
				}
			});
			$(c.inputSelector).click(function(){
				if(this.value==c.keyword){
					$(this).css({color: "#000"});
					this.value= '';
				}
			});
		}
	};
})(jQuery);
