
$(function(){
	
	// pre class="run" タグにサンプルコードの実行ボタン[>>Run]の追加
	$("pre.run").append('<input type="submit" value="&raquo; Run"/>')
		.find("input").click(function(){
			var code = $(this).parent().text();
			eval(code);
		}).end();
	
	// div class="dom" タグの中身を pre タグの中にソースとして展開する
	$("div.dom").each(function(){
		var html = $(this).html();
		html = html.replace(/\n\t{1,2}/g, "\n");
		html = html.replace(new RegExp('<', 'g'), '&lt;');
		html = html.replace(new RegExp('>', 'g'), '&gt;');
		$(this).after('<p>次の段落の内容は $("#' + $(this).attr('id') + '") で取得できます．<\/p>'
			+ '<pre class="dom">' + html + '<\/pre>');
	});
	
	// H1～H6タグより目次を生成する
	var idcount = 1;
	var toc = '';
	var currentlevel = 0;
	$(".head").each(function(){
		this.id = "toc_" + idcount;
		idcount++;
		var level = 0;
		if(this.nodeName.toLowerCase() == "h1") {
			level = 1;
		} else if(this.nodeName.toLowerCase() == "h2") {
			level = 2;
		} else if(this.nodeName.toLowerCase() == "h3") {
			level = 3;
		} else if(this.nodeName.toLowerCase() == "h4") {
			level = 4;
		} else if(this.nodeName.toLowerCase() == "h5") {
			level = 5;
		} else if(this.nodeName.toLowerCase() == "h6") {
			level = 6;
		}
		while(currentlevel < level) {
			toc += "<ol>";
			currentlevel++;
		}
		while(currentlevel > level) {
			toc += "<\/ol>";
			currentlevel--;
		}
		toc += '<li><a href="" class="toc_jump" jumpto="' + this.id + '">' + $(this).html() + "<\/a><\/li>\n";
		
		$(this).append('<a href="#toc" class="jump_toc">目次<\/a>');
	});
	while(currentlevel > 0) {
		toc += "<\/ol>";
		currentlevel--;
	}
	$("#toc").html(toc);
	
	// 目次から各Hタグ，およびその逆のリンクのジャンプ処理
	$("a.toc_jump").click(function(){
		$("#" + $(this).attr("jumpto")).ScrollTo(300);
		return false;
	});
	$("a.jump_toc").click(function(){
		$("#toc_header").ScrollTo(300);
		return false;
	});
});

// jqueryオブジェクトの中身をダンプする関数
function jquery_dump($obj) {
	var dumphtml = [];
	if($.browser.msie) {
		for(var i = 0; i < $obj.length; i++) {
			dumphtml.push('[' + i + '] ');
			dumphtml.push($obj[i].outerHTML.replace(/^[\r\n\t]+/, ''));
			dumphtml.push("\n");
		}
	} else {
		for(var i = 0; i < $obj.length; i++) {
			dumphtml.push('[' + i + '] '
				+ '<' + $obj[i].nodeName.toLowerCase());
			for(var j = 0; j < $obj[i].attributes.length; j++) {
				dumphtml.push(' ' + $obj[i].attributes[j].nodeName + '="' 
					+ $obj[i].attributes[j].nodeValue + '"');
			}
			dumphtml.push('>' + $obj[i].innerHTML);
			dumphtml.push('<\/' + $obj[i].nodeName.toLowerCase() + '>');
			dumphtml.push("\n");
		}
	}
	alert(dumphtml.join(''));
}

