// Original By http://archiva.jp/web/javascript/getRange_in_textarea.html
// Edited by ok.2nd
function encloseTextArea(tag1, tag2, obj) {
	var target = document.getElementById(obj);
	var pos = getAreaRange(target);
	if (isIE && (tag2 == '' || pos.start == pos.end)) {	// by ok.2nd
		target.focus();
		var selection = document.selection.createRange();
		selection.text = tag1 + tag2 + selection.text;
		return;
	}
	var val = target.value;
	var range = val.slice(pos.start, pos.end);
	var beforeNode = val.slice(0, pos.start);
	var afterNode  = val.slice(pos.end);
	var insertNode;
	if (range || pos.start != pos.end) {
		insertNode = tag1 + range + tag2 ;
		target.value = beforeNode + insertNode + afterNode;
	} else if (pos.start == pos.end) {
		insertNode = tag1 + tag2;
		target.value = beforeNode + insertNode + afterNode;
	}
	// カーソルを挿入文字列の後ろに表示する by ok.2nd
	target.focus();
	if (isIE) {
		r = target.createTextRange();
		if (retmatch = beforeNode.match(/\r\n/g)) { // カーソル位置より前の改行の数
			retnum = retmatch.length;
		} else {
			retnum = 0;
		}
		if (range) {
			if (retmatch = range.match(/\r\n/g)) { // 選択文字列中に改行がある場合
				retnum += retmatch.length;
			}
		}
		r.move('character', pos.end + tag1.length + tag2.length - retnum);
		r.select();
	} else {
		var newpos = pos.end + tag1.length + tag2.length;
		target.setSelectionRange(newpos, newpos);
	}
}
function getAreaRange(obj) {
	var pos = new Object();
	if (isIE) {
		obj.focus();
		var range = document.selection.createRange();
		var clone = range.duplicate();
		clone.moveToElementText(obj);
		clone.setEndPoint('EndToEnd', range);
		pos.start = clone.text.length - range.text.length;
		pos.end   = clone.text.length - range.text.length + range.text.length;
  	} else if(window.getSelection()) {
		pos.start = obj.selectionStart;
		pos.end   = obj.selectionEnd;
	}
	return pos;
}
var isIE = (navigator.appName.toLowerCase().indexOf('internet explorer')+1?1:0);
