﻿function plog(msg) {
	document.write('<p>'+msg+'</p>');
}

function getElementsByClass(element, class_name) {
	var allPageTags = element.getElementsByTagName("*"); 
	var an_array = new Array();
	for (var i=0; i<allPageTags.length; i++) { 
		if (allPageTags[i].className==class_name) {
			an_array.push(allPageTags[i]);
		}
	}
	return an_array;
}

function postCountTBA(id){
	var hs_search = new RegExp('\\W','gi');
	var hs_id = id.replace(hs_search,"_");
	id = hs_id;
	if (hstb[id]){
		if (hstb[id] === 1) {
			return "Trackback (1)";
		} else {
			return "Trackbacks (" + hstb[id] + ")";
		}
	} else {
	 return "Trackback";
 }
}

function setupHaloScan() {
	// Safari + XHTML だと、document.body が無いようだ。
	var topicframes = getElementsByClass(document.getElementsByTagName("body")[0], 'topic-frame');
	for (var i=0; i< topicframes.length; i++) {
		var topicid = getElementsByClass(topicframes[i], "topic-date")[0].getElementsByTagName("a")[0].getAttribute("id");
		
		var a_tb = document.createElement("a");
		a_tb.setAttribute("href", "javascript:HaloScanTB('"+topicid+"');");
		a_tb.setAttribute("target", "_self");
		var tb_text = postCountTBA(topicid);
		a_tb.appendChild(document.createTextNode(tb_text));
			
		var a_postcomment = document.createElement("a");
		a_postcomment.setAttribute("href", "javascript:HaloScan('"+topicid+"');");
		a_postcomment.setAttribute("target", "_self");
		var postcomment_text = postCountA(topicid);
		a_postcomment.appendChild(document.createTextNode(postcomment_text));
		
		delimtext = document.createTextNode(" | ");
		
		var hs_elem = document.createElement("p");
		hs_elem.setAttribute("class", "haloscan-comment");
		hs_elem.appendChild(a_tb);
		hs_elem.appendChild(delimtext);
		hs_elem.appendChild(a_postcomment);
		
		var contentnode = getElementsByClass(topicframes[i], "topic-content")[0];
		topicframes[i].insertBefore(hs_elem, contentnode);
	}
	return true;
}
window.addEventListener("load", setupHaloScan, true);