/*	http://facet.cocolog-nifty.com/divers/foldSidebar02c.js
	made by facet, http://facet.cocolog-nifty.com/divers/
	this ver.	02c07	@ 2004-10-13
			02c00	@ 2004-09-28
	original ver.	02a	@ 2004-03-14
*/

// ---- user variables ----
var foldMark = "-";
var foldTitle = "close";
var unfoldMark = "+";
var unfoldTitle = "open";
var switchStyle = "";
var labelStyle = "";
var foldBroadly = false;

var counterPrefix = "(";
var counterPostfix = ")";
var counterStyle = "letter-spacing:normal;";
var countBroadly = false;

// ---- system variables ----
var headingTagName = "h2";

var pattern = ".";
var switchTagName = "button";
var scopeIds = new Array("left", "right");

var counterTagName = "span";
var counterClassName = "counter";

function getTextContent(e){
	if (!e) return '';
	if (e.textContent) return e.textContent;
	if (e.innerText) return e.innerText;
	var t = _getInnerText(e);
	return (t) ? t : '';
}
function makeSwitchesBy(pattern) {
	if (!pattern) return;
	var args = new Array();
	args["re4NoSwitch"]=getRegExp4NoSwitch(pattern);
	args["pattern"] = getPositivePattern(getGivenPattern(pattern));
	for (var i = 0; i < scopeIds.length; i++) {
		var scopeElement = document.getElementById(scopeIds[i]);
		if (!scopeElement) continue;
		args["scopeId"] = scopeIds[i];
		appendSwitchesBy(args);
	}
}
function appendSwitchesBy(args) {
	if (!args["scopeId"]) return false;
	var scopeElement = document.getElementById(args["scopeId"]);

	if (!args["pattern"]) args["pattern"] = ".";	// if no pattern, append switch to all
	var regExp = new RegExp(args["pattern"], "i");

	var headingTagName = "h2";
	var h2s = scopeElement.getElementsByTagName(headingTagName);

	for (var i = 0; i < h2s.length; i++) {
		var h2 = scopeElement.getElementsByTagName(headingTagName).item(i);
		if (hasAlreadySwitch2Fold(h2)) continue;
		if (isCommentNode(h2.firstChild)) continue;
		var t = getTextContent(h2);
		if (!t||consistsOfOnlyKuuhaku(t)) continue;
		if (!t.match(regExp)) continue;
		if (args["re4NoSwitch"]&&t.match(args["re4NoSwitch"])) continue;

		// make switch and label
		if (h2.innerHTML) {
			// get headingChildNodes, create switch and append them into a new lable
			var oldInnerHTML = h2.innerHTML;
			switchTagName.toLowerCase();
			var switchStyleAttr = "";
			if (switchStyle) switchStyleAttr = ' style="' + switchStyle + '"';
			var labelStyleAttr = "";
			if (labelStyle) labelStyleAttr = ' style="' + labelStyle + '"';
			var newInnerHTML =
				'<' + switchTagName +
				' class="switch"' +
				' title=' + foldTitle +
				' name="switch-' + i + '"' +
				' onclick="switchMode(this)"' +
				' onmouseover="actOnMouseOver(this)"' +
				' onmouseout="actOnMouseOut(this)"' +
				switchStyleAttr +
				'>' +
				foldMark +
				'</' + switchTagName + '>' +
				'<label' +
				' class= "switch-label"' +
				' for="switch-' + i + '"' +
				labelStyleAttr +
				'>' +
				oldInnerHTML +
				'</label>';
			h2.innerHTML = newInnerHTML;
		} else {
			// append the all childNodes into a new labelElement
			var labelElement = document.createElement("label");
			var headingChildNodes = h2.childNodes;
			for (var k = 0; k < headingChildNodes.length; k++) {
				labelElement.appendChild(headingChildNodes[k]);
			}

			// - create switch and append it into heading
			var switchElement = document.createElement(switchTagName);
			h2.appendChild(switchElement);

			// append label into heading
			h2.appendChild(labelElement);

			h2.onclick = function() { switchMode(this.firstChild); };

			// - set attributes
			switchElement.className="switch";
			switchElement.title=foldTitle;
			switchElement.name="switch-" + i;
			switchElement.onclick = function() { switchMode(this); };
			_setAttribute(switchElement, "style", switchStyle);
			switchElement.onmouseover=function() {actOnMouseOver(this)};
			switchElement.onmouseout=function() {actOnMouseOut(this)};
			
			labelElement.className="switch-label";
			_setAttribute(labelElement, "for", "switch-" + i);
			_setAttribute(labelElement, "style", labelStyle);
		}
		h2.className="unfolded";	
	}
}
function getRegExp4NoSwitch(pattern){
	return getRegExp2Unfold(pattern);
}
function hasAlreadySwitch2Fold(h2){
	return (h2.className&&h2.className.indexOf('folded')>-1||h2.firstChild&&h2.firstChild.nodeName&&h2.firstChild.nodeName==switchTagName);
}
function consistsOfOnlyKuuhaku(str){
	return (str.match(/^[　\s]+$/));
}
function actOnMouseOver(e){
}
function actOnMouseOut(e){
}

function foldContentsBy(pattern,continued) {
	if (!continued) eraseCookiedKey4NonExistingList();
	if (!pattern) pattern='.';
	var args = new Array();
	args["cookiedPattern"]=getCookiedPattern2FoldSidebar();
	pattern=getGivenPattern(pattern);
	args["re2Fold"]=getRegExp2Fold(pattern);
	args["re2Unfold"]=getRegExp2Unfold(pattern);
		
	for (var i = 0; i < scopeIds.length; i++) {
		var scopeElement = document.getElementById(scopeIds[i]);
		if (!scopeElement) continue;
		args["scopeId"] = scopeIds[i];
		switchModesBy(args);
	}
}
function switchModesBy(args) {
	if (!args["scopeId"]) return false;
	var scopeElement = document.getElementById(args["scopeId"]);
	if (!scopeElement) return;

	var h2s = scopeElement.getElementsByTagName("h2");
	for (var i = 0; i < h2s.length; i++) {
		var h2 = h2s[i];
		if (!h2.firstChild||isCommentNode(h2.firstChild)) continue;
		var switchElement = getSwitchElement(h2);
		if (!switchElement) continue;
		var headingText = getSidebarContentTitle(h2);
		if (!headingText) continue;
		var action='unfold';
		var t=escapeRegExpChars(headingText);
		var cookiedState=getCookiedState(t,args["cookiedPattern"]);
		if (cookiedState){
			if (h2.className==cookiedState) continue;
			action=cookiedState.replace(/ed$/,'');
		} else {
			if (args["re2Fold"]&&t.match(args["re2Fold"])) {
				if (h2.className&&h2.className=='folded') continue;
				action='fold';
			}
			if (args["re2Unfold"]&&t.match(args["re2Unfold"])) {
				if (h2.className&&h2.className=='unfolded') continue;
				action='unfold';
			}
		}
		switchMode(switchElement,action);
	}
}
function getCookiedState(t,p){
	if (!t) return null;
	if (!p) p=getCookiedPattern2FoldSidebar();
	if (!p) return null;
	var Key=p.split('|');
	for (var i=0,key; (key=Key[i]); i++){
		var folded=(key.charAt(0)!='!');
		if (!folded) key=key.substring(1);
		if (key==t) return (folded)?'folded':'unfolded';
	}
	return null;
}
function getGivenPattern(p){
	p=p.replace(/\|/g,'DUMMYBRVBAR');
	return escapeRegExpChars(p).replace(/DUMMYBRVBAR/g,'|');
}
function getCookiedPattern2FoldSidebar(){
	return unescape(readCookie('pattern2FoldSidebar'));
}
function getRegExp2Fold(p){
	return new RegExp(getPositivePattern(p), 'i');
}
function getPositivePattern(p){
	var R=new Array();
	var Key=p.split('|');
	for (var i=0,key; (key=Key[i]); i++){
		if (key.indexOf('!')!=0) R.push(key);
	}
	if (R.length==0) return null;
	return R.join('|');
}
function getRegExp2Unfold(p){
	return new RegExp(getNegativePattern(p), 'i');
}
function getNegativePattern(p){
	var R=new Array();
	var Key=p.split('|');
	for (var i=0,key; (key=Key[i]); i++){
		if (key.indexOf('!')==0) R.push(key.substring(1));
	}
	if (R.length==0) return null;
	return R.join('|');
}
function isCommentNode(e){
	if (!e){return false;}
	return (e.nodeType == 8);
}
function getSwitchElement(h2){
	var S = h2.getElementsByTagName(switchTagName);
	if (S.length==0){return false;}
	for (var j = 0,s; (s = S[j]); j++) {
		var cls = _getAttribute(s, "class");
		if (cls && cls == "switch") {
			return s;
		}
	}
	return false;
}

function switchMode(switchElement, action) {
	var h2 = switchElement.parentNode;
	var ul = _getNextElement(h2);
	var oldDisplayMode = (ul.style&&ul.style.display) ? ul.style.display : "";
	var newDisplayMode = (oldDisplayMode == "none") ? "" : "none";
	if (action) newDisplayMode = (action=='fold') ? 'none' : '';
	
	// switch style.display
	var e = ul;
	while (e) {
		if (!e||!e.nodeName||e.nodeName.match(/h2/i)) break;
		e.style.display = newDisplayMode;
		if (!foldBroadly) break;
		e = _getNextElement(e);
	}
	
	// switch marker
	var newMarker = (newDisplayMode == "none") ? unfoldMark : foldMark;
	if (document.createTextNode) {
		switchElement.firstChild.nodeValue = newMarker;
	}
	
	// switch attributes
	switchElement.title = (newDisplayMode == "none") ? unfoldTitle : foldTitle;
	h2.className = (newDisplayMode == "none") ? "folded" : "unfolded";
	
	// handle cookie
	var headingText = getSidebarContentTitle(h2);
	setCookiePattern2FoldSidebar(headingText,h2.className);
}
function getSidebarContentTitle(h2){
	var label=h2.getElementsByTagName('label')[0];
	return (label) ? getTextContent(label) : '';
}
function setCookiePattern2FoldSidebar(headingText,newClass,action){
	if (!headingText) return;
	var t=escapeRegExpChars(headingText);
	var p=getCookiedPattern2FoldSidebar();
	if (!p) {
		if (newClass!='folded') t='!'+t;
		p=t;
	} else {
		var Key=p.split('|');
		var matched=false;
		for (var i=0,key; (key=Key[i]); i++){
			if (key.replace('!','')==t) {
				if (key.charAt(0)=='!'&&newClass=='folded') Key[i]=key.replace('!','');
				if (key.charAt(0)!='!'&&newClass!='folded') Key[i]='!'+key;
				matched=true;
				break;
			}
		}
		if (!matched) {
			if (newClass!='folded') t='!'+t;
			Key.push(t);
		}
		p=Key.join('|');
		
	}
	createCookiePattern2FoldSidebar(p);
}
var reRegExpChars2Escape=new RegExp('[-~`@$%^*()_+=|{}:"<>,?/\']', 'g');
function escapeRegExpChars(t){
	t=t.replace(/\\/g,'.');
	t=t.replace(/\[/g,'.');
	t=t.replace(/\]/g,'.');
	t=t.replace(reRegExpChars2Escape,'.');
	return t;
}
function eraseCookiedKey4NonExistingList(){
	var ScopeId=new Array('left','right');
	var T=new Array();
	for (var i=0,id; (scopeId=ScopeId[i]); i++){
		var scope=document.getElementById(scopeId);
		if (!scope) continue;
		var H2=scope.getElementsByTagName('h2');
		for (var j=0,h2; (h2=H2[j]); j++){
			var t=getSidebarContentTitle(h2);
			if (t) T.push('^'+escapeRegExpChars(t)+'$');
		}
	}
	var allTitlePattern=T.join('|');
	
	var cookiedPattern=getCookiedPattern2FoldSidebar();
	cookiedPattern=cookiedPattern.replace(/\|\|+/g,'|')
	var R=new Array();
	if (cookiedPattern) {
		var Key=cookiedPattern.split('|');
		for (var i=0,key; (key=Key[i]); i++){
			var t=key;
			if (key.indexOf('!')==0) t=key.substring(1);
			t='^'+t+'$';
			if (allTitlePattern.indexOf(t)>-1) R.push(key);
		}
	}
	if (R.length>0) createCookiePattern2FoldSidebar(R.join('|'));
}
function createCookiePattern2FoldSidebar(p){
	createCookie('pattern2FoldSidebar',escape(p),30);
}

/*	The functions createCookie() & readCookie() below are from:
	http://yujiro.dyndns.org/blog/koikikukan/archives/2004/09/13-235641.php
*/
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

/*	The function eraseCookie(name) below is from:
	http://www.quirksmode.org/js/cookies.html
*/
function eraseCookie(name)
{
	createCookie(name,"",-1);
}

function countItemsBy(pattern) {
	if (!pattern) return;
	var reNoCount = getRegExpNoCount(pattern);
	pattern=getPositivePattern(getGivenPattern(pattern));
	var regExp = new RegExp(pattern, "i");

	for (var i = 0; i < scopeIds.length; i++) {
		var scopeElement = document.getElementById(scopeIds[i]);
		if (!scopeElement) continue;

		var h2s = scopeElement.getElementsByTagName(headingTagName);
		for (var j = 0; j < h2s.length; j++) {
			var h2 = h2s[j];
			var t = getSidebarContentTitle(h2);
			if (!t||!t.match(regExp)) continue;
			if (reNoCount&&t.match(reNoCount)) continue;
			
			var n = getNumOfItems(h2);
			var span=h2.getElementsByTagName('span')[0];
			if (span&&span.className&&span.className==counterClassName) {
				var m=getTextContent(span).replace(counterPrefix,'').replace(counterPostfix,'');
				if (m==n) continue;
				else h2.removeChild(span);
			}
			if(h2.innerHTML) {
				var oldInnerHTML = h2.innerHTML;
				var counterStyleAttr = "";
				if (counterStyle) counterStyleAttr = ' style="' + counterStyle + '"';
				var newInnerHTML =
					oldInnerHTML +
					'<' + counterTagName +
					' class="' + counterClassName + '"' +
					counterStyleAttr +
					'>' +
					counterPrefix + n + counterPostfix +
					'</' + counterTagName + '>';
				h2.innerHTML = newInnerHTML;
			} else {
				var counterElement = document.createElement(counterTagName);
				counterElement.appendChild(document.createTextNode(counterPrefix));
				counterElement.appendChild(document.createTextNode(n));
				counterElement.appendChild(document.createTextNode(counterPostfix));
				h2.appendChild(counterElement);
				counterElement.className=counterClassName;
				if (counterStyle) {
					_setAttribute(counterElement, "style", counterStyle);
				}
			}
		}
	}
}
function getRegExpNoCount(pattern){
	return getRegExp2Unfold(pattern);
}
function getNumOfItems(h2) {
	var n = 0;
	var targetElement = _getNextElement(h2);
	while(targetElement) {
		if (targetElement.nodeName&&targetElement.nodeName.match(/H2/i)) break;

		var LIs = targetElement.getElementsByTagName("li");
		var dn = LIs.length;
		if (dn == 0 && countBroadly) dn = 1;
		n += dn;
		targetElement = _getNextElement(targetElement);
	}
	return n;
}
