/**
 * 에디터가 실행되는 페이지에 이 js 파일을 링크하면 됩니다
 * 에디터는 1페이지에 1개만 나타낼수 있습니다
 * body의 onload 이벤트에 
 * HTMLeditor.init(textarea 엘리먼트 id) 를 실행시키면 됩니다.
 * 예) <body onload="HTMLeditor.init('editor');">
 */
var HTMLeditor = {
	iframe: null,
	textarea: null,
	mode: 'editor',
	IE: false,
	selectedElement: null,
	
	/**
	 * 생성자
	 * 
	 * @param textarea_id
	 * @param iframe_id
	 * @return
	 */
	init : function(textarea_id, iframe_id, defaultValue) {
		this.textarea = document.getElementById(textarea_id);
		this.iframe = document.getElementById(iframe_id);

		//alert(defaultValue);
		
		if(this.textarea){
			if(!this.iframe){
				this.iframe = document.createElement('iframe');
				// 초기화 에디터 크기 설정
				this.iframe.frameBorder = '0';
				this.iframe.id = 'teditor';
				this.iframe.style.width = this.textarea.style.width;
				this.iframe.style.height = this.textarea.style.height;
				this.iframe.style.borderWidth = this.textarea.style.borderWidth;
				this.iframe.style.borderColor = this.textarea.style.borderColor;
				this.iframe.style.borderStyle = this.textarea.style.borderStyle;
			}
			this.textarea.style.display = 'none';
			this.textarea.parentNode.insertBefore(this.iframe, this.textarea);
			
			// 에디터 문서 파일
			var doc = this.getIframeDocument();
			doc.open();
			doc.write(
'<?xml version="1.0" encoding="UTF-8" ?>\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\
<html xmlns="http://www.w3.org/1999/xhtml">\
<head>\
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />\
<style>\
	body{margin: 5px; font: 12px Gulim, "은 돋움"; background-color: #fff; line-height: 180%; border:0; }\
	font{line-height: 180%;}\
</style>\
</head>\
<body>' + defaultValue + '\
</body>\
</html>');
			doc.close();
			doc.designMode = 'on';

			var contentDocument = this.iframe.contentWindow.document;
			//contentDocument.addEventListener("mousedown", this.eventHandler, false);
			
			return true;
		}
		return false;
	},
	
	/**
	 * 선택 영역을 구하기 위한 객체를 얻는다.
	 *
	 */
	getSel : function() {
		var t = this, w = this.win;
		return w.getSelection ? w.getSelection() : w.document.selection;
	},

	/**
	 * 실제 선택 영역을 구한다.
	 */
	getRng : function() {
		var t = this, s = t.getSel(), r;

		try {
			if (s)
				r = s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : t.win.document.createRange());
		} catch (ex) {
			// IE throws unspecified error here if TinyMCE is placed in a frame/iframe
		}

		// No range found then create an empty one
		// This can occur when the editor is placed in a hidden container element on Gecko
		// Or on IE when there was an exception
		if (!r)
			r = this.IE ? t.win.document.body.createTextRange() : t.win.document.createRange();

		return r;
	},
	
	eventHandler : function(event) {
		var t = this, r = t.getRng();
		// 마우스를 클릭했을땐 이벤트가 발생한 오브젝트 핸들을 selectedElement 변수에 저장해둔다
		alert(r);
		if(event.type == "mousedown") {
			this.selectedElement = event.target;
			alert(this.selectedElement);
		}
	},
	
	/**
	 * 에디터의 document 객체를 리턴
	 * 
	 * @return
	 */
	getIframeDocument : function() {
		// if contentDocument exists, W3C compliant (Mozilla)
		if (this.iframe.contentDocument) {
			this.IE = false;
			return this.iframe.contentDocument;
		} else {
			this.IE = true;
			return this.iframe.contentWindow.document; // IE
		}
	},
	
	/**
	 * 명령 실행
	 * 
	 * @param command
	 * @param value
	 * @return
	 */
	execCommand : function(command, value) {
		// 예외 사항
		switch (command) {
		case 'hiliteColor':
			if (this.IE)
				command = 'backColor';
			break;
		case 'createLink':
			var URL = prompt('Enter a URL:', 'http://');
			if ((URL != null) && (URL != ''))
				value = URL;
			break;
		}
		this.getIframeDocument().execCommand(command, false, value);
		this.iframe.contentWindow.focus();
	},
	
	/**
	 * 
	 * @return
	 */
	execCommandLink : function() {
		var URL = prompt('Enter a URL:', 'http://');
		if ((URL != null) && (URL != '')) {
			this.execCommand('CreateLink', URL);
		}
	},
	
	/**
	 * select 박스의 값을 가져옴
	 * 
	 * @param select
	 * @return
	 */
	getSelectValue : function(select) {
		var value = select.options[select.selectedIndex].getAttribute('value');
		if (value)
			return value;
		else
			return false;
	},
	
	/**
	 * 모드 변경 changeMode(변경할타입) 인자가 없을경우 현재 보여지고 있는 에디터모드에따라 반전이되고 인자가 (editor 또는 code) 있을 경우 해당 모드로 전환된다
	 * 
	 * @param modeValue
	 * @return
	 */
	changeMode : function(modeValue) {
		if (modeValue) {
			if (modeValue == this.mode)
				return false;
			if (modeValue == 'editor') {
				this.mode = 'editor';
				this.iframe.style.display = 'inline';
				this.textarea.style.display = 'none';
				this.getIframeDocument().body.innerHTML = this.textarea.value;
			} else {
				this.mode = 'code';
				this.iframe.style.display = 'none';
				this.textarea.style.display = 'inline';
				this.textarea.value = this.getIframeDocument().body.innerHTML;
			}
		} else {
			if (this.mode == 'editor') {
				this.mode = 'code';
				this.iframe.style.display = 'none';
				this.textarea.style.display = 'inline';
				this.textarea.value = this.getIframeDocument().body.innerHTML;
			} else {
				this.mode = 'editor';
				this.iframe.style.display = 'inline';
				this.textarea.style.display = 'none';
				this.getIframeDocument().body.innerHTML = this.textarea.value;
			}
		}
	},
	
	/**
	 * 
	 * @return
	 */
	sync : function() {
		if (this.mode == 'editor')
			this.textarea.value = this.getIframeDocument().body.innerHTML;
	},

	/**
	 * 
	 * @return
	 */
	puts : function() {
		if (this.mode == 'editor')
			this.getIframeDocument().body.innerHTML = this.textarea.value;
	}
	
	
}