/* takumadesign Common Script */

sfHover = function() {
	var sfEls = document.getElementById("headerLink").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" over";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" over\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

/* Search
------------------------------------------------- */
$(document).ready(function() {
	$('#search').blur(function() {
		var $$=$(this);
		if($$.val()=='' || $$.val()==$$.attr('title')) {
			$$.val($$.attr('title'));
		}
	})
	.focus(function() {
		var $$=$(this);
		if($$.val()==$$.attr('title')) {
			$(this).val('');
		}
	})
	.parents('form:first').submit(function() {
		var $$=$('#search');
		if($$.val()==$$.attr('title')) {
			$$.triggerHandler('focus');
		}
	}).end()
	.blur();
});

/* Portfolio Carousel
------------------------------------------------- */
jQuery(document).ready(function() {
		jQuery('#carousel').jcarousel();
});

/* Rollover
------------------------------------------------- */
$(document).ready(function(options) {
	var c = $.extend({
	hoverSelector: '.rollover, .allbtn img',
	groupSelector: '.btngroup',
	postfix: '_over'
	}, 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($) {
	$(function() {
		$.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];
				});
			}
		},
		//ページ内リンクはするするスクロール
		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){
					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^=#], 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 == 0) target = $('a[name='+this.hrefdata.fragment+']');
				if (target.length) {
					scroller.set({
						endY: target.offset().top,
						hrefdata: this.hrefdata
					});
					return false;
				}
			});
		}
	};
})(jQuery);

/* Flickr
------------------------------------------------- */
$(document).ready(function() {
photo_search({ user_id: '58949794@N00' });
});

// 画像検索を行う関数
function photo_search ( param ) {
    // APIリクエストパラメタの設定
    param.api_key  = '17a4b506254eb4e78a0edd9118619195';
    param.method   = 'flickr.photos.search';
    param.per_page = 9;
    param.sort     = 'date-posted-desc';
    param.format   = 'json';
    param.jsoncallback = 'jsonFlickrApi';

    // APIリクエストURLの生成(GETメソッド)
    var url = 'http://www.flickr.com/services/rest/?'+obj2query( param );

    // script 要素の発行
    var script  = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.src  = url;
    document.body.appendChild( script );
};

// オブジェクトからクエリー文字列を生成する関数
function obj2query ( obj ) {
    var list = [];
    for( var key in obj ) {
        var k = encodeURIComponent(key);
        var v = encodeURIComponent(obj[key]);
        list[list.length] = k+'='+v;
    }
    var query = list.join( '&' );
    return query;
}

// Flickr検索終了後のコールバック関数
function jsonFlickrApi ( data ) {
    // データが取得できているかチェック
    if ( ! data ) return;
    if ( ! data.photos ) return;
    var list = data.photos.photo;
    if ( ! list ) return;
    if ( ! list.length ) return;

	$("#flickr").html("");
		var ul = document.createElement('ul');
		$("#flickr").append(ul);
		for( var i=0; i<list.length; i++ ) {
        	var photo = list[i];
			var li = document.createElement('li');
			var a = document.createElement('a');
			var img = document.createElement( 'img' );
			ul.appendChild(li);
			li.appendChild(a);
			a.appendChild(img);
			a.setAttribute('href', 'http://www.flickr.com/photos/'+photo.owner+'/'+photo.id+'/');
			a.setAttribute("target", "_blank");
			img.setAttribute("src", 'http://static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_s.jpg');
		}
	$("#flickr p").remove();
	$("#flickr ul").fadeIn("slow");
}

/* delicious
------------------------------------------------- */
$(document).ready(function() {
	$.getJSON("http://delicious.com/feeds/json/takuma?count=8&callback=?", function(data) {
		$("#delicious").html("");
		var ul = document.createElement('ul');
		$("#delicious").append(ul);
		for (var i=0, post; post = data[i]; i++) {
			var li = document.createElement('li');
			var a = document.createElement('a');
			ul.appendChild(li);
			li.appendChild(a);
			a.appendChild(document.createTextNode(post.d));
			a.setAttribute('href', post.u);
			a.setAttribute("target", "_blank")
		}
		$("#delicious p").remove();
		$("#delicious ul").fadeIn("slow");
	})
});