//========== twitter ==========//

(function($) {
	/*
		jquery.twitter.js v1.5
		Last updated: 08 July 2009

		Created by Damien du Toit
		http://coda.co.za/blog/2008/10/26/jquery-plugin-for-twitter

		Licensed under a Creative Commons Attribution-Non-Commercial 3.0 Unported License
		http://creativecommons.org/licenses/by-nc/3.0/
	*/

	$.fn.getTwitter = function(options) {

		$.fn.getTwitter.defaults = {
			userName: null,
			numTweets: 5,
			loaderText: "Loading tweets...",
			slideIn: true,
			slideDuration: 750,
			showHeading: true,
			headingText: "",
			showProfileLink: true,
			showTimestamp: true
		};

		var o = $.extend({}, $.fn.getTwitter.defaults, options);

		return this.each(function() {
			var c = $(this);

			// hide container element, remove alternative content, and add class
			c.hide().empty().addClass("twitted");

			// add heading to container element
			if (o.showHeading) {
				c.append(o.headingText);
			}

			// add twitter list to container element
			var twitterListHTML = "<ul id=\"twitter_update_list\"><li></li></ul>";
			c.append(twitterListHTML);

			var tl = $("#twitter_update_list");

			// hide twitter list
			tl.hide();

			// add preLoader to container element
			var preLoaderHTML = $("<p class=\"preLoader\">"+o.loaderText+"</p>");
			c.append(preLoaderHTML);

			// add Twitter profile link to container element
			if (o.showProfileLink) {
				var profileLinkHTML = "";
				c.append(profileLinkHTML);
			}

			// show container element
			c.show();

			$.getScript("http://twitter.com/javascripts/blogger.js");
			$.getScript("http://twitter.com/statuses/user_timeline/"+o.userName+".json?callback=twitterCallback2&count="+o.numTweets, function() {
				// remove preLoader from container element
				$(preLoaderHTML).remove();

				// remove timestamp and move to title of list item
				if (!o.showTimestamp) {
					tl.find("li").each(function() {
						var timestampHTML = $(this).children("a");
						var timestamp = timestampHTML.html();
						timestampHTML.remove();
						$(this).attr("title", timestamp);
					});
				}

				// show twitter list
				if (o.slideIn) {
					// a fix for the jQuery slide effect
					// Hat-tip: http://blog.pengoworks.com/index.cfm/2009/4/21/Fixing-jQuerys-slideDown-effect-ie-Jumpy-Animation
					var tlHeight = tl.data("originalHeight");

					// get the original height
					if (!tlHeight) {
						tlHeight = tl.show().height();
						tl.data("originalHeight", tlHeight);
						tl.hide().css({height: 0});
					}

					tl.show().animate({height: tlHeight}, o.slideDuration);
				}
				else {
					tl.show();
				}

				// add unique class to first list item
				tl.find("li:first").addClass("firstTweet");

				// add unique class to last list item
				tl.find("li:last").addClass("lastTweet");
			});
		});
	};
})(jQuery);

$(document).ready(function() {
$("#twitter").getTwitter({
		userName: "happideath",
		numTweets: 5,
		loaderText: "Loading tweets...",
		slideIn: true,
		slideDuration: 750,
		showHeading: true,
		headingText: "",
		showProfileLink: true,
		showTimestamp: true
	});
});

/****************************************************
 * jQuery RSS Plugin by fieeeld
 * version: 0.04 (2008/12/01)
 * @requires jQuery v1.2.6 or later
 *
 * Demo at: http://tpfields.xrea.jp/demo/js/sitefeeds/
 *
 ****************************************************/
$(function(){
	$.ajax({
		url: "http://happideath.com/proxy.php?url=http://ws.audioscrobbler.com/1.0/user/happideath/recenttracks.rss",//RSSファイル名
		async: true,
		cache: false,
		dataType:"xml",
		success: function(xml){
			$(xml).find('item').each(function(i){
                /* 初期設定で3件出力します。件数を変更は"i > 2"の部分を修正してください。
                   数値は"出力したい件数 - 1"を入力して下さい。*/
                if ( i > 4 ) {
                    return false;
                }
				var title = $(this).find('title').text();
				var url = $(this).find('link').text();
				//日付を整形
				var date = dateParse($(this).find('pubDate').text());
				//"2008/10/14  ほにゃらら" の形式で出力
				$('#feedList').append('<li class="list"><a href="'+url+'" style="color:#696768; font-weight:normal;">'+title+'</a></li>');
    		});
		}
	});
});

//dateParse: "2008/10/14" 形式
function dateParse(str){
    var objDate = new Date(str);
    var nowDate = new Date();
    //現在の日付との差を計算
    myDay = Math.floor((nowDate.getTime()-objDate.getTime()) / (1000*60*60*24)) + 1;
    //もし2週間以内なら"new!"マーク
    if (myDay < 0 ){
        var newMsg = '&nbsp;&nbsp;<span style="color:#ff6666; font-weight:bold;">new!</span>';
    } else {
        var newMsg = '';
    }
    var year = objDate.getFullYear();
    var month = objDate.getMonth() + 1;
    var date = objDate.getDate();
    if ( month < 10 ) { month = "0" + month; }
    if ( date < 10 ) { date = "0" + date; }
    str = year + '/' + month + '/' + date;
    rtnValue = new Array(2);
    rtnValue[0] = str;
    rtnValue[1] = newMsg;
    return rtnValue;
}

/*
 * 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
 *
 * jQuery 1.3.1
 * 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 = {
		// 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: '.btn, .allbtn img',
				groupSelector: '.btngroup',
				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);
			}

		},
		//外部リンクは別ウインドウを設定
		externalLink: function(options) {
			var c = $.extend({
				windowOpen:true,
				externalClass: 'externalLink',
				addIconSrc: ''
			}, options);
			var uri = new $.yuga.Uri(location.href);
			var e = $('a[href^="http://"]').not('a[href^="' + uri.schema + '://' + uri.host + '/' + '"]');
			if (c.windowOpen) {
				e.click(function(){
					window.open(this.href, '_blank');
					return false;
				});
			}
			if (c.addIconSrc) e.not(':has(img)').after($('<img src="'+c.addIconSrc+'" class="externalIcon" />'));
			e.addClass(c.externalClass);
		},
		//画像へ直リンクするとthickboxで表示(thickbox.js利用)
		thickbox: function() {
			try {
				tb_init('a[href$=".jpg"]:not(.thickbox, a[href*="?"]), a[href$=".gif"][href!="?"]:not(.thickbox, a[href*="?"]), a[href$=".png"][href!="?"]:not(.thickbox, a[href*="?"])');
			} catch(e) {
			}	
		},
		//ページ内リンクはするするスクロール
		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;
				}
			});
		},
		//タブ機能
		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);


/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		

		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

// Last.Fm Records 3.1

// Copyright 2008-2009 Jeroen Smeets
// http://jeroensmeets.net/

// Released under GPL license, with an additional remark:
// If you release this code as part of your own package,
// you have to change the API key. For more info, see
// http://www.last.fm/api/account

var lastFmRecords = (function() {

  // private, reachable through public setters
  var _user;
  var _period        = 'recenttracks';
  var _count         = 1;
  var _styletype     = ''; // can be highslide, lightbox
  var _refreshmin    = 3;
  var _placeholder   = 'lastfmrecords';
  var _defaultthumb  = 'http://cdn.last.fm/depth/catalogue/noimage/cover_85px.gif';
  var _debug         = false;
  var _gmt_offset    = '+9';

	/////////////
	// private //
	/////////////

	var _imgs_found    = [];

	// capitals to pretend these are constant
	var _LASTFM_APIKEY = '87e98318c3c1babb987d7e39f1eb9235';
	var _LASTFM_WS_URL = 'http://ws.audioscrobbler.com/2.0/';

	// last.fm added a default album image, and I don't like it
	var _LASTFM_DEFAULTIMG = 'http://cdn.last.fm/flatness/catalogue/noimage/2/default_album_medium.png';

  function _logStatus(text) {
    if (_debug)
      if ('undefined' != typeof console)
        if ('function' == typeof console.log)
          if ('object' == typeof text)
            console.log(text);
          else
            console.log('last.fm.records: ' + text);
  };

  function _getLastFMData() {
    var _method = false;
    switch(_period) {
    	case 'lovedtracks':
    		_method = 'user.getlovedtracks';
    		break;
    	case 'topalbums':
    		_method = 'user.gettopalbums';
    		break;
    	case 'overall':
    	case '7day':
    	case '3month':
    	case '6month':
    	case '12month':
    		_method = 'user.gettopalbums&period=' + _period;
    		break;
    	default:
    		_method = 'user.getrecenttracks';
    }
    jQuery.getJSON(
    	_LASTFM_WS_URL + '?method=' + _method + '&user=' + _user + '&api_key=' + _LASTFM_APIKEY + '&limit=50&format=json&callback=?',
    	lastFmRecords.processLastFmData
    );
  };

  function _getArtistData(_artistmbid) {
    jQuery.getJSON(
    	_LASTFM_WS_URL + '?method=artist.getinfo&mbid=' + _artistmbid + '&api_key=' + _LASTFM_APIKEY + '&format=json&callback=?',
    	lastFmRecords.processArtistData
    );
  };

	function _errorInLastFmResponse(data) {
		var _errorfound = false;
		var _errormsg;
		jQuery.each(data, function(tag, val) {
			if ('error' == tag) {
				_errorfound = true;
				_errormsg = ' (' + val + ')';
			}
			if (_errorfound && ('message' == tag)) {
				_errormsg = val + _errormsg;
			}
		});

		if (_errorfound) {
			_logStatus('last.fm reported error: ' + _errormsg);
		}

		return _errorfound;
	}

	function _findLargestImage(_imgarray) {
		// _imgarray is an array returned by last.fm that looks like

		// "image":[{"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"small"},
		// 	 			 {"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"medium"},
		// 	 			 {"#text":"http:\/\/images.amazon.com\/images\/P\/B00004YYTW.02._SCMZZZZZZZ_.jpg","size":"large"}
		// 	 			]

   	_biggestYet = false;

    jQuery.each(_imgarray, function(j, _img) {
     	if ('large' == _img.size) {
     		_biggestYet = _img['#text'];
     		// biggest found, get out of this loop
     		return false;
     	} else if ('medium' == _img.size) {
     		_biggestYet = _img['#text'];
     	} else if (('small' == _img.size) && ('' == _biggestYet)) {
     		_biggestYet = _img['#text'];
     	}
    });

		return (_LASTFM_DEFAULTIMG == _biggestYet) ? false : _biggestYet;
	}

  function _processLastFmData(data) {
  	// error in response?
		if (_errorInLastFmResponse(data)) {
			return false;
		}

		// get the cd data from the json
		switch(_period) {
      case 'recenttracks':
        data = data.recenttracks.track;
        break;
      case 'lovedtracks':
        data = data.lovedtracks.track;
        break;
      default:
        data = data.topalbums.album;
	  }

		if (!data) {
			_logStatus('No return data from Last.fm');
			return false;
		}

    // JNS 2009-07-30
    // thanks to my friend xample who only listened to 1 album last week,
    // i was able to fix this bug:
    // if only one result is found, data is not an array of albums/tracks but just one album/track.
		if (data.name && 'string' == typeof data.name) {
			data = [data];
		}
		jQuery.each(data, function(i, _json) {  
      if (i > _count) {
        return false;
      }
      var track = [];
      track.cdcover    = _json.image ? _findLargestImage(_json.image) : false;
      track.artistname = _json.artist['#text'] || _json.artist.name;
      track.artistmbid = _json.artist['mbid'];
      track.name       = _json.name;
      track.mbid       = _json.mbid;
      track.url        = _json.url;
			if ('recenttracks' == _period) {
				// aaargh! json has changed!
				if (_json['@attr'] && ('true' == _json['@attr'].nowplaying)) {
      		track.time     = 'listening now';
      	} else {
      		track.time     = ('undefined' == typeof _json.date)
      		               ? 'some time'
      		               : _getTimeAgo(_json.date['#text'], _gmt_offset);
      	}
      } else {
      	track.time = '';
      }

      _showCover(i, track);
    });

    if (_refreshmin > 0) {
      setTimeout('lastFmRecords.refreshCovers();', _refreshmin * 60000);
    }
  };

  function _showCover(_id, _track) {
  	// store last.fm data about this track in (well, near, thanks to jQuery) the image
  	jQuery.each(_track, function(tag, val) {
  		jQuery('#lastfmcover' + _id).data(tag, val);
  	});
  	
    // always set title of image
    var _title = _track.name + ' by ' + _track.artistname;
    if ('' != _track.time) {
    	_title += ' (' + _track.time + ')';
    }
    jQuery('#lastfmcover' + _id).attr('title', _title);
    if ('' == _track.cdcover) {
			// no cover for cd, do we have an image for the artist?
			if (_imgs_found[_track.artistmbid] && ('*' != _imgs_found[_track.artistmbid])) {
				// yes, use that url
				jQuery('#lastfmcover' + _id).attr('src', _imgs_found[_track.artistmbid]);
			} else {
				// nope, let's ask last.fm.
				if ('*' != _imgs_found[_track.artistmbid]) {
				 	_logStatus('cover for ' + _track.name + ' not found, trying to find image of artist ' + _track.artistname);
				 	// Setting a star to know we're already looking for this one
					_imgs_found[_track.artistmbid] = '*';
					_getArtistData(_track.artistmbid);
				}

     		jQuery('#lastfmcover' + _id).attr('src', _defaultthumb);
     		jQuery('#lastfmcover' + _id).addClass(_track.artistmbid);
     		
     	}
    } else {
      // point src and href of parent a to the image
      // and make link clickable
      jQuery('#lastfmcover' + _id).attr('src', _track.cdcover).parent('a').attr('href', _track.url).unbind('click', lastFmRecords.dontFollowLink);
    }
  };

  function _processArtistData(data) {
  	// error in response?
		if (_errorInLastFmResponse(data)) {
			return false;
		}

    // data = data.artist;
    jQuery.each(data, function(i, _json) {
    	_imgurl = _findLargestImage(_json.image);
    	_mbid   = _json.mbid;
    	// find images that need to be changed
    	jQuery('.' + _mbid).each( function() {
    	  // point src and href of parent a to the image
    	  // and make link clickable
    	  jQuery(this).attr('src', _imgurl).removeClass(_mbid).parent('a').attr('href', _json.url).unbind('click', lastFmRecords.dontFollowLink);
    	});

			// remember we have an url for this artist
			_imgs_found[_mbid] = _imgurl;

    	// stop looping
    	return false;
    });
  };

  // this code is just too complex, I know. Suggestions?
  function _getTimeAgo(_t, gmt_offset) {
    // _logStatus('trying to figure out how long ago ' + _t + ' is, in your timezone ' + gmt_offset);
    
    // difference between then and now
    var _diff = new Date() - new Date(_t);
    // take into account the timezone difference
    _diff = _diff - (gmt_offset * 60000 * 60);

    // _logStatus(_diff);

    var _d = [];
    // how many years in the difference? not many, I hope ;-)
    _d.ye = parseInt(_diff / (1000 * 60 * 60 * 24 * 365));
    _d.da = parseInt(_diff / (1000 * 60 * 60 * 24)) - (_d.ye * 365);
    _d.ho = parseInt(_diff / (1000 * 60 * 60)) - (_d.ye * 365 * 24) - (_d.da * 24);
    _d.mi = parseInt(_diff / (1000 * 60)) - (_d.ye * 365 * 24 * 60) - (_d.da * 24 * 60) - (_d.ho * 60);

    var _meantime = [];
    if (_d.ye > 0) { _meantime.push(_d.ye + ' year' + _getPluralS(_d.ye)); }
    if (_d.da > 0) { _meantime.push(_d.da + ' day' + _getPluralS(_d.da)); }
    if (_d.ho > 0) { _meantime.push(_d.ho + ' hour' + _getPluralS(_d.ho)); }
    if (_d.mi > 0) { _meantime.push(_d.mi + ' minute' + _getPluralS(_d.mi)) };

    _logStatus(_meantime);

    // TODO: replace last comma with 'and'
    return _meantime.join(', ') + ' ago';
  };

  function _getPluralS(_c) {
    return (1 == _c) ? '' : 's';
  };

  function _handleError(_msg, _url, _linenumber) {
  	var _err  = [];
  	_err.msg  = _msg;
  	_err.url  = _url;
  	_err.line = _linenumber;
  	_err.ref  = document.location.href;
  	_logStatus(_err);

  	// we're always happy
  	return true;
  };

	////////////
	// public //
	////////////

  return {
    
    addStyle: function(styletype) {
      _logStatus('function addStyle not supported yet');
    },

    setUser: function(orUsername) {
      // TODO: validation
      _user = orUsername;
    },

    setPeriod: function(orPeriod) {
      // TODO: just todo ;-)
      _period = orPeriod;
    },

    setCount: function(orCount) {
      var _pI = parseInt(orCount);
      if (_pI > 0) {
        _count = _pI;
      }
    },

    setStyle: function(orStyle) {
      // TODO: validation
      _styletype = orStyle;
    },

    setPlaceholder: function(orPlaceholder) {
      // TODO: validate
      _placeholder = orPlaceholder;
    },

    setDefaultThumb: function(orDefaultThumb) {
    	// TODO: validate
    	_defaultthumb = orDefaultThumb;
    },

    setRefreshMinutes: function(orRefresh) {
      var _pI = parseInt(orRefresh);
      if (_pI > 0) {
        _refreshmin = _pI;
      }
    },

    setTimeOffset: function(orOffset) {
      _gmt_offset = parseInt(orOffset);
    },

		debug: function() {
			_debug = true;

			// send javascript errors to error handler
			// to catch javascript errors that could make js stop
			jQuery(window).bind('error', lastFmRecords.err);
			_logStatus('registering error handler');
		},

		err: function(msg, url, linenumber) {
			_handleError(msg, url, linenumber);
		},

		dontFollowLink: function() {
			// made it a function so I can unbind it
			return false;
		},

    init: function(_settings) {
      _logStatus('initializing');

			if (_settings.placeholder)  { this.setPlaceholder(_settings.placeholder); }

      // is a string [lastfmrecords|period|count] found on the page?
      var _regex = /\[lastfmrecords\|.+\|.+\]/;
      // get the strings in it
      var _match = document.body.innerHTML.match(_regex);
      if (_match) {
        // and put the div where the cd covers should be
        document.body.innerHTML = document.body.innerHTML.replace(_regex, '<div id=' + _placeholder + '></div>');

        // change settings based on _match
        _match = _match[0].replace('[', '').replace(']', '').split('|');
        _logStatus('Hey, that\'s nice, this site is using the [lastfmrecords|period|count] way of showing covers.');
        if (_match[1]) {
          _settings.period = _match[1];
          _logStatus('Changing period to ' + _match[1]);
        }
        if (_match[2]) {
          _settings.count = _match[2];
          _logStatus('Changing number of covers to ' + _match[2]);
        }
      }

      if (jQuery("dd#" + _placeholder).length < 1) {
        _logStatus('error: placeholder for cd covers not found');
        return false;
      }

			if (_settings.username)     { this.setUser(_settings.username) }
			if (_settings.period)       { this.setPeriod(_settings.period); }
			if (_settings.defaultthumb) { this.setDefaultThumb(_settings.defaultthumb); }
			if (_settings.count)        { this.setCount(_settings.count); }
			if (_settings.refresh)      { this.setRefreshMinutes(_settings.refresh); }
			if (_settings.offset)       { this.setTimeOffset(_settings.offset); }
			if (_settings.styletype)    { this.setStyle(_settings.styletype); }

			// no need to refresh when period isn't Recent tracks
			if ('recenttracks' != _period) {
				_refreshmin = 0;
			}

      // add an ul to placeholder div
      var _ol = jQuery("<ol></ol>").appendTo("dd#" + _placeholder);
      if (!_ol) {
        _logStatus('error: placeholder for cd covers not found');
      }

      // add temporary cd covers
      _logStatus('adding temporary cd covers');
      var _img, _li;
      for (var i = 0; i < _count; i++) {
        _li  = jQuery('<li></li>').attr('style', 'display: inline;');

        _a   = jQuery('<a></a>').bind('click', lastFmRecords.dontFollowLink).attr('href', '').appendTo(_li);
        // highslide?
        if ('highslide' == _styletype)  {
          _a.click( function() { return hs.expand(this); });
        }

        if ('lightbox' == _styletype) {
          _a.attr('rel', 'lightbox');
        }

        _img = jQuery('<img></img>').attr('src', _defaultthumb).attr('id', 'lastfmcover' + i).appendTo(_a);

        _li.appendTo(_ol);
      }

			_getLastFMData();
    },

    refreshCovers: function() {
      _getLastFMData();
    },

    processLastFmData: function(data) {
      // handle it internally
      _processLastFmData(data);
    },

    processArtistData: function(data) {
      // handle it internally
      _processArtistData(data);
    }
  };

})();

    var _config = { username: 'happideath',
                    placeholder: 'lastfmrecords',
                    defaultthumb: 'http://cdn.last.fm/depth/catalogue/noimage/cover_85px.gif',
                    count: 1,
                    period: 'recenttracks',
                    refresh: 3,
                    offset: +9
                  };
    jQuery(document).ready( function() {
      lastFmRecords.debug();
      lastFmRecords.init(_config);
    });
	
// vim: set expandtab tabstop=2 shiftwidth=2 foldmethod=marker:
// +----------------------------------------------------------+
// |   __             _                               _
// |  / _| __ ___   _(_) ___ ___  _ __     __ _ _ __ (_)
// | | |_ / _` \ \ / / |/ __/ _ \| '_ \   / _` | '_ \| |
// | |  _| (_| |\ V /| | (_| (_) | | | | | (_| | |_) | |
// | |_|  \__,_| \_/ |_|\___\___/|_| |_|  \__,_| .__/|_|
// |                                           |_|
// | 
// | Copyright (c) 2006 Favicon API 
// |                    (http://favicon.aruko.net/) - aruko.net
// |                                            version - 0.0.3
// +----------------------------------------------------------+
// |  * This script is freely distributable under 
// |    the terms of an MIT-style license.
// |    http://favicon.aruko.net/dl/license.txt
// +----------------------------------------------------------+
// 参考 : http://shinobibloglab.blog.shinobi.jp/Entry/181/

var fapi_conf = [
  // ---------------------------------------------------------+
  // Please change the following. 
  { 
    name: 'favicon_m',
    size: 'm',
    def: 'e',
    margin: '0 0 0 3px',
    padding: '0 0 2px 19px',
    background_color: '',
    background_position: '1px 1px'
  },
  { 
    name: 'favicon',
    size: 's',
    def: 'e',
    margin: '0 0 0 2px',
    padding: '0 0 2px 19px',
    background_color: '',
    background_position: 'left center'
  }
  // ---------------------------------------------------------+ 
]

var fapi = { 

  /* Do not edit below */
  addE: function(obj, type, listener) {
    if (obj.addEventListener) // Std DOM Events
      obj.addEventListener(type, listener, false);
    else if (obj.attachEvent) // IE
      obj.attachEvent(
        'on' + type,
        function() { listener( {
          type            : window.event.type,
          target          : window.event.srcElement,
          currentTarget   : obj,
          clientX         : window.event.clientX,
          clientY         : window.event.clientY,
          pageY           : document.body.scrollTop + window.event.clientY,
          shiftKey        : window.event.shiftKey,
          stopPropagation : function() { window.event.cancelBubble = true }
        } ) }
      );
  },
  init: function() {
    if (!document.getElementsByTagName) return false;
    var lists = document.getElementsByTagName("a");
    var num = lists.length; 
    var m_num = fapi_conf.length;
    for (var i=0; i < num; i++) {
      for(var j=0; j<m_num; j++ ) {
        if (lists[i].className.match(fapi_conf[j].name)) {
          fapi.changeLink(lists[i],j);
        } 
      } 
    }
  }, 
  changeLink: function(e,n) {
    var url = e.href; 
		var domain = url.match(/(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/);
		domain = RegExp.$2;
    var es = e.style; 
    var bk = '';

    if(fapi_conf[n].background_color != '') { 
      bk += fapi_conf[n].background_color + ' ';
    } 
    bk += 'url("http://www.google.com/s2/favicons?domain='+
         domain + 
         '") no-repeat'; 

    es.margin = fapi_conf[n].margin;
    es.padding = fapi_conf[n].padding; 
    es.background = bk; 
    es.backgroundPosition = fapi_conf[n].background_position; 

    return true; 
  }

} 

fapi.addE(window, 'load', fapi.init);


