/*
 * yuga.js 0.6.3
 *
 * 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
 */

(function($) {

	$(function() {
		$.yuga.selflink({
			reOrignalSrc: 'h1, .pageTop, #gNav li', //現在のページでもファイル名を変更しないように
			postfix: '_over'
		});
		$.yuga.rollover({
			hoverSelector: '.imgLink, .imgLink img, .imgLink input', //ロールオーバーさせる画像用のクラス名
			postfix: '_over'
		});
		$.yuga.externalLink({
			blankIconPath: '<img src="/img/item/icon_blank.gif" alt="別ウィンドウで開きます" class="externalIcon" />',
			notWindowURL: 'a[href^="http://example.com/"],a[href$="pdf"],a[href$="doc"],a[href$="xls"]', //MTなどで別窓が開いてしまう対策
			blankIconHidden: '#sub .externalIcon' //別窓アイコンを表示させたくない要素
		});
		$.yuga.thickbox();
		$.yuga.tab();
		$.yuga.stripe();
		$.yuga.css3class();
		$("a[href*='#']").slideScroll();
		$("a[href$='.pdf']").append('<img src="/img/icons/icon_pdf.gif"  class="externalIcon" />');
		$("a[href$='.doc']").append('<img src="/img/icons/icon_doc.gif"  class="externalIcon" />');
		$("a[href$='.xls']").append('<img src="/img/icons/icon_xls.gif"  class="externalIcon" />');
		$("a[href$='.pps']").append('<img src="/img/icons/icon_pps.gif"  class="externalIcon" />');
	});

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

	$.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]]; 
			}
		},
		//現在のページと親ディレクトリへのリンク
		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);
					});
				}
			});
			$(c.reOrignalSrc).find('img').each(function(){
				$(this).attr('src',this.originalSrc);
			});
		},
		//ロールオーバー
		rollover: function(options) {
			var c = $.extend({
				hoverSelector: '.btn, .allbtn img',
				groupSelector: '.btngroup',
				postfix: '_on'
			}, 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',
				blankIconPath: '<img src="./img/item/icon_blank.gif" alt="別窓で開きます" class="externalIcon" />',
				notWindowURL: 'a[href^="http://example.com/"]',
				blankIconHidden: '#sub .externalIcon',
				noIcon: '.noIcon'
			}, options);
			var e = $('a[href^="http://"]').not(c.notWindowURL).not(c.noIcon).append(c.blankIconPath);
			if (c.windowOpen) {
				e.click(function(){
					window.open(this.href, '_blank');
					return false;
				});
			}
			e.addClass(c.externalClass);
			$(c.blankIconHidden).css("display","none");
		},
		//画像へ直リンクすると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) {
			}	
		},
		//タブ機能
		tab: function(options) {
			var c = $.extend({
				tabNavSelector:'.tabNav',
				activeTabClass:'active'
			}, options);
			$(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.removeClass(c.activeTabClass);
						$(this).addClass(c.activeTabClass);
						tabBodyList.hide();
						$(selecter).show();
						return false;
					});
				});
				tabBodyList.hide()
				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');
		}
	};
})(jQuery);



/* -------------------------------------------------- *
 * ToggleVal Plugin for jQuery                        *
 * Version 1.0                                        *
 * -------------------------------------------------- *
 * Author:   Aaron Kuzemchak                          *
 * URL:      http://kuzemchak.net/                    *
 * E-mail:   afkuzemchak@gmail.com                    *
 * Date:     8/18/2007                                *
 * -------------------------------------------------- */

jQuery.fn.toggleVal = function(focusClass) {
	this.each(function() {
		$(this).focus(function() {
			// clear value if current value is the default
			if($(this).val() == this.defaultValue) { $(this).val(""); }
			
			// if focusClass is set, add the class
			if(focusClass) { $(this).addClass(focusClass); }
		}).blur(function() {
			// restore to the default value if current value is empty
			if($(this).val() == "") { $(this).val(this.defaultValue); }
			
			// if focusClass is set, remove class
			if(focusClass) { $(this).removeClass(focusClass); }
		});
	});
}

$(document).ready(function() {
	$(".searchBox, textarea").toggleVal();
});


/* -------------------------------------------------- *
 * Font Size Changer                                  *
 * -------------------------------------------------- */

function fontsizeChanger() {
	document.write('<dl class="fontsize">');
	document.write('<dt class="fontsize-title">文字の大きさ</dt>');
	document.write('<dd class="small"><a href="javascript:;" onclick="setActiveStyleSheet(\'small\');" class="fontsize_s">小</a></dd>');
	document.write('<dd class="middle"><a href="javascript:;" onclick="setActiveStyleSheet(\'middle\');" class="fontsize_m">中</a></dd>');
	document.write('<dd class="large"><a href="javascript:;" onclick="setActiveStyleSheet(\'large\');" class="fontsize_l">大</a></dd>');
	document.write('</dl>');
}

function setActiveStyleSheet(title) {
  var i, a, main, b;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}
function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}


window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);




/*---------------------------------------------------------------

 jQuery.slideScroll.js
 
 jQuery required (tested on version 1.2.6)
 encoding UTF-8

 Copyright (c) 2008 nori (norimania@gmail.com)
 http://moto-mono.net
 Licensed under the MIT

 $Update: 2008-12-24 20:00
 $Date: 2008-12-22 23:30
 
 ----------------------------------------------------------------*/

$.fn.slideScroll = function(options){
	
	var c = $.extend({
		interval: 1, // 変化はあんまりないかも
		easing: 0.6, // 0.4 ~ 2.0 くらいまで
		comeLink: false
	},options);
	var d = document;
	
	// timerとposのscopeを$.fn.slideScroll内に限定する
	var timer;
	var pos;
	
	// スクロール開始時の始点を得る
	function currentPoint(){
		var current = {
			x: d.body.scrollLeft || d.documentElement.scrollLeft,
			y: d.body.scrollTop || d.documentElement.scrollTop
		}
		return current;
	}
	
	// 現在のウィンドウサイズとターゲット位置から最終到達地点を決める
	function setPoint(){
		
		// 表示部分の高さと幅を得る
		var h = d.documentElement.clientHeight;
		var w = d.documentElement.clientWidth;
		
		// ドキュメントの最大の高さと幅を得る
		var maxH = d.documentElement.scrollHeight;
		var maxW = d.documentElement.scrollWidth;
		
		// ターゲットの位置が maxH(W)-h(w) < target < maxH(W) なら スクロール先をmaxH(W)-h(w)にする
		pos.top = ((maxH-h)<pos.top && pos.top<maxH) ? maxH-h : pos.top;
		pos.left = ((maxW-w)<pos.left && pos.left<maxW) ? maxW-w : pos.left;
	}
	
	// 次のスクロール地点を決める
	function nextPoint(){
		var x = currentPoint().x;
		var y = currentPoint().y;
		var sx = Math.ceil((x - pos.left)/(5*c.easing));
		var sy = Math.ceil((y - pos.top)/(5*c.easing));
		var next = {
			x: x - sx,
			y: y - sy,
			ax: sx,
			ay: sy
		}
		return next;
	}
	
	// 到達地点に近づくまでスクロールを繰り返す
	function scroll(href){
		var movedHash = href;
		timer = setInterval(function(){
			nextPoint();
			
			// 到達地点に近づいていたらスクロールをやめる
			if(Math.abs(nextPoint().ax)<1 && Math.abs(nextPoint().ay)<1){
				clearInterval(timer);
				window.scroll(pos.left,pos.top);
				location.href = movedHash;
			}
			window.scroll(nextPoint().x,nextPoint().y);
		},c.interval);
	}
	
	// URIにhashがある場合はスクロールする
	function comeLink(){
		if(location.hash){
			if($(location.hash) && $(location.hash).length>0){
				pos = $(location.hash).offset();
				setPoint();
				window.scroll(0,0);
				if($.browser.msie){
					setTimeout(function(){
						scroll(location.hash);
					},50);
				}else{
					scroll(location.hash);
				}
			}
		}
	}
	if(c.comeLink) comeLink();
	
	// アンカーにclickイベントを定義する
	$(this).each(function(){
		var url = location.href.split("#")[0]; 
		if(this.hash && $(this.hash).length>0 
			&& this.href.match(new RegExp(url.split("?")[0]))){	// パラメータに対応
			var hash = this.hash;
			$(this).click(function(){
								   				
				// ターゲットのoffsetを得る
				pos = $(hash).offset();
				
				// スクロール中ならスクロールをやめる
				clearInterval(timer);
				
				// 到達地点を決めてスクロールを開始する
				setPoint();
				scroll(this.href);
				return false;
			});
		}
	});
}