$(function () {
    $("span.wikitip").click(function(){
    	var target = this;
    	var keyword = $(target).text();
		if (mw_cache[keyword]) {
			mw_show(target, keyword);
			return;
		}
		$(target).css({
			'background-image': 'url(wikitip/loading.gif)',
			'background-color': '#007BA3',
			'color': '#FFF'
		});
		$.getJSON("http://ja.wikipedia.org/w/api.php?action=parse&prop=text&format=json&page=" + encodeURIComponent(keyword) + "&callback=?",
			function(data){
				var str = !data.failed ? data.parse.text["*"] : '<p>(要約データの取得に失敗しました)</p>';
				mw_cache[keyword] = mw_getSummary(str);
				mw_show(target, keyword);
				$(target).css({
					'background-image': '',
					'background-color': '',
					'color': ''
				});
			});
    });
});

// グローバル変数
var mw_cache = {};

// Wikiの記事テキストを受け取って、要約を返す
function mw_getSummary(content){
	content = content.replace(/\<img\ .*?\>|\<a\ .*?\>|<\/a\>/g, "");
	var summary = "";
	$('<div>'+content+'</div>').children().each(function (i){
		if (jQuery.trim(this.textContent || this.innerHTML || "") == "")
			return true;
		if (this.tagName == "P" || this.tagName == "UL" || this.tagName == "OL")
			summary += "<"+this.tagName+">"+this.innerHTML+"</"+this.tagName+">";
		if (this.tagName == "H1" || this.tagName == "H2")
			return false;
	});
	return summary || "(概要はありません)";
}

// ツールチップ表示
function mw_show(target, keyword){
	var uri = 'http://ja.wikipedia.org/wiki/'+keyword;
	var source = '出典:フリー百科事典『ウィキペディア』';
	var license = 'available under the GNU Free Documentation License';
	var p = $(target).absPos();
	$(
		'<div class="wikitip">'
			+'<h6>'+keyword+'</h6>'
			+mw_cache[keyword]
			+'<p align="center"><a href="'+uri+'" target="_blank">'+source+'</a></p>'
			+'<div>'+license+'</div>'
		+'</div>'
	)
	.css({
		left: (p.left-3)+'px',
		top: (p.top-1)+'px'
	})
	.click(function(){
		$(this).fadeOut(100, function(){
			$(this).remove();
		});
	})
	.insertAfter(target);
}

// 最初の要素の絶対座標を返す (標準のpositionとは若干異なる)
jQuery.fn.absPos = function(){
	var p = {left:0, top:0}, elm;
	if (elm = this[0]){
		while (elm && elm.nodeName != "BODY") {
			p.left += elm.offsetLeft;
			p.top += elm.offsetTop;
			elm = elm.offsetParent;
		}
		return p;
	}
	return null;
}

/* Copyright 2009 CogniTom Academic Design & Tsutomu Kawamura
 * http://www.cognitom.com/
 * office@cognitom.com
 * ------------------------------------------------------------------
 *
 * MediaWiki Tips for jQuery
 *
 * - version 1.0.0
 * - release 2009.11.3
 * 
 * ------------------------------------------------------------------
 * 本スクリプトは、Apache License Version 2.0に基づいてライセンスされます。
 * あなたがこのファイルを使用するためには、本ライセンスに従わなければなりません。
 * 本ライセンスのコピーは下記の場所から入手できます。
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * 適用される法律または書面での同意によって命じられない限り、本ライセンスに基づい
 * て頒布されるソフトウェアは、明示黙示を問わず、いかなる保証も条件もなしに「現状
 * のまま」頒布されます。本ライセンスでの権利と制限を規定した文言については、本ラ
 * イセンスを参照して下さい。
 * ------------------------------------------------------------------
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */