try {
	window.addEventListener("load", function() {
		var common = new Common();
		common.anchor();
		common.setAsideHeight();
	}, false);
} catch (e) {
	// IE<=8
	window.attachEvent("onload", function() {
		var common = new Common();
		common.anchor();
		common.setAsideHeight();
	});
}

var Common = function() {
};
Common.prototype = {
	/**
	 * サイドバーの高さをコンテンツに合わせる
	 */
	setAsideHeight: function() {
		var asideElement = document.getElementById("sidebar");
		var contentsHeight = document.getElementById("page-contents").offsetHeight;

		if (contentsHeight > asideElement.offsetHeight) {
			asideElement.style.height = contentsHeight + "px";
		}
	},
	/**
	 * a要素をすべて抜き出し、外部サイトへのアンカーは別窓で開くようにし、別窓アイコンを付ける
	 */
	anchor: function() {
		var aElements = document.getElementsByTagName("a");
		for (var i = 0; i < aElements.length; i++) {
			var a = aElements[i];
			var href = a.getAttribute("href", 2);
			if ((href.indexOf("http") === 0 || href.indexOf("//") === 0) && href.indexOf("http://www.kinotrope.co.jp/") !== 0 && href.indexOf("https://www.kinotrope.co.jp/") !== 0) {
				// 絶対参照またはスキームなしの相対参照
				a.onclick = function(event) {
					return launchWindow(this, event);
				};
				a.onkeypress = function(event) {
					return launchWindow(this, event);
				};

				if (a.innerText && a.innerText !== "" || a.textContent && a.textContent !== "") {
					// テキストを含むアンカー
					var newWindowIcon = document.createElement("img");
					newWindowIcon.setAttribute("src", "/common/images/new-window-icon.gif");
					newWindowIcon.setAttribute("alt", "(新しいウィンドウが開きます)");
					newWindowIcon.setAttribute("height", "14");
					newWindowIcon.setAttribute("width", "15");

					var existFigre = false;
					var childNodes = a.childNodes;
					for (var j = 0; j < childNodes.length; j++) {
						var tag = childNodes[j].tagName;
						if (tag === "figure" || tag === "FIGURE") {
							childNodes[j].appendChild(newWindowIcon);
							existFigre = true;
							break;
						}
					}

					if (!existFigre) {
						a.appendChild(newWindowIcon);
					}
				}
			}
		}
	}
};

/**
 * 参考: http://www.ciaj.or.jp/access/web/docs/WCAG-TECHS/SCR24.html
 */
function launchWindow(objAnchor, objEvent) {
	var bSuccess = false;

	// キーボードからのイベントである場合、ユーザーがリンクをリクエストしたときだけ
	// 新しいウィンドウを開くようにする（リターン又はスペース）
	if (objEvent && objEvent.type === "keypress") {
		var iKeyCode = false;

		if (objEvent.keyCode) {
			iKeyCode = objEvent.keyCode;
		} else if (objEvent.which) {
			iKeyCode = objEvent.which;
		}

		// キャリッジ・リターン又はスペースではない場合、ユーザーエージェントが
		// アクションの処理を継続するようにtrueを返す
		if (iKeyCode !== 13 && iKeyCode !== 32) {
			return true;
		}
	}

	bSuccess = window.open(objAnchor.href);

	// ウィンドウが開かなかった場合、ブラウザには同じウィンドウで開くという
	// デフォルトのアクションを継続させる
	if (!bSuccess) {
		return true;
	}

	// ウィンドウが開いたら、ブラウザによる処理をそこで止める
	return false;
}

