var chutil = new CH_UTILITIES();
var GB = {
    colors : ["#ffffff", "#000000", "#eeece1", "#1f497d", "#4f81bd", "#c0504d", "#9bbb59", "#8064a2", "#4bacc6", "#f79646",
              "#f2f2f2", "#7f7f7f", "#ddd9c3", "#c6d9f0", "#dbe5f1", "#f2dcdb", "#ebf1dd", "#e5e0ec", "#dbeef3", "#fdeada",
              "#d8d8d8", "#595959", "#c4bd97", "#8db3e2", "#b8cce4", "#e5b9b7", "#d7e3bc", "#ccc1d9", "#b7dde8", "#fbd5b5",
              "#bfbfbf", "#3f3f3f", "#938953", "#548dd4", "#95b3d7", "#d99694", "#c3d69b", "#b2a2c7", "#92cddc", "#fac08f",
              "#a5a5a5", "#262626", "#494429", "#17365d", "#366092", "#953734", "#76923c", "#5f497a", "#31859b", "#e36c09",
              "#7f7f7f", "#0c0c0c", "#1d1b10", "#0f243e", "#244061", "#632423", "#4f6128", "#3f3151", "#205867", "#974806",
              "#c00000", "#ff0000", "#ffc000", "#ffff00", "#92d050", "#00b050", "#00b0f0", "#0070c0", "#002060", "#7030a0"],
 
    htmlKey : ["!doctype", "a", "abbr", "acronym", "address", "applet", "area", "b", "base", "basefont", "bgsound", "bdo",
               "big", "blink", "dl", "body", "br", "button", "caption", "center", "cite", "code", "col", "colgroup",
               "comment", "dd", "del", "dfn", "dir", "div", "font", "dt", "em", "embed", "fieldset", "blockquote",
               "form", "frame", "frameset", "h", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr",
               "html", "i", "iframe", "img", "input", "ins", "isindex", "kbd", "label", "legend", "li", "link",
               "listing", "map", "marquee", "menu", "meta", "multicol", "nextid", "nobr", "noframes", "noscript", "object", "ol",
               "optgroup", "option", "p", "param", "plaintext","pre", "q", "s", "samp", "script", "select", "server",
               "small", "sound", "spacer", "span", "strike", "strong", "style", "sub", "sup", "table", "tbody", "td",
               "textarea", "title", "tfoot", "th", "thead", "textflow", "tr", "tt", "u", "ul", "var", "wbr", "xmp"],
               
    MSIE    : navigator.userAgent.toLowerCase().indexOf("msie")   != -1,
    GECKO   : navigator.userAgent.toLowerCase().indexOf('gecko')  != -1,
    OPERA   : navigator.userAgent.toLowerCase().indexOf('opera')  != -1,
    SAFARI  : navigator.userAgent.toLowerCase().indexOf('safari') != -1,

    editorMode  : 'rich',
    imageBorder : '#ccc solid',
    currentRS   : new Object(),
    frameFocus  : (navigator.userAgent.toLowerCase().indexOf("msie")  != -1) ? 'onfocus' : 'onload',

    LANG        : { toolTip : { btnPrint:'인쇄', btnUndo:'실행취소', btnRedo:'되돌리기', btnCopy:'복사', btnCut:'잘라내기',
                                btnPaste:'붙이기', btnPasteFromWord:'MS워드 붙이기', btnSelectAll:'전체 선택', btnBold:'진하게',
                                btnUnderline:'밑줄', btnStrike:'취소선', btnItalic:'기울임', btnSuperscript:'위첨자',
                                btnSubscript:'아래첨자', btnJustifyLeft:'왼쪽 정렬', btnJustifyCenter:'가운데 정렬', btnJustifyRight:'오른쪽 정렬',
                                btnJustifyFull:'양쪽 정렬', btnOrderedList:'문단 번호', btnUnOrderedList:'글 머리표',
                                btnOutdent:'왼쪽여백 줄이기', btnIndent:'왼쪽여백 늘리기', btnFontType:'글꼴', btnParagraph:'단락',
                                btnFontSize:'글꼴 크기', btnBoxStyle:'박스', btnBackColor:'형광펜', btnForeColor:'글자색',
                                btnBGColor:'바탕색', btnSChar:'특수 문자', btnHyperLink:'하이퍼링크', btnUnLink:'하이퍼링크 해제',
                                btnFlash:'플래쉬 무비', btnMedia:'미디어', btnUploadImage:'그림 넣기', btnBGImage:'배경 그림', btnFullScreen:'전체화면',
                                btnEmotion:'표정 아이콘', btnHR:'가로선', btnTable:'표', btnPageBreak:'인쇄 페이지 나눔', btnHighLight:'소스코드 하이라이트' } },                             

    popupIFrame : ['fontType', 'fontSize', 'Paragraph', 'boxStyle', 'foreColor', 'backColor', 'BgColor'],
    popup       : {image :      { tmpl : 'insert_image.html',   boxW : 354, title : '그림 넣기' },
                   media :      { tmpl : 'insert_media.html',   boxW : 430, title : '미디어' },
                   bgimage :    { tmpl : 'insert_bgimage.html', boxW : 379, title : '배경 이미지' },
                   table :      { tmpl : 'insert_table.html',   boxW : 430, title : '테이블 만들기' },
                   hyperLink :  { tmpl : 'insert_hlink.html',   boxW : 420, title : '하이퍼링크' },
                   emotion :    { tmpl : 'insert_emicon.html',  boxW : 350, title : '표정아이콘' },
                   schar :      { tmpl : 'insert_schar.html',   boxW : 450, title : '특수 문자' },
                   flash :      { tmpl : 'insert_flash.html',   boxW : 500, title : '플래쉬 무비' },
                   highlight :  { tmpl : 'insert_highlight.html', boxW : 500, title : '소스코드 하이라이트' }}
}

function CH_UTILITIES()
{
    this.oname;
}

function URI (uri) {
    this.scheme    = null;
    this.authority = null;
    this.path      = '';
    this.query     = null;
    this.fragment  = null;

    this.parse = function (uri) {
        var m = uri.match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/);
        this.scheme    = m[3] ? m[2] : null;
        this.authority = m[5] ? m[6] : null;
        this.path      = m[7];
        this.query     = m[9] ? m[10] : null;
        this.fragment  = m[12]? m[13] : null;
        return this;
    }

    this.toString = function () {
        var result = '';
        if(this.scheme    != null) result = result +      this.scheme + ':';
        if(this.authority != null) result = result +'//'+ this.authority;
        if(this.path      != null) result = result +      this.path;
        if(this.query     != null) result = result + '?'+ this.query;
        if(this.fragment  != null) result = result + '#'+ this.fragment;
        return result;
    }

    this.toAbsolute = function (base) {
        var base = new URI(base);
        var r = this;
        var t = new URI;

        if (base.scheme == null) return false;

        if (r.scheme != null && r.scheme.toLowerCase() == base.scheme.toLowerCase()) {
            r.scheme = null;
        }

        if (r.scheme != null) {
            t.scheme    = r.scheme;
            t.authority = r.authority;
            t.path      = removeDotSegments(r.path);
            t.query     = r.query;
        }
        else {
            if (r.authority != null) {
                t.authority = r.authority;
                t.path      = removeDotSegments(r.path);
                t.query     = r.query;
            }
            else {
                if (r.path == '') {
                    t.path = base.path;
                    t.query = r.query || base.query;
                }
                else {
                    if (r.path.substr(0,1) == '/') {
                        t.path = removeDotSegments(r.path);
                    }
                    else {
                        if (base.authority != null && base.path == '') {
                            t.path = '/'+r.path;
                        }
                        else {
                            t.path = base.path.replace(/[^\/]+$/,'')+r.path;
                        }
                        t.path = removeDotSegments(t.path);
                    }
                    t.query = r.query;
                }
                t.authority = base.authority;
            }
            t.scheme = base.scheme;
        }

        t.fragment = r.fragment;
        return t;
    }

    function removeDotSegments (path) {
        var out = '';
        while (path) {
            if (path.substr(0,3)=='../' || path.substr(0,2)=='./') {
                path = path.replace(/^\.+/,'').substr(1);
            }
            else if (path.substr(0,3)=='/./' || path=='/.') {
                path = '/'+path.substr(3);
            }
            else if (path.substr(0,4)=='/../' || path=='/..') {
                path = '/'+path.substr(4);
                out = out.replace(/\/?[^\/]*$/, '');
            }
            else if (path=='.' || path=='..') {
                path = '';
            }
            else {
                var rm = path.match(/^\/?[^\/]*/)[0];
                path = path.substr(rm.length);
                out = out + rm;
            }
        }
        return out;
    }

    if (uri) this.parse(uri);
}

function setConfig (oname) {
    this.config = {
            editorWidth     : '100%',
            editorHeight    : '300px',
            editorFontSize  : '9pt',
            editorFontFace  : '굴림',
            editorFontColor	: '#000',
            editorBgColor	: '#fff',
            lineHeight      : 1.4,
            editAreaMargin  : '7px',
            tabIndex        : 0,
            editorPath      : null,
            fullHTMLSource  : false,
            outputXhtml		: false,
            hrefTarget      : '_blank',
            showTagPath     : true,
            toolBarSplit    : true,
            imgMaxWidth     : 730,
            imgReSize       : true,
            includeHostname : true,
            ieEnterMode     : 'css', // [css, div, br, default]
            useSource       : true,
            usePreview      : true,
            usePrint        : false,
            useUndo         : true,
            useCopy         : true,
            useCut          : true,
            usePaste        : true,
            usePasteFromWord: true,
            useSelectAll    : true,
            useBold         : true,
            useUnderline    : true,
            useStrike       : true,
            useItalic       : true,
            useSuperscript  : true,
            useSubscript    : true,
            useJustifyLeft  : true,
            useJustifyCenter: true,
            useJustifyRight : true,
            useJustifyFull  : true,
            useOrderedList  : true,
            useUnOrderedList: true,
            useOutdent      : true,
            useIndent       : true,
            useFontType     : true,
            useParagraph    : true,
            useFontSize     : true,
            useBackColor    : true,
            useForeColor    : true,
            useBGColor      : false,
            useSChar        : true,
            useHyperLink    : true,
            useUnLink       : true,
            useFlash        : true,
            useMedia        : false,
            useUploadImage  : true,
            useBGImage      : false,
            useEmotion      : true,
            useHR           : true,
            autoHeight      : false,
            useTable        : true,
            useBoxStyle     : true,
            useFullScreen   : true,
            usePageBreak    : false
    };

    if (this.config.editorPath == null) {
        var base = location.href;
        var e = document.getElementsByTagName('base')
        for (var i=0; i<e.length; i++) {
            if (e[i].href)
                base = e[i].href;
        }

        var e = document.getElementsByTagName('script');
        for (var i=0; i<e.length; i++) {
            if (e[i].src) {
                var src = new URI(e[i].src);
                if(/\/cheditor\.js$/.test(src.path)) {
                    var srcAbs = src.toAbsolute(base).toString();
                    delete srcAbs.query;
                    delete srcAbs.fragment;
                    this.config.editorPath = srcAbs.replace(/[^\/]+$/, '');
                }
            }
        }
    }
    
    this.oname              = oname;
    this.editorId           = 'id_'+this.oname;
    this.editArea           = null;
    this.doc				= null;
    this.editAreaWrapper    = null;
    this.tmpObject          = null;
    this.inputForm          = null;
    this.range          	= null;
    this.selectionType      = null;
    this.displayMode        = 'RICH';
    this.szTmp              = '';
    this.images             = new Array();
    this.toolbarRow1        = new Object();
    this.toolbarRow2        = new Object();
    this.popupID            = null;
    this.currentMode        = 'rich';
    this.setFullScreenMode	= false;
    this.icons 				= this.config.editorPath + 'icons/';
    this.fontFaceMenu		= ['굴림', '바탕', '돋움', '궁서', '맑은 고딕', 
                  			   'Arial', 'Arial Black', 'Arial Narrow', 'Courier New', 'Tahoma', 'Times New Roman', 'Verdana'];
}

function cheditor () {
    var argv = arguments;
    try {
        if (typeof(document.execCommand) == 'undefined') {
            throw "현재 브라우저가 execCommand를 지원하지 않습니다.";
        }
        if (GB.MSIE) {
            if (parseFloat(navigator.appVersion.split("MSIE")[1]) < 5.5)
                throw "CHEditor는 MSIE 6.0 이하 버전은 지원하지 않습니다.";
        }
        if (GB.GECKO) {
            if (navigator.productSub < 20030107)
                throw "CHEditor는 현재 사용 중인 브라우저를 지원하지 않습니다.";
        }
        if (argv.length < 1) {
            throw "CHEditor의 개체 이름을 설정하여 주십시오.";
        }
    }
    catch (e) {
        alert(e);
        return null;
    }

    setConfig.apply(this, argv);

    if (this.config.editorPath == null) {
        alert('CHEditor 경로가 바르지 않습니다.\nmyeditor.config.editorPath를 설정하여 주십시오.');
        return null;
    }
}

cheditor.prototype = {
//----------------------------------------------------------------

resetData : function () {
	this.resetEditArea();
    if (GB.GECKO) this.doc.body.appendChild(document.createElement('br'));
    if (GB.MSIE) {
    	try { this.doc.execCommand('BackgroundImageCache', false, true); }
    	catch (e) {}
    }
},

appendContents : function (contents) {
    this.editArea.focus();
    var div = this.doc.createElement('DIV');
    div.innerHTML = '' + contents;
    this.doc.body.appendChild(div.firstChild);
    this.editArea.focus();
},

insertContents : function (contents) {
	this.editArea.focus();
	this.setSelection();
	this.doCmdPaste(contents);
},

replaceContents : function (contents) {
    this.editArea.focus();
    this.doc.body.innerHTML = '';
    this.loadContents(contents);
    this.editArea.focus();
},

loadContents : function (contents) {
    this.editAreaWrapper.style.visibility = 'hidden';

    if (typeof(contents) == 'string')
        this.doc.body.innerHTML = contents;

    this.editAreaWrapper.style.visibility = 'visible';
},

setDesignMode : function (designMode) {
	if (GB.MSIE) {
		this.doc.body.contentEditable = designMode;
	}
	else { 
		this.doc.designMode = designMode ? "On" : "Off";
	}
},

openDoc : function (doc, contents) {
	doc.open("text/html", "replace");
    doc.close();

	if (typeof(contents) == 'string')
		doc.body.innerHTML = '' + contents;
},

resetDoc : function () {
    this.editAreaWrapper = this.$(this.editorId);
    this.editArea = this.editAreaWrapper.contentWindow;
    this.doc = this.editArea.document;
},

resetEditArea : function () {
	this.resetDoc();
    this.openDoc(this.doc);
    this.setDesignMode(true);
    this.editArea.focus();

    if (this.inputForm != null && this.$(this.inputForm) != null)
        this.loadContents(this.$(this.inputForm).value);

    this.editArea.focus();
    this.doc.body.style.fontSize      	= this.config.editorFontSize;
    this.doc.body.style.fontFamily    	= this.config.editorFontFace;
    this.doc.body.style.color 		  	= this.config.editorFontColor;
    this.doc.body.style.margin        	= this.config.editAreaMargin;
    this.doc.body.style.lineHeight    	= this.config.lineHeight;
    this.doc.body.style.backgroundColor = this.config.editorBgColor;
    this.editAreaWrapper.style.padding  = '0px';
    this.editAreaWrapper.style.margin   = '0px';
    this.editAreaWrapper.style.fontSize = '9pt';
},

startDrag : function (event) {
    GB.currentRS.elNode = this.editAreaWrapper;
    var y = GB.MSIE ? window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop :
        event.clientY + window.pageYOffset;

    GB.currentRS.cursorStartY = y;
    GB.currentRS.elStartTop = parseInt(GB.currentRS.elNode.style.height);
    if (isNaN(GB.currentRS.elStartTop)) GB.currentRS.elStartTop = 0;

    var self = this;

    if (GB.MSIE) {
        document.attachEvent("onmousemove", self.dragGo );
        document.attachEvent("onmouseup",   function () { self.dragStop.call(self); });
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    else {
        GB.currentRS.elNode.style.visibility = 'hidden';
        document.addEventListener("mousemove", self.dragGo,   true);
        document.addEventListener("mouseup",   function () { self.dragStop.call(self); }, true);
        event.preventDefault();
    }
},

dragGo : function (event) {
    var y = (GB.MSIE) ? window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop :
        event.clientY + window.pageYOffset;

    var h = (GB.currentRS.elStartTop + y - GB.currentRS.cursorStartY);
    GB.currentRS.elNode.style.height  = (h < 1 ? 1 : h) + 'px';

    if (GB.MSIE) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    else
        event.preventDefault();
},

dragStop : function () {
    if (GB.MSIE) {
        document.detachEvent("onmousemove", this.dragGo);
        document.detachEvent("onmouseup",   this.dragStop);
    }
    else {
        document.removeEventListener("mousemove", this.dragGo,   true);
        document.removeEventListener("mouseup",   this.dragStop, true);
        GB.currentRS.elNode.style.visibility = 'visible';
    }
},

switchEditorMode : function (selectedMode) {
    this.editArea.focus();
    if (this.currentMode == selectedMode) return;

    switch (selectedMode) {
        case 'rich' :
            if (this.currentMode == 'preview')
                this.previewMode();
            else if (this.currentMode == 'code')
                this.editMode();

            this.$(this.oname+'_tabEditModeRich').src = this.icons + 'edit_mode_rich_a.gif';
            if (this.config.useSource) {
                this.$(this.oname+'_tabEditModeCode').src = this.icons + 'edit_mode_code_b.gif';
            }
            this.$(this.oname+'_tabEditModePreview').src = this.icons + 'edit_mode_view_b.gif';
            break;
        case 'code' :
            this.$(this.oname+'_tabEditModeRich').src = this.icons + 'edit_mode_rich_b.gif';
            this.$(this.oname+'_tabEditModeCode').src = this.icons + 'edit_mode_code_a.gif';
            this.$(this.oname+'_tabEditModePreview').src = this.icons + 'edit_mode_view_b.gif';
            this.editMode();
            break;
        case 'preview' :
            this.previewMode();
            this.$(this.oname+'_tabEditModeRich').src = this.icons + 'edit_mode_rich_b.gif';
            if (this.config.useSource) {
                this.$(this.oname+'_tabEditModeCode').src = this.icons + 'edit_mode_code_b.gif';
            }
            this.$(this.oname+'_tabEditModePreview').src = this.icons + 'edit_mode_view_a.gif';
            break;
    }
    this.currentMode = selectedMode;
},

run : function (element) {
	
	var _customRunChEditor = new StringBuffer();
	
    this.setDefaultCss({cssName: 'default.css', doc: window.document});

    
    _customRunChEditor.append('<div style="text-align:left;position:relative;color:#000;width:'+this.config.editorWidth+';" id="container_'+this.oname+'">');
    _customRunChEditor.append('<div class="cheditor_toolbar" id="idToolbar_'+this.oname+'">');
    _customRunChEditor.append(this.drawToolbar("idToolbar_"+this.oname));
    _customRunChEditor.append('</div>');
    _customRunChEditor.append('<div class="cheditor_editarea" id="editArea_'+this.oname+'">');
    _customRunChEditor.append('<iframe frameborder="0" style="border:0px;width:100%;overflow:auto;height:'+this.config.editorHeight+'" id="'+this.editorId+'"');

    if (isNaN(this.config.tabIndex) == false)
    	_customRunChEditor.append(' tabindex="'+this.config.tabIndex+'"');

    _customRunChEditor.append(' '+GB.frameFocus+'="chutil.oname=\''+this.oname+'\'"></iframe>');
    _customRunChEditor.append('</div>');
    _customRunChEditor.append('<div id="CHModifyBlock'+this.oname+'" class="cheditor_modify_block">&#160;</div>');

    _customRunChEditor.append('<div id="statusBlock'+this.oname+'">');
    _customRunChEditor.append('<table border="0" cellpadding="0" cellspacing="0" width="100%" style="background-color:#ededed;border-right:1px solid #ccc;border-left:1px solid #ccc;"><tr>');
    if (this.config.showTagPath) {
        _customRunChEditor.append('<td id="CHstatusBar'+this.oname+'" class="cheditor_status_bar">&lt;html&gt; &lt;body&gt;</td>');
    }
    _customRunChEditor.append('<td align="right" style="vertical-align:bottom; text-align:right;"><span onmousedown="'+this.oname+'.startDrag(event)" id="reSize'+this.oname+'" class="cheditor_resize"><img src="'+this.icons+'statusbar_resize.gif" width="11" height="16" alt=""></span>');
    _customRunChEditor.append('</td></tr></table>');

    _customRunChEditor.append('<div style="padding-left:4px;text-align:left;background:url('+this.icons+'statusbar_bgline.gif);background-repeat:repeat-x;background-position:top">');
    _customRunChEditor.append('<img class="cheditor_mode_icon" id="'+this.oname+'_tabEditModeRich" src="'+this.icons+'edit_mode_rich_a.gif" onclick="'+this.oname+'.switchEditorMode(\'rich\')" title="입력모드" />');

    if (this.config.useSource)
        _customRunChEditor.append('<img class="cheditor_mode_icon" id="'+this.oname+'_tabEditModeCode" src="'+this.icons+'edit_mode_code_b.gif" onclick="'+this.oname+'.switchEditorMode(\'code\')" title="편집모드" />');

    _customRunChEditor.append('<img class="cheditor_mode_icon" id="'+this.oname+'_tabEditModePreview" src="'+this.icons+'edit_mode_view_b.gif" onclick="'+this.oname+'.switchEditorMode(\'preview\')" title="미리보기" />');
    _customRunChEditor.append('</div></div>');
    _customRunChEditor.append('<div id="dwindow_'+this.oname+'" class="cheditor_popup_window" onselectstart="return false">');
    _customRunChEditor.append('<div id="dragHandle_'+this.oname+'" class="cheditor_popup_drag_handle">');
    _customRunChEditor.append('<div class="cheditor_popup_title_bar"><label id="popupTitle_'+this.oname+'" class="cheditor_popup_title"></label></div></div>');
    _customRunChEditor.append('<div id="cframe_'+this.oname+'" class="cheditor_popup_cframe"></div></div>');
    _customRunChEditor.append('</div>'); //Container
    _customRunChEditor.append('<div id="modalWindowBackground" class="cheditor_modalPopupTransparent"></div>');

    element.append(_customRunChEditor.toString());
    this.resetData();
    this.popupID = this.$('dwindow_'+this.oname);
    this.editArea.focus();
    this.setEditorEvent();
    this.setDefaultCss();
    
},

fullScreenMode : function () {
	var self = this;
	self.editArea.focus();
    self.boxHideAll();
    
	var container = self.$('container_'+self.oname);
	var tmpFlagId = 'CHEditorTmpFlag_' + self.oname;
	var docElement = self.doc.documentElement;

	container.style.visibility = 'hidden';
	var openDoc = function(content) {
		self.doc.open("text/html", "replace");
		self.doc.write(content);
	    self.doc.close();
	};
	
	if (self.setFullScreenMode == false) {
		var margin = 2;
		var tmpFlag = document.createElement('DIV');
		var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
		var clientHeight= (GB.MSIE) ? document.documentElement.clientHeight || document.body.clientHeight :
			((document.documentElement.clientHeight < document.body.clientHeight) ? document.body.clientHeight :
				document.documentElement.clientHeight);
		
		tmpFlag.id = tmpFlagId;
		tmpFlag.style.display = 'none';
		container.parentNode.insertBefore(tmpFlag, container);
		document.body.insertBefore(container, document.body.firstChild);

		container.style.position = 'absolute';
		container.style.left = margin + 'px';
		container.style.top = margin + 'px';
		container.style.width = (clientWidth - margin - 2) + 'px';
		container.style.zIndex = 99;
		
		self.editAreaWrapper.style.height = clientHeight + 'px';
		var scrollHeight = document.body.scrollHeight;
		if (scrollHeight < 200) {
			scrollHeight = document.documentElement.scrollHeight;
		}
		margin = -2;
		self.editAreaWrapper.style.height = (clientHeight - (scrollHeight - clientHeight)) + margin + 'px';
		
		self.resetDoc();
		openDoc(GB.MSIE ? docElement.outerHTML : docElement.innerHTML);
	}
	else {
		self.$(tmpFlagId).parentNode.replaceChild(container, self.$(tmpFlagId));
		self.resetDoc();
		openDoc(GB.MSIE ? docElement.outerHTML : docElement.innerHTML);
		
		container.removeAttribute('style');
		container.style.position = 'relative';
		container.style.width = self.config.editorWidth;
		container.style.textAlign = 'left';
		self.editAreaWrapper.style.height = self.config.editorHeight;
	}
	
	self.setFullScreenMode = !(self.setFullScreenMode);
	container.style.visibility = 'visible';
	
	self.setDesignMode(true);
	self.setEditorEvent();
	self.setDefaultCss();
	self.editArea.focus();
},

showColorMenu : function (idImg, menu) {
	var boxName = menu + '_' + this.oname;

    if (this.$(boxName) == null) {
    	var output = this.createWindow(180, this.setColorTable(menu));
    	this.createPulldownFrame(output, menu);
    }

    this.windowPos(idImg, boxName);
    this.displayWindow(boxName);
},

showFontTypeMenu : function (idImg) {
    var boxName = 'fontType_' + this.oname;

    if (!this.$(boxName)) {
        var output = document.createElement('div');
        for (var i=0; i < this.fontFaceMenu.length; i++) {
            var div = document.createElement('div');
            var label = document.createElement('label');
            div.setAttribute('onclick',     this.oname + '.changeFontType("' + this.fontFaceMenu[i] + '")');
            div.setAttribute('onmouseover', this.oname + '.mouseOver(this)');
            div.setAttribute('onmouseout',  this.oname + '.mouseOut(this)');
            div.style.padding = '2px';
            div.style.lineHeight = 1.1;
            div.style.margin = '1px';
            div.style.fontSize = '9pt';
            label.style.fontFamily = this.fontFaceMenu[i];

            label.appendChild(document.createTextNode(this.fontFaceMenu[i]));
            div.appendChild(label);
            output.appendChild(div);
        }

        this.createPulldownFrame(this.createWindow(150, output.innerHTML), 'fontType');
    }
    
    this.windowPos(idImg, boxName);
    this.displayWindow(boxName);
},

showParagraphMenu : function (idImg) {
    var boxName = 'Paragraph_' + this.oname;
    
    if (!this.$(boxName)) {
        var output = '';
        var para = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'PRE', 'ADDRESS', 'DIV', 'P'];
        
        // 2009-06-30 add by 석용범
        // 관리자단 css와 충돌로 인해 추가
        var _para = [24, 18, 13.5, 12, 10, 7.5];
        
        var text = ['제목 1', '제목 2', '제목 3', '제목 4', '제목 5', '제목 6', 'Preformatted (PRE)', '주소 (ADDRESS)', '보통 (DIV)', '보통 (P)'];

        for (var i=0; i < para.length; i++) {
            output += "<div onclick=\""+this.oname+".applyParagraph('<"+para[i]+">')\" onmouseover='"+this.oname+".mouseOver(this)'";
            output += " onmouseout='"+this.oname+".mouseOut(this)' class='dropdown' style='padding:2px;margin:1px;cursor:default;line-height:1.1'>";
            if (para[i].match(/H[123456]/)) {
//            	output += '<'+para[i]+' style="margin:0px">'+text[i]+'</'+para[i]+'>';
	        
				// 2009-06-30 add by 석용범
				// 관리자단 css와 충돌로 인해 추가
           		output += '<div style="font-size:'+_para[i]+'pt; font-weight:bold; margin:0px;">'+text[i]+'</div>';
            }
            else {
            	output += '<span style="font-size:9pt;margin:0px;';
            	output += (para[i] == 'ADDRESS') ? "font-style:italic" : '';
            	output += '">'+text[i]+'</span>';
            }
            output += '</div>';
        }

        this.createPulldownFrame(this.createWindow(150, output), 'Paragraph');
    }
    
    this.windowPos(idImg, boxName);
    this.displayWindow(boxName);
},

showFontSizeMenu : function (idImg) {
	var boxName = 'fontSize_' + this.oname;

    if (this.$("fontSize_"+this.oname) == null) {
        var output = document.createElement('div');
        var fontSize = [1, 2, 3, 4, 5, 6, 7];
        var showFont = [8, 10, 12, 14, 18, 24, 32];

        for (var i=0; i < fontSize.length; i++) {
            var div = document.createElement('div');
            var label = document.createElement('label');
            var text = showFont[i] == 32 ? '가나다' : '가나다라';
            div.setAttribute('onclick',     this.oname + '.changeFontSize("' + fontSize[i] + '")');
            div.setAttribute('onmouseover', this.oname + '.mouseOver(this)');
            div.setAttribute('onmouseout',  this.oname + '.mouseOut(this)');
            div.style.padding = '2px';
            div.style.margin = '1px';
            div.style.lineHeight = 1.1;
            div.style.fontSize = showFont[i] + 'pt';
            label.style.fontFamily = this.config.editorFontFace;
            
            label.appendChild(document.createTextNode(text+'('+showFont[i]+'pt)'));
            div.appendChild(label);
            output.appendChild(div);
        }

        this.createPulldownFrame(this.createWindow(280, output.innerHTML), 'fontSize');
    }
    
    this.windowPos(idImg, boxName);
    this.displayWindow(boxName);
},

showBoxStyleMenu : function (idImg) {
	var boxName = 'boxStyle_' + this.oname;

    if (this.$("boxStyle_"+this.oname) == null ) {
        var output = document.createElement('div');
        var quote = [['1px #dedfdf solid','#f7f7f7'],
                     ['1px #aee8e8 solid','#bfffff'],
                     ['1px #d3bceb solid','#e6ccff'],
                     ['1px #e8e88b solid','#ffff99'],
                     ['1px #c3e89e solid','#d6ffad'],
                     ['1px #e8c8b7 solid','#ffdcc9'],
                     ['1px #666666 dashed','#ffffff'],
                     ['1px #d4d4d4 solid','#ffffff'],
                     ['1px #cccccc inset','#f7f7f7']];

        for (var i=0; i < quote.length; i++) {
        	var wrapper = document.createElement('div');
            var div = document.createElement('div');
            div.setAttribute('onclick', this.oname + '.boxStyle(this)');
            wrapper.setAttribute('onmouseover', 'this.style.border="1px #316ac5 solid";');
            wrapper.setAttribute('onmouseout', 'this.style.border="1px #fff solid";');
            wrapper.style.border = '1px #fff solid';
            wrapper.style.padding = '1px';
            wrapper.style.margin = '1px';
            div.style.textAlign = 'center';
            div.style.lineHeight = '18px';
            div.style.fontSize = '9pt';
            div.style.border = quote[i][0];
            div.style.backgroundColor = quote[i][1];
            div.style.cursor = 'default';
            div.style.fontFamily = this.config.editorFontFace;
            div.appendChild(document.createTextNode('가나다라 ABC'));
            wrapper.appendChild(div);
            output.appendChild(wrapper);
        }

        this.createPulldownFrame(this.createWindow(100, output.innerHTML), 'boxStyle');
    }
    
    this.windowPos(idImg, boxName);
    this.displayWindow(boxName);
},

createPulldownFrame : function (contents, id) {
    var div = document.createElement('div');
    div.id = id + '_' + this.oname;
    div.className = 'cheditor_pulldown_frame';
    div.appendChild(contents);
    this.$('container_'+this.oname).firstChild.appendChild(div);
},

setDefaultCss : function (ar) {
    if (arguments.length == 0) {
        ar = {cssName: 'default.css', doc: this.doc};
        if (GB.MSIE) {
            ar = {cssName: 'p.css', doc: this.doc};
        }
    }

    var cssFile = this.config.editorPath + ar.cssName;
    var head = ar.doc.getElementsByTagName('head');
    var found = false;

    if (typeof head[0] == 'undefined')
    	return;
    
    if (head[0].hasChildNodes()) {
        var child = head[0].childNodes;
        for (var i = 0; i < child.length; i++) {
            if (child[i].tagName == 'LINK') {
                var href = child[i].getAttribute('href');
                if (href != null && href == cssFile) {
                    found = true;
                    break;
                }
            }
        }
    }

    if (found == false) {
        var css = head[0].appendChild(ar.doc.createElement('link'));
        css.setAttribute('type', 'text/css');
        css.setAttribute('rel', 'stylesheet');
        css.setAttribute('media', 'all');
        css.setAttribute('href', this.config.editorPath + ar.cssName);
    }
},

setEditorEvent : function () {
    var self = this;
    
    if (GB.MSIE && self.config.ieEnterMode == 'br')
        self.doc.onkeydown = function () { self.doOnKeyPress(); };

    if (self.config.showTagPath) {
        var func 	= function () { self.doEditorEvent(); };
        var hideBox = function () { self.boxHideAll(); };
        
        self.addEvent(self.doc, "mouseup", func);
        self.addEvent(self.doc, "mousedown", hideBox);
    }
},

addEvent : function (doc, ev, func) {
    this.removeEvent(doc, ev, func);

    if (GB.MSIE)
        doc.attachEvent("on"+ev, func);
    else
        doc.addEventListener(ev, func, false);
},

removeEvent : function (doc, ev, func) {
    if (GB.MSIE)
        doc.detachEvent("on"+ev, func);
    else
        doc.removeEventListener(ev, func, false);
},

toolbarButtonOut : function (elemButton, nTop) {
    elemButton.style.top = -nTop + 'px';
},

toolbarButtonOver : function (elemButton) {
    var nTop = elemButton.style.top.substring(0, elemButton.style.top.length - 2);
    elemButton.style.top = nTop - 22 + 'px';
},

showToolbar : function (tb) {
	var ele = new StringBuffer();
    for (var i in tb) {
        if (typeof(tb[i].use) == "boolean" && tb[i].use == true) {
           ele.append(this.drawToolbarIcon(tb[i].icon[0], tb[i].icon[1], tb[i].icon[2], i+this.oname, GB.LANG.toolTip[i], this.oname+tb[i].exec, ele));
        }
    }

    return ele;
},

drawToolbarIcon : function (iconBlock, top, iconWidth, id, toolTip, cmd, ele) {
	ele.append('<div style="float:left;margin:0px 2px 0px 0px;width:'+iconWidth+'px;height:24px">');
	ele.append('<span unselectable="on" style="cursor:pointer;position:absolute;clip:rect(0px '+iconWidth+'px 22px 0px)">');
	ele.append('<img id="'+id+'" title="'+toolTip+'" src="'+this.icons+'toolbar_icon_'+iconBlock+'.gif"' +
            ' style="position:absolute;top:-'+top+'px;width:'+iconWidth+'px"' +
            ' onmouseover="'+this.oname+'.toolbarButtonOver(this)" onmouseout="'+this.oname+'.toolbarButtonOut(this,'+top+')"' +
            ' onclick="'+((cmd.indexOf('fullScreenMode') != -1) ? this.oname+'.toolbarButtonOut(this,'+top+');'+cmd : cmd) +
            '" alt="" />');
	ele.append('</span></div>');
},

drawToolbar : function (ch_id) {
    this.toolbarRow1 = {
        //btnPrint : { use : this.config.usePrint, icon : [1,0,22], exec : ".doCmd('print', false)" },
        //btnUndo : { use : this.config.useUndo, icon : [1,44,22], exec : ".doCmd('Undo', false)" },
        //btnRedo : { use : this.config.useUndo, icon : [1,88,22], exec : ".doCmd('Redo', false)" },
        btnCopy : { use : this.config.useCopy, icon : [1,132,22], exec : ".doCmd('Copy', false)" },
        btnCut : { use : this.config.useCut, icon : [2,0,22], exec : ".doCmd('Cut', false)" },
        btnPaste : { use : this.config.usePaste, icon : [2,44,22], exec : ".doCmd('Paste', false)" },
        //btnPasteFromWord : { use : this.config.usePasteFromWord, icon : [10,88,22], exec : ".doCmd('PasteFromWord', false)" },
        btnSelectAll : { use : this.config.useSelectAll, icon : [2,88,22], exec : ".doCmd('SelectAll', false)" },
        btnBold : { use : this.config.useBold, icon : [2,132,22], exec : ".doCmd('Bold', false)" },
        btnUnderline : { use : this.config.useUnderline, icon : [3,0,22], exec : ".doCmd('Underline', false)" },
        btnStrike : { use : this.config.useStrike, icon : [3,44,22], exec : ".doCmd('Strikethrough', false)" },
        btnItalic : { use : this.config.useItalic, icon : [3,88,22], exec : ".doCmd('Italic', false)" },
        btnSuperscript : { use : this.config.useSuperscript, icon : [3,132,22], exec : ".doCmd('Superscript', false)" },
        btnSubscript : { use : this.config.useSubscript, icon : [4,0,22], exec : ".doCmd('Subscript', false)" },
        btnJustifyLeft : { use : this.config.useJustifyLeft, icon : [4,44,22], exec : ".doCmd('JustifyLeft', false)" },
        btnJustifyCenter : { use : this.config.useJustifyCenter, icon : [4,88,22], exec : ".doCmd('JustifyCenter', false)" },
        btnJustifyRight : { use : this.config.useJustifyRight, icon : [4,132,22], exec : ".doCmd('JustifyRight', false)" },
        btnJustifyFull : { use : this.config.useJustifyFull, icon : [5,0,22], exec : ".doCmd('JustifyFull', false)" },
        btnOrderedList : { use : this.config.useOrderedList, icon : [5,44,22], exec : ".doCmd('InsertOrderedList', false)" },
        btnUnOrderedList : { use : this.config.useUnOrderedList, icon : [5,88,22], exec : ".doCmd('InsertUnOrderedList', false)" },
        btnOutdent : { use : this.config.useOutdent, icon : [5,132,22], exec : ".doCmd('Outdent', false)" },
        btnIndent : { use : this.config.useIndent, icon : [6,0,22], exec : ".doCmd('Indent', false)" }
    };
    this.toolbarRow2 = {
        btnFontType : { use : this.config.useFontType, icon : [8,0,30], exec : ".showFontTypeMenu(this);" },
        btnParagraph : { use : this.config.useParagraph, icon : [8,44,30], exec : ".showParagraphMenu(this);" },
        btnFontSize : { use : this.config.useFontSize, icon : [8,88,30], exec : ".showFontSizeMenu(this);" },
        btnBoxStyle : { use : this.config.useBoxStyle, icon : [11,0,22], exec : ".showBoxStyleMenu(this);" },
        btnBackColor : { use : this.config.useBackColor, icon : [9,88,22], exec : ".showColorMenu(this,'backColor');" },
        btnForeColor : { use : this.config.useForeColor, icon : [9,132,22], exec : ".showColorMenu(this,'foreColor');" },
        btnBGColor : { use : this.config.useBGColor, icon : [9,44,22], exec : ".showColorMenu(this,'BgColor');" },
        btnSChar : { use : this.config.useSChar, icon : [7,132,22], exec : ".windowOpen('schar')" },
        btnHyperLink : { use : this.config.useHyperLink, icon : [6,44,22], exec : ".windowOpen('hyperLink')" },
        btnUnLink : { use : this.config.useUnLink, icon : [6,88,22], exec : ".doCmd('UnLink',false)" },
        btnFlash : { use : this.config.useFlash, icon : [9,0,22], exec : ".windowOpen('flash')" },
        btnMedia : { use : this.config.useMedia, icon : [6,132,22], exec : ".windowOpen('media')" },
        btnUploadImage : { use : this.config.useUploadImage, icon : [7,0,22], exec : ".windowOpen('image')" },
        btnBGImage : { use : this.config.useBGImage, icon : [7,44,22], exec : ".windowOpen('bgimage')" },
        btnEmotion : { use : this.config.useEmotion, icon : [7,88,22], exec : ".windowOpen('emotion')" },
        btnHR : { use : this.config.useHR, icon : [10,0,22], exec : ".doCmd('InsertHorizontalRule')" },
        btnTable : { use : this.config.useTable, icon : [10,44,22], exec : ".windowOpen('table')" },
        //btnPageBreak : { use : this.config.usePageBreak, icon : [10,132,22], exec : ".printPageBreak()" },
        //btnFullScreen : { use : this.config.useFullScreen, icon : [11,88,22], exec : ".fullScreenMode()" },
        btnHighLight : { use : this.config.useHighlight, icon : [11,44,22], exec : ".windowOpen('highlight')," }
    };
    
    var _html = new StringBuffer();
    
    _html.append('<table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin:0 0">');
    _html.append('<tr><td align="left">');
	_html.append(this.showToolbar(this.toolbarRow1));
    
    if (this.config.toolBarSplit) _html.append('</td></tr><tr><td>');
	_html.append(this.showToolbar(this.toolbarRow2));

    _html.append('</td></tr></table>');
    return _html;
},

changeFontType  : function (val) { this.doCmdPopup("FontName", val); },
applyParagraph  : function (val) { this.doCmdPopup("FormatBlock", val); },
changeFontSize  : function (val) { this.doCmdPopup("FontSize", val); },
changeBodyColor : function (val) { this.setBodyColor(val); },

changeFontColor : function (color, type) {
    if (type == 'back') {
        this.doCmdPopup(GB.MSIE ? 'BackColor' : 'HiliteColor', color);
    }
    else {
        this.doCmdPopup('ForeColor', color);
    }
},

setBodyColor : function (color) {
    this.doc.body.style.backgroundColor = color;

    if (GB.MSIE && this.range)
        this.range.select();

    this.boxHideAll();
    this.editArea.focus();
},

getElement : function (elm, tag) {
    while (elm != null && elm.tagName != tag) {
        if (elm.id == this.editorId) return null;
        elm = elm.parentElement;
    }
    return elm;
},

hyperLink: function (href, target, title) {
    var rng = this.range;
    var selType = this.selectionType;
    var linked = '';

    if (GB.MSIE) {
        if (rng.text == '' || selType == "None")
            return;
        else
        	rng.select();
        
        rng.execCommand("UnLink", false);
        rng.execCommand("CreateLink", false, href);
        linked = rng.parentElement ? rng.parentElement() : this.getElement(rng.item(0), "A");
    }
    else {
        var sel = this.getSelection();
        var rng = this.getRange();
        this.$(this.editorId).contentDocument.execCommand("CreateLink", false, href);
        linked = rng.startContainer;
    }

    if (linked) {
        if (target) try { linked.setAttribute("target", target); } catch(e) {};
        if (title)  try { linked.setAttribute("title",  title); } catch(e) {};
    }
},

boxStyle: function (el) {
    var range = this.range;
    var quote = this.doc.createElement("blockquote");

    if (el.currentStyle) {
        quote.style.backgroundColor = el.currentStyle.backgroundColor;
        quote.style.border = el.style.border;
    }
    else if (window.getComputedStyle) {
        var compStyle = document.defaultView.getComputedStyle(el, null);
        var style = compStyle.getPropertyValue('border-top-style');
        var width = compStyle.getPropertyValue('border-top-width');
        var color = compStyle.getPropertyValue('border-top-color');
        quote.style.border = width + ' ' + color + ' ' + style;
        quote.style.backgroundColor = compStyle.getPropertyValue("background-color");
    }
    else {
        alert('현재 브라우저는 이 기능을 지원하지 않습니다.');
        return;
    }

    quote.style.padding = "2px";
    quote.style.margin = "5px";

    if (GB.MSIE) {
        var ctx = range.htmlText;
        quote.innerHTML = ctx ? ctx: '&nbsp;';
        range.select();
        this.insertHTML(quote.outerHTML);
    }
    else {
        var pDiv = this.doc.createElement('div');
        quote.appendChild(range != '' ? range.extractContents() : this.doc.createElement('br'));
        pDiv.appendChild(quote);
		this.insertNodeAtSelection(pDiv);
    }

    this.boxHideAll();
},

insertBgImage: function (img) {
    this.editArea.focus();

    if (img) {
        this.doc.body.style.backgroundImage = "url("+img+")";
    }
    else {
        var s = this.doc.body.style;
        GB.MSIE ? s.removeAttribute("backgroundImage") : s.backgroundImage = "none";
    }
},

insertFlash: function (elem) {
	this.editArea.focus();
	
	if (typeof elem == 'string') {
		var div = this.doc.createElement('DIV');
		var rData = '';
		div.innerHTML = elem;
		var embed = div.getElementsByTagName('EMBED');

		if (embed[0]) {
			rData = embed[0].outerHTML;
			if (GB.MSIE) {
				this.doCmdPaste(rData);
			}
			else {
				this.insertNodeAtSelection(embed[0]);
			}
		}
	}

	this.editArea.focus();
},

insertHtmlPopup: function (elem) {
	this.editArea.focus();

	if (GB.MSIE) {
		if (typeof elem == 'string') {
			this.doCmdPaste(elem);
		}
		else {
			this.doCmdPaste(elem.outerHTML);
		}
	}
	else {
		if (typeof elem == 'string') {
			var div = this.doc.createElement('DIV');
			div.innerHTML = elem;
			this.insertNodeAtSelection(div.firstChild);
		}
		else {
			this.insertNodeAtSelection(elem);
		}
	}
	this.editArea.focus();
},

insertHTML: function (html) {
	if (GB.MSIE) {
		this.getRange().pasteHTML(html);
	}
	else {
		var div = this.doc.createElement('DIV');
		div.innerHTML = html;
		this.insertNodeAtSelection(div.firstChild);
	}
},

insertNodeAtSelection: function (insertNode) {
    var sel = this.getSelection();
    var rng = this.getRange();

    sel.removeAllRanges();
    rng.deleteContents();

    var container = rng.startContainer;
    var pos = rng.startOffset;

    rng = document.createRange();

    if (container.nodeType==3 && insertNode.nodeType==3) {
        container.insertData(pos, insertNode.nodeValue);
        try {
        	rng.setEnd(container, pos+insertNode.length);
        	rng.setStart(container, pos+insertNode.length);
		}
		catch (e) {};
    }
    else {
        var afterNode, beforeNode;
        
        if (container.nodeType == 3) {
            var textNode 	= container;
            var text 		= textNode.nodeValue;
            var textBefore 	= text.substr(0, pos);
            var textAfter 	= text.substr(pos);
            
            container 	= textNode.parentNode;
            beforeNode 	= document.createTextNode(textBefore);
            afterNode 	= document.createTextNode(textAfter);

            container.insertBefore(afterNode, textNode);
            container.insertBefore(insertNode, afterNode);
            container.insertBefore(beforeNode, insertNode);
            container.removeChild(textNode);
        }
        else {
            afterNode = container.childNodes[pos];
            container.insertBefore(insertNode, afterNode);
        }

        try {
        	rng.setEnd(afterNode, 0);
        	rng.setStart(afterNode, 0);
        }
        catch (e) { }; //alert(e); }
    }
    
    sel.addRange(rng);
},

doInsertImage : function (images) {
    for (var i=0; i<images.length; i++) {
        var img = new Image();
        img.src = images[i]['filepath'];
        img.width = images[i]['width'];
        img.height = images[i]['height'];
        img.align = images[i]['align'];
        img.alt = images[i]['alt'] ? images[i]['alt'] : '';
        img.border = 0;

        var imgInfo = new Object();
        imgInfo['src'] = img.src;
        imgInfo['filename'] = images[i]['fileorig'];
        imgInfo['fileid'] = images[i]['filename'];
        imgInfo['width'] = img.width;
        imgInfo['height'] = img.height;

        this.images.push(imgInfo);
        this.insertImage(img);
    }
},

insertImage : function (img) {
    var linebreak = false;
    var reSize = false;
    var outer = img;

    if (this.config.imgReSize) reSize = this.resizeImageComplete(img);
    if (img.alt == 'break') {
        linebreak = true;
        img.removeAttribute("align");
        img.alt = '';
    }

    if (reSize) {
//09.07.13 : betty - 일정사이즈 이상이면 A링크가 자동 붙는걸 방지하기위해 막음
//        var szRandom = Math.random();
//        var imgId = 'image_'+szRandom;
//        var thumb = 'thumb_'+szRandom;
//        var href = document.createElement('a');
//
//        imgId = imgId.replace(/\./,'');
//        thumb = thumb.replace(/\./,'');
//
//        img.id = imgId;
//        img.className = 'chimg_photo';
//        img.onload = 'true';
//        href.id = thumb;
//        href.href = img.src;
//        href.className = 'imageUtil';
//        href.onclick = 'return false';
//        href.appendChild(img);
//        outer = href;
    }

    if (linebreak) {
        var p = document.createElement('p');
        p.style.width = '100%';
        p.style.margin = '5px 0px';
        p.appendChild(outer);
        outer = p;
    }

	this.insertHtmlPopup(outer);
},

resizeImageComplete : function (img) {
    var maxWidth = isNaN(this.config.imgMaxWidth) ? 600 : this.config.imgMaxWidth;
    if (img.width <= maxWidth) return false;

    img.style.width  = maxWidth + 'px';
    img.style.height = Math.round((img.height * maxWidth) / img.width) + 'px';
    img.removeAttribute("width");
    img.removeAttribute("height");

    return true;
},

showTagSelector : function (on) {
    if (!this.config.showTagPath) return;
    var el = this.$("CHstatusBar"+this.oname);
    el.style.display = on ? '' : 'none';
},

showTags : function (doc) {
    var retDoc = '';
    if (doc.hasChildNodes()) {
        var child = doc.firstChild;
        do {
            child = child.nextSibling;

        } while (child);
        var children = doc.childNodes;
        for (var i=0; i < children.length; i++) {
            this.showTags(children[i]);
        }
    }
},

editMode: function () {
    this.range = null;
    this.popupWinClose();
    this.resetStatusBar();
    this.editAreaWrapper.style.visibility = 'hidden';
    this.setDesignMode(true);

    if (this.currentMode == 'rich' || this.currentMode == 'preview') {
        var tmpBody = this.getContents(false);
        this.szTmp = this.doc.body.style.cssText;
        var content = (this.config.fullHTMLSource == true) ? tmpBody : this.docSplit(tmpBody);
        var key = GB.htmlKey.join ("|");
        var reg1 = new RegExp ("(&lt;\/?)("+key+")( ?\/?)(&gt;)", "ig");
        var reg2 = new RegExp ("(&lt;)("+key+") +([a-zA-Z]+)=(.+?)(\/?)(&gt;)", "ig");

        content = content.replace(/</g,'&lt;').replace(/>/g,'&gt;');
        content = content.replace(/&nbsp;/g, '&amp;nbsp;');
        content = content.replace(reg2, "<font color=\"#0000c8\">$1$2</font> <font color=\"#b40000\">$3</font>=<font color=\"#248f00\">$4</font><font color=\"#0000c8\">$5$6</font>");
        content = content.replace(reg1, "<font color=\"#0000cc\">$1$2$3$4</font>");
        content = content.replace(/\n/g, '<br />');
        
        this.doc.body.innerHTML = content;
        this.doc.body.clearAttributes;
        this.doc.body.style.fontFamily = 'courier new,courier';
        this.doc.body.style.fontSize = '9pt';
        this.doc.body.style.color = '#000';
        this.doc.body.style.lineHeight = this.config.lineHeight;
        this.doc.body.style.background = '#fff';

        var tmpHeight = this.editAreaWrapper.offsetHeight + this.$("idToolbar_"+this.oname).offsetHeight;
        this.$("idToolbar_"+this.oname).style.display = "none";
        this.editAreaWrapper.style.height = parseInt(tmpHeight) + 'px';
        this.showTagSelector(false);
    }
    else {
        this.setDesignMode(false);
        this.putContents(this.makeHtmlContent());
        this.$("idToolbar_"+this.oname).style.display = '';

        var tmpHeight = this.editAreaWrapper.offsetHeight - this.$("idToolbar_"+this.oname).offsetHeight;
        this.editAreaWrapper.style.height = tmpHeight + 'px';

        if (!this.config.fullHTMLSource)
            this.doc.body.style.cssText = this.szTmp;

        this.setDesignMode(true);
        this.showTagSelector(true);
        this.setEditorEvent();
    }

    this.editAreaWrapper.style.visibility = 'visible';
    this.editArea.focus();
    this.setDefaultCss();
},

makeHtmlContent : function () {
    if (GB.MSIE) return this.doc.body.innerText;
    
    var html = this.doc.createRange();
    html.selectNodeContents(this.doc.body);
    
    return html.toString();
},

resetStatusBar : function () {
    if (this.config.showTagPath)
        this.$('CHstatusBar'+this.oname).innerHTML = '&lt;html&gt; &lt;body&gt; ';
},

previewMode : function () {
    this.range = null;
    this.popupWinClose();
    this.resetStatusBar();

    if (this.config.useSource) {
        if (this.currentMode == 'code') {
            this.setDesignMode(false);
            this.putContents(this.makeHtmlContent());
            this.currentMode = 'rich';
        }
    }

    this.editAreaWrapper.style.visibility = 'hidden';

    if (this.currentMode == 'rich') {
        this.setDesignMode(false);
        this.$("CHModifyBlock"+this.oname).style.display = 'none';
        this.showTagSelector(false);

        var tmpHeight = this.editAreaWrapper.offsetHeight + this.$("idToolbar_"+this.oname).offsetHeight;
        this.$("idToolbar_"+this.oname).style.display = "none";
        this.editAreaWrapper.style.height =  tmpHeight+'px';
    }
    else {
        this.setDesignMode(true);
        this.$("idToolbar_"+this.oname).style.display = '';
        var tmpHeight = this.editAreaWrapper.offsetHeight - this.$("idToolbar_"+this.oname).offsetHeight;

        this.editAreaWrapper.style.height = tmpHeight + 'px';
        this.showTagSelector(true);
        this.setEditorEvent();
    }

    this.editAreaWrapper.style.visibility = 'visible';
    this.editArea.focus();
    this.setDefaultCss();
},

putContents : function (sContent) {
    sContent = (this.config.fullHTMLSource == false) ? sContent : this.docSplit(sContent);
    if (GB.MSIE) {
    	this.openDoc(this.doc, sContent);
        this.setDesignMode(true);
        this.doc.execCommand("2D-Position", true, true);
        this.doc.execCommand("MultipleSelection", true, true);
        this.doc.execCommand("LiveResize", true, true);
    }
    else {
        this.doc.body.innerHTML = sContent;
    }

    this.doc.body.style.cssText = this.szTmp;
},

getImages : function () {
    var img = this.doc.body.getElementsByTagName('img');
    var imgNumber = this.images.length;
    var imgArr = new Array();

    for (i=0; i<img.length; i++) {
        if (img[i].src) {
            var imgid = img[i].src;
            imgid = imgid.slice(imgid.lastIndexOf("/") + 1);
            for (var j=0; j<imgNumber; j++) {
                if (this.images[j]['fileid'] == imgid) {
                    imgArr.push(this.images[j]);
                    break;
                }
            }
        }
    }

    return imgArr.length > 0 ? imgArr : false;
},

scanDom : function (node) {
	if (!(node = this.eValidate(node))) return null;
	var rData = new Array(0);
	var stack = new Array(new Array(node, node.childNodes.length, 0));
	
	while (stack.length) {
		var currentStackIndex = stack.length - 1;
		if (typeof(stack[currentStackIndex][0]) == "object" && stack[currentStackIndex][1]) {
			if (!stack[currentStackIndex][2]) {
				rData.push(stack[currentStackIndex][0]);
			}
			var nextObjectIndex = (stack[currentStackIndex][0].childNodes.length - stack[currentStackIndex][1]);
			--stack[currentStackIndex][1];
			stack[currentStackIndex][2] = 1;
			stack.push(new Array(stack[currentStackIndex][0].childNodes[nextObjectIndex], 
					stack[currentStackIndex][0].childNodes[nextObjectIndex].childNodes.length, 0));
		}
		else {
			if (!stack[currentStackIndex][2]) {
				rData.push(stack[currentStackIndex][0]);
			}
			stack.pop();
		}
	}
	
	return rData;
},

getAttrs : function (element, returnString) {
	if (!(element = this.eValidate(element))) return null;
	var rData = new String(' ');
	var array = new Array();
	for(var i=0; i < element.attributes.length; i++) {
		if (element.attributes[i].specified) {
			array[element.attributes[i].nodeName] = element.attributes[i];
			var nodeValue = element.attributes[i].nodeValue;
			
			if (element.attributes[i].nodeName.toLowerCase() == "style" && returnString) {
    			var css = element.style["cssText"].split(';');
    			if (css) {
    				var val = new Array();
    				for (var j=0; j < css.length; j++) {
    					var s = css[j].split(':');
    					if (s[0] && typeof s[1] != 'undefined') {
    						val.push(s[0].toLowerCase() + ':' + s[1]);
    					}
    				}
    			}
    			nodeValue = val.join('; ');
			}
		
			if (nodeValue != null && nodeValue != '' && 
					(typeof nodeValue == 'string' && nodeValue.indexOf('Apple-style') == -1))
			{
				rData = rData.concat(element.attributes[i].nodeName.toLowerCase(), '="', nodeValue, '" ');
			}
		}
	}
	
	return (!returnString) ? array : (returnString == 1) ? rData.substring(0, rData.length-1) :
			new Array(array, rData.substring(0, rData.length-1));
},

eValidate : function (element) {
	if (typeof(element) == "string") {
		element = element.replace(/(^\s+)|(\s+$)/g, "");
	}
	
	return element= (typeof(element) == "undefined" || !(document.getElementById)) ? null :
		(typeof(element) == "object") ? element :
			document.getElementById(element) ? document.getElementById(element) :
				(typeof(element) == "string" && document.getElementsByTagName(element.toUpperCase())) ?
						document.getElementsByTagName(element.toUpperCase())[0] :
							null;
},

getHTML : function (element, reportOnlyTags, standaloneTags) {
	if(!(element = this.eValidate(element))) {
		return null;
	}

	standaloneTags = (typeof(standaloneTags) ==  "object") ? standaloneTags :
		{"br":1, "doctype":1, "hr":1, "img":1, "input":1, "link":1, "meta":1};
	
	var CRLFTags = {"body":1, "p":1, "div":1, "blockquote":1, "li":1, "ul":1, "ol":1};
	var stack = new Array();
	var rData = new String('');
	var elements = this.scanDom(element);

	for(var i=0; i < elements.length; i++) {
		if (elements[i].childNodes.length > 0) {
			stack.push(new Array(elements[i].nodeName, elements[i].childNodes.length));
			rData = rData.concat("<", elements[i].nodeName.toLowerCase());
			
			var attributes = this.getAttrs(elements[i], 1);
			rData = rData.concat(attributes ? " " + attributes : "", ">");
			
			if (elements[i].nodeName.toLowerCase() == 'html') {
				rData = rData.concat("\n");
			}
		}
		else {
			if (elements[i].nodeType == 1) {		
				if (elements[i].nodeName.indexOf("/") == -1) {
					if ((elements[i].nodeName == 'P' || elements[i].nodeName == 'DIV')) {
						if (!(elements[i].hasChildNodes())) {
							rData = rData.concat(this.config.outputXhtml ? "<br />" : "<br>", "\n");
						}
					}
					else {
						rData = rData.concat("<", elements[i].nodeName.toLowerCase());
						var attributes = this.getAttrs(elements[i], 1);
						var nbsp = (elements[i].nodeName == 'HEAD') ? '' : '&nbsp;';
						rData = rData.concat(attributes ? " " + attributes : "");
						rData = (!standaloneTags[elements[i].nodeName.toLowerCase()]) ?
								rData.concat(">", nbsp, "</", elements[i].nodeName.toLowerCase(), ">") :
									rData.concat(this.config.outputXhtml ? " />\n" : ">\n");
					}
				}
			}
			else {
				if (!reportOnlyTags) {
					if(elements[i].nodeType == 8) {
						rData = rData.concat("<!--", elements[i].nodeValue, "-->");
					}
					else {
						var str = elements[i].nodeValue;
						var len = str.length;
						var newStr = '';
						var nbsp = true;
						for (var j=0; j < len; j++) {
							newStr += (nbsp && str.charCodeAt(j) == 160) ? '&nbsp;' : str.charAt(j);
						}
						rData = rData.concat(str);
					}
				}
			}
			
			while ((stack.length > 0) && !(--stack[stack.length-1][1])) {
				rData = rData.concat("</", stack[stack.length-1][0].toLowerCase(), ">");
				if (CRLFTags[stack[stack.length-1][0].toLowerCase()]) {
					rData = rData.concat("\n");
				}
				stack.pop();
			}
		}
	}

	return rData;
},
	
getContents : function (op) {
    if (this.config.hrefTarget != '' || this.config.hrefTarget != null) {
        for (var i=0; i < this.doc.links.length; i++) {
            if (!this.doc.links[i].target) {
                this.doc.links[i].target = this.config.hrefTarget;
            }
        }
    }

    this.szTmp = this.doc.body.style.cssText;

    if (GB.MSIE && (this.config.ieEnterMode == 'css' || this.config.ieEnterMode == 'div')) {
        var p = this.doc.body.getElementsByTagName('P');
        var remove = new Array();
        
        for (var i=0; i < p.length; i++) {
        	if (this.config.ieEnterMode == 'css') {
        		p[i].style.margin = '0px';
        		continue;
        	}
            
            if (this.config.ieEnterMode == 'div') {
            	var div = this.doc.createElement('div');
            	
            	p[i].parentElement.insertBefore(div, p[i]);
        	
            	var attr = p[i].getAttribute('name');
            	if (attr) div.setAttribute('name', attr);
        	
            	attr = p[i].getAttribute('id');
            	if (attr) div.setAttribute('id', attr);
        	
            	attr = p[i].getAttribute('style');
            	if (attr) {
            		if (typeof attr == 'string') {
            			if (attr != '') {
            				div.setAttribute('style', attr);
            			}
            		}
            		else if (typeof attr == 'object') {
            			var css = attr.cssText.split(';');
           				for (var j=0; j < css.length; j++) {
           					var s = css[j].split(':');
           					if (s[0] && typeof s[1] != 'undefined') {
           						div.style.setAttribute(s[0], s[1]);
           					}
            			}
            		}
            	}
        	
            	div.innerHTML = p[i].innerHTML;
            	remove.push(p[i]);
            }
        }
        
        for (i=0; i<remove.length; i++) {
        	this.doc.body.removeChild(remove[i]);
        }
    }

    if (op == true) {
        var img = this.doc.images;
        var hostname = location.hostname;
        for (var i=0; i<img.length; i++) {
            if (img[i].src) {
                if (!this.config.includeHostname && img[i].src.indexOf(hostname) != -1) {
                    img[i].src = img[i].src.substring(img[i].src.indexOf(hostname) + hostname.length);
                }

                if (img[i].getAttribute("onload")) {
                    var href = img[i].parentNode;
                    if (href && href.nodeName.toUpperCase() == 'A') {
                        href.removeAttribute("target");
//                        href.setAttribute("onclick", 'return hs.run(this)');
                    }
//                    img[i].setAttribute("onload", 'javascript:addCaption(this)');
                }
            }
            else {
                img[i].removeAttribute("onload", "", 0);
            }
        }
    }

    this.doc.body.removeAttribute('contentEditable');
    var mydoc 	= new String('');
    var content = this.doc.documentElement;
	var removeTags = ['LINK', 'TITLE', 'META'];
	
	for (var i=0; i<removeTags.length; i++) {
		var tags = content.getElementsByTagName(removeTags[i]);
		for (var j=0; j < tags.length; j++) {
			if (tags[j]) tags[j].parentNode.removeChild(tags[j]);
		}
	}
	
    // mydoc = this.getHTML(content, false, false);
    if (GB.MSIE) {
        mydoc = content.outerHTML;
        mydoc = mydoc.replace(/<(\/?)strong>/ig, "<$1B>");
        mydoc = mydoc.replace(/<(\/?)em>/ig, "<$1I>");
    }
    else {
    	mydoc = '<html>'+content.innerHTML+'</html>';
    }

    mydoc = mydoc.replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;');
	this.setDesignMode(true);

    return mydoc;
},

docSplit : function (mydoc) {
    mydoc = mydoc.substr(mydoc.search(/<body/ig) + 1);
    mydoc = mydoc.substr(mydoc.indexOf('>') + 1);
    mydoc = mydoc.slice(0, mydoc.search(/<\/body/ig));
	mydoc = this.trimSpace(mydoc);
    return mydoc;
},

returnContents : function (mydoc) {
	this.setDesignMode(true);
    if (this.inputForm && this.$(this.inputForm))
        this.$(this.inputForm).value = mydoc;
    return mydoc;
},

outputHTML : function () {
    this.resetViewHTML();
    var mydoc = this.getContents(true);
    mydoc = mydoc.replace (/&amp;lt;/g, '&lt;').replace(/&amp;gt;/g,'&gt;');
    return this.returnContents(mydoc);
},

outputBodyHTML : function () {
    this.resetViewHTML();
    var str = this.docSplit(this.outputHTML());
    return this.returnContents(str);
},

outputBodyText : function () {
    this.resetViewHTML();
    return (GB.MSIE) ? this.doc.body.innerText :
        this.outputBodyHTML().replace(/<br>/ig, "\n").replace(/<[^>]+>/g, "");
},

returnFalse : function () {
    this.editArea.focus();
    var img = this.doc.images;
    for (i=0; i<img.length; i++) {
        if (img[i].src) {
            if (img[i].getAttribute("onload")) {
                img[i].onload = 'true';
            }
        }
        else {
            img[i].removeAttribute("onload", "", 0);
            img[i].removeAttribute("className", "", 0);
        }
    }
    this.setEditorEvent();
    return false;
},

trimSpace : function (str) {
	str = str ? '' + str : '';
	return str.replace(/^\s+|\s+$/g, '');
},

strLength : function (str) {
    var len = str.length;
    var mbytes = 0;
    var i = 0;

    for (; i<len; i++) {
        var c = str.charCodeAt(i);
        if (c > 128) mbytes++;
    }

    return (len-mbytes) + (mbytes*2);
},

resetViewHTML : function () {
    if (this.currentMode == 'code') {
        this.switchEditorMode('rich');
    }
},

contentsLengthAll : function () {
    this.resetViewHTML();
    return this.outputHTML().length;
},

contentsLength : function () {
    this.resetViewHTML();
    var content = this.outputBodyHTML();
    content = this.trimSpace(content);

    if (!content || content == "")
        return 0;

    return this.strLength(content);
},

inputLength : function () {
    this.resetViewHTML();
    var content = this.trimSpace(this.outputBodyText());

    if (!content || content == "")
        return 0;

    return this.strLength(content);
},

displayWindow : function (boxName) {
	this.editArea.focus();
	this.popupWinClose();
    this.boxHideAll();
    this.setSelection();

    var pullDown = this.$(boxName);
    pullDown.style.visibility = "visible";
    pullDown.style.zIndex = 1002;
},

mouseOver : function (el) { el.className = "cheditor_pulldown_mouseover"; },
mouseOut  : function (el) { el.className = "cheditor_pulldown_mouseout"; },

windowPos : function (idImg, boxName) {
    var boxEl = this.$(boxName);
   	var pNode = this.$(idImg.id).parentNode;
   	boxEl.style.left = pNode.offsetLeft + 'px';
   	boxEl.style.top  = (pNode.offsetTop + 24) + 'px';
},

boxHideAll : function () {
    for (i=0; i < GB.popupIFrame.length; i++) {
        if (this.$(GB.popupIFrame[i]+'_'+this.oname)) {
            this.$(GB.popupIFrame[i]+'_'+this.oname).style.visibility = 'hidden';
        }
    }
},

createWindow : function (width, content) {
	var div = document.createElement('div');
	div.className = 'cheditor_pulldown_container';
	div.style.width = width+'px';
	div.innerHTML = content;
	return div;
},

setColorTable : function (menu) {
    var title = '';
    switch (menu) {
    	case 'foreColor' : title = '글자색'; break;
    	case 'backColor' : title = '형광펜'; break;
    	case 'BgColor' : title = '바탕색'; break;
    }
    
    var selectedId = 'selected' + menu + '_' + this.oname;
    var strCap = '<div class="cheditor_pulldown_background"><div class="cheditor_popup_drag_handle">' +
        '<div class="cheditor_popup_title_bar"><label class="cheditor_popup_title">'+title+'</label></div></div>'+
        '<table cellpadding="1" cellspacing="2" class="cheditor_pulldown_color_table">'+
        '<tbody><tr><td colspan="10" id="'+selectedId+'" class="cheditor_pulldown_color_selected">&#160;</td></tr>';

    var colorRows = [strCap];
    var k = 0, w = 7, h = 10;
    var eCellColor = "document.getElementById('"+selectedId+"').style.backgroundColor";
    var cmd = (menu == 'backColor') ? ".changeFontColor("+eCellColor+",'back')" :
        (menu == 'foreColor' ? ".changeFontColor("+eCellColor+",'fore')" : ".changeBodyColor("+eCellColor+")");

    for (var i = 0; i < w; i++) {
        colorRows[colorRows.length] = "<tr>";
        for (var j = 0; j < h; j++) {
            colorRows[colorRows.length] = '<td onmouseover="'+this.oname+'.showColor(document.getElementById(\''+selectedId+'\'),this)" '+
                'onclick="'+this.oname+cmd+';" bgcolor="'+GB.colors[k]+'" class="cheditor_pulldown_color_cell">&#160;</td>';
            k++;
        }
        colorRows[colorRows.length] = "</tr>";

        if (i == 0 || i == 5) {
            colorRows[colorRows.length] = '<tr><td colospan="10" style="height:3px"></td></tr>';
        }
    }

    colorRows[colorRows.length] = '</tbody></table></div>';
    return colorRows.join("\n");
},

showColor : function (val, obj) {
    if (obj.bgColor) {
        val.innerHTML = val.style.backgroundColor = obj.bgColor;
    }
    else {
        val.innerHTML = '없음';
        GB.MSIE ? val.style.removeAttribute('backgroundColor') : val.style.backgroundColor = "";
    }
},

doOnKeyPress : function () {
    var oEditor = this.editArea;
    var key = oEditor.event.keyCode;

    if (key) {
        if (key == 13) {
            if (oEditor.event.shiftKey == false) {
                var rng = this.getRange();
                oEditor.event.returnValue = false;
                oEditor.event.cancelBubble = true;
                rng.pasteHTML('<br />');
                rng.select();
                rng.moveEnd("character", 1);
                rng.moveStart("character", 1);
                rng.collapse(false);
                return false;
            }
            else
                return oEditor.event.keyCode = 13;
        }
    }
},

setWinPosition : function (oWin, oWinWidth) {
	var obj = this.$('container_'+this.oname);
	var container = obj;
	var curLeft = 0;
	var curTop = 0;

	if (obj.offsetParent) {
		do {
			curLeft += obj.offsetLeft;
			curTop += obj.offsetTop;
		} while (obj = obj.offsetParent);		
	}
	
	if (GB.MSIE) curLeft /= 2;
	curLeft = (container.offsetWidth / 2) - (oWinWidth / 2) + curLeft;
	oWin.style.left = curLeft + 'px';
	oWin.style.top = curTop + 'px';
	oWin.style.width = oWinWidth + 'px';
},

popupWinLoad : function (popupInfo) {
    var container = this.$('editArea_'+this.oname);
    var titleBar = this.$('popupTitle_'+this.oname);
    if (titleBar.hasChildNodes())
        titleBar.removeChild(titleBar.firstChild);
    titleBar.appendChild(document.createTextNode(popupInfo['title']));

    var dwindow = this.popupID;
    dwindow.style.zIndex = 3007;
	this.setWinPosition(dwindow, popupInfo['boxW']);
    
    var iframe = document.createElement("iframe");
    iframe.setAttribute('frameBorder', 0);
    iframe.style.width  = '100%';
    iframe.style.border = "0px";
    iframe.setAttribute('src', this.config.editorPath + popupInfo['tmpl'] + '?r=' + Math.random());
    iframe.style.visibility = 'hidden';
    
    var cframe = this.$("cframe_"+this.oname);
    if (cframe.hasChildNodes()) cframe.removeChild(cframe.firstChild);
    cframe.appendChild(iframe);
 
    var obj = document.getElementById('container_'+this.oname).offsetParent
    var popWinResizeHeight = function () {
    	var windowHeight = (popupInfo['tmpl'] == 'insert_image.html') ?
    		iframe.contentWindow.document.getElementById('fm_insert_form').contentWindow.document.body.scrollHeight :
    			iframe.contentWindow.document.body.scrollHeight;
    		iframe.style.height = windowHeight + 'px';
    	iframe.style.visibility = 'visible';
        iframe.contentWindow.focus();

        //betty-add : admin에서 top 위치 조정
        
        //if(obj.getAttribute('class') == 'contentsWrap'){
		//var _clientH = $('body').get(0).clientHeight;
        var _clientH = screen.availHeight;
		var _top 	= (( _clientH / 2) - (windowHeight/2) - 100);
        dwindow.style.top = _top+'px';
        //}
       // alert(_clientH);
	        
    };

    if (GB.MSIE) {
        iframe.contentWindow.detachEvent("onload", popWinResizeHeight);
    	iframe.contentWindow.attachEvent("onload", popWinResizeHeight);
    }
    else iframe.onload = popWinResizeHeight;

    dwindow.style.display = 'block';
	chutil.oname = this.oname;
    
    var modalWinBg = this.$('modalWindowBackground');
    modalWinBg.style.width = document.body.clientWidth + 'px';
    modalWinBg.style.height = document.body.clientHeight + 'px';
    modalWinBg.style.display = 'block';
	modalWinBg.style.zIndex = 1000;	
	document.body.insertBefore(modalWinBg, document.body.firstChild);
	document.body.insertBefore(dwindow, document.body.firstChild);

    DragWindow.init(this.$('dragHandle_'+this.oname), dwindow);
},

popupWinClose : function () {
    if (this.popupID == null) return;
    
    this.popupID.style.display = 'none';
    this.popupID.style.zIndex = -1;
    
    this.$("cframe_"+this.oname).src = "";
    this.$('modalWindowBackground').style.display = 'none';
    this.$('modalWindowBackground').style.zIndex = -1;
    
    this.editArea.focus();
},

windowOpen : function (popupName) {
    this.editArea.focus();
    this.boxHideAll();

    if (GB.MSIE) this.setSelection();
    
    if (popupName == 'hyperLink') {
    	if (GB.MSIE) {
    		if (this.selectionType == 'None') {
    			alert('문자열을 선택하여 주십시오.');
    			return;
    		}
    	}
    }

    if (typeof(GB.popup[popupName]) != 'undefined')
        this.popupWinLoad(GB.popup[popupName]);
    else
        alert('사용할 수 없는 명령입니다.');
},

getSelection : function () {
	return (GB.MSIE) ? this.doc.selection : this.editArea.getSelection();
},

getRange : function () {
	var self = this;
	var sel = self.getSelection(), rng = null;
	
	try {
		if (sel) {
			rng = GB.MSIE ? (sel.createRange ? sel.createRange() : self.doc.createRange()) : sel.getRangeAt(0);
		}
	}
	catch (e) {}
	
	if (!rng) {
		rng = GB.MSIE ? self.doc.body.createTextRange() : self.doc.createRange();
	}
	
	return rng;
},

setSelection : function () {
    this.range = this.getRange();
    this.selectionType = this.getSelectionType(this.range);
},

setRange : function (rng) {
	if (GB.MSIE) {
		try {
			rng.select();
		}
		catch(e) {}
	}
	else {
		var sel = this.getSelection();
		if (sel) {
			sel.removeAllRanges();
			sel.addRange(rng);
		}
	}
},

getSelectionType : function (rng) {
	return rng ? (GB.MSIE ? this.doc.selection.type : rng.startContainer.nodeType) : null;
},

doCmd : function (cmd, opt) {
	var self = this;
    var rng;
    
    self.popupWinClose();
    self.boxHideAll();
    self.range = null;
    
    if (GB.MSIE) {
    	rng =  self.getRange();
    	if (self.getSelectionType(rng) == 'None') rng = self.doc;
    }
    else {
    	rng = self.doc;
    }

    if (cmd == 'Print') {
        self.editArea.print();
        return;
    }

    if (!GB.MSIE && ((cmd == 'Cut') || (cmd == 'Copy') || (cmd == 'Paste'))) {
    	if (cmd == 'PasteFromWord') {
    		cmd = 'Paste';
    	}
    	
        try {
            rng.execCommand(cmd, false, opt);
        }
        catch (e) {
            var keyboard = '';
            var command = '';
            switch (cmd) {
                case 'Cut'  : keyboard = 'x'; command = '자르기'; break;
                case 'Copy' : keyboard = 'c'; command = '복사'; break;
                case 'Paste': keyboard = 'v'; command = '붙이기'; break;
            }

            alert('사용하고 계신 브라우저에서는 \'' + command + '\' 명령을 사용하실 수 없습니다. \n' +
            '키보드 단축키를 이용하여 주세요. \(윈도 사용자: Ctrl + ' + keyboard + ', 맥킨토시 사용자: Apple + ' + keyboard + '\)')
        }

        self.editArea.focus();
        return;
    }

    try {
        if (cmd == 'PasteFromWord') {
            var tmpDoc = this.$("tmpId_" + self.oname).contentWindow;
            tmpDoc.document.execCommand("SelectAll");
            tmpDoc.document.execCommand("Paste");
            rng.pasteHTML(self.cleanFromWord(tmpDoc));
            rng.select();
        }
        else {
            rng.execCommand(cmd, false, opt);
        }
    }
    catch (e) {
        alert(cmd + ": 지원되지 않는 명령입니다.");
    }

    self.setEditorEvent();
},

cleanFromWord : function (tmpDoc) {
    for (var i=0; i < tmpDoc.document.body.all.length; i++) {
        tmpDoc.document.body.all[i].removeAttribute("className", "", 0);
    }
    
    var str = tmpDoc.document.body.innerHTML;
    var arrTmp = str.split('<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />');
    if (arrTmp.length > 1) str = arrTmp.join("");
    var arrTmp = str.split("<o:p>");
    if (arrTmp.length > 1) str = arrTmp.join("");
    var arrTmp = str.split("</o:p>");
    if (arrTmp.length > 1) str = arrTmp.join("");
    var arrTmp = str.split("<o:p>&nbsp;");
    if (arrTmp.length > 1) str = arrTmp.join("");
    var arrTmp = str.split("<P>&nbsp;</P>");
    if (arrTmp.length > 1) str = arrTmp.join("");
    var arrTmp = str.split("<P>");
    if (arrTmp.length > 1) str = arrTmp.join("");
    var arrTmp = str.split("</P>");
    if (arrTmp.length > 1) str = arrTmp.join("<br />");
    var arrTmp = str.split("<STRONG>");
    if (arrTmp.length > 1) str = arrTmp.join("");
    var arrTmp = str.split("</STRONG>");
    if (arrTmp.length > 1) str = arrTmp.join("");
    str = str.replace(/&nbsp;<br>/ig, "<br />");

    return str;
},

printPageBreak : function () {
	this.editArea.focus();
    var html = '<div style="page-break-after: always;line-height: 0px;padding: 0px;border-top: 1px #f45000 dotted;';
    html += 'border-bottom: 1px #f45000 dotted;height: 3px;font-size: 1px;margin: 5px 0px 10px 0px;"</div>';
    this.insertHTML(html);
},

doCmdPaste : function (str) {
    this.editArea.focus();
    if (GB.MSIE) {
        if (this.selectionType == "Control") return;
      //09.11.16 betty IE에서 코드표 삽입시에 스크립트 에러떠서 추가해줌 (임시)
      if(!this.range) this.range = this.getRange();
      
      this.range.pasteHTML(str);
      this.range.collapse(false);
      this.range.select();
    }
    else {
    	this.insertNodeAtSelection(str);
    }
},

setFontSize : function (elem, ptSize) {
	if (!elem) return;
	var child = elem;
	
	do {
		if (child.nodeName == 'FONT' && child.getAttribute('size') && child.getAttribute('size') == 1) {
			child.removeAttribute('size');
			child.style.fontSize = ptSize + 'pt';
		}
		
		child = child.nextSibling;
	} while (child);
	
	var children = elem.childNodes;
	
	for (var i=0; i < children.length; i++)
		this.setFontSize(children[i], ptSize);
},

doCmdPopup : function (cmd, opt) {
    this.editArea.focus();
    var rng;

    if (GB.MSIE) {
        if (this.selectionType == 'None') {
        	rng = this.doc;
        }
        else {
        	rng = this.range;
        	rng.select();
        }
    }
    else {	
        rng = this.doc;
    }

    try {
   		rng.execCommand(cmd, false, opt);
    }
    catch(e) {
    	alert(cmd + ": 지원되지 않는 명령입니다.");
    }

    this.setEditorEvent();
    this.boxHideAll();
},

insideEditor : function (el) {
    while (el != null) {
        if (el.tagName == "BODY" && el.contentEditable == "true")
            return true;
        el = el.parentElement();
    }
    return false;
},

modifyImage : function (img) {
    var a_align = new Array("baseline","top","middle","bottom","texttop","absmiddle","absbottom","left","right");
    var a_text = new Array("기준선","위쪽","가운데","아래쪽","문자열 위쪽","선택 영역의 가운데","선택 영역의 아래쪽","왼쪽","오른쪽");
    if (img.hspace < 0) img.hspace = 0;
    if (img.vspace < 0) img.vspace = 0;
    if (img.border < 0 || img.border == '') img.border = 0;
    var htmlOutput = '<table cellpadding="0" cellspacing="0" border="0"><tr>' +
        '<td width="110"><font style="font-size:9pt">가로 픽셀: <input type="text" size="3" style="font-size:9pt" value="'+img.width+'" id="n_width" />&#160;</font>\n</td>' +
        '<td width="110"><font style="font-size:9pt">가로 여백: <input type="text" size="3" style="font-size:9pt" value="'+img.hspace+'" id="n_hspace" />&#160;</font>\n</td>' +
        '<td width="200"><font style="font-size:9pt">정렬: <select id="n_alignment" name="n_alignment" style="font-size:9pt">' +
        '<option value="">없음</option>';
        for (var i=0; i<a_align.length; i++) {
            htmlOutput += '<option value='+a_align[i];
            if (img.align == a_align[i].toLowerCase()) htmlOutput += ' selected';
            htmlOutput += '>'+a_text[i]+'</option>';
        }

     htmlOutput += '</select><select id="n_alignment_caption" name="n_alignment_caption" style="display:none;font-size:9pt">'+
        '<option value="left">왼쪽</option><option value="right">오른쪽</option></select></font></td>' +
        '<td>&#160;<font style="font-size:9pt">괘선 두께: <input type="text" size="1" style="font-size:9pt" value="'+img.border+'" id="n_border" />&#160;</font>\n</td></tr>' +
        '<tr><td><font style="font-size:9pt">세로 픽셀: <input type="text" size="3" style="font-size:9pt" value="'+img.height+'" id="n_height" />&#160;</font>\n</td>' +
        '<td><font style="font-size:9pt">세로 여백: <input type="text" size="3" style="font-size:9pt" value="'+img.vspace+'" id="n_vspace" />&#160;</font>\n</td>' +
        '<td colspan="2"><font style="font-size:9pt">설명: <input type="text" size="25" id="n_alt" style="font-size:9pt" value="'+img.alt+'" />' +
        '&#160;<input type="button" name="editimg" style="height:21px;font-size:9pt;" id="editimg" value="수정" />' +
        '&#160;<input type="checkbox" name="isCaption" id="isCaption" style="background-color:#a3d260" />캡션</font>\n</td></tr></table>';

    this.$("CHModifyBlock" + this.oname).innerHTML = htmlOutput;
    this.$("isCaption").onclick = function () {
        if (document.getElementById("isCaption").checked) {
        	document.getElementById("n_alignment_caption").style.display = '';
        	document.getElementById("n_alignment").style.display = 'none';
        }
        else {
        	document.getElementById("n_alignment_caption").style.display = 'none';
        	document.getElementById("n_alignment").style.display = '';
        }
    };
    this.$("editimg").onclick = function () {
        var n_width  = document.getElementById("n_width");
        var n_height = document.getElementById("n_height");
        var n_hspace = document.getElementById("n_hspace");
        var n_vspace = document.getElementById("n_vspace");
        var n_border = document.getElementById("n_border");
        var n_alt    = document.getElementById("n_alt");

        if (n_width.value == '' || n_width.value == null || n_width.value < 1) {
            alert("가로 픽셀 크기를 입력하여 주십시오");
            return;
        }
        else if (n_height.value == '' || n_height.value == null || n_height.value < 1) {
            alert("세로 픽셀 크기를 입력하여 주십시오");
            return;
        }
        else {
            var n_align  = '';
            if (document.getElementById("n_alignment").style.display != 'none') {
                n_align = document.getElementById("n_alignment");
            }
            else {
                n_align = document.getElementById("n_alignment_caption");
            }

            img.width  = parseInt(n_width.value);
            img.height = parseInt(n_height.value);

            if (parseInt(n_hspace.value) > 0) img.hspace = parseInt(n_hspace.value);
            else img.removeAttribute("hspace", "", 0);
            if (parseInt(n_vspace.value) > 0) img.vspace = parseInt(n_vspace.value);
            else img.removeAttribute("vspace", "", 0);
            if (parseInt(n_border.value) > 0) {
                img.style.border = n_border.value+'px ' + GB.imageBorder;
                img.removeAttribute("border", "", 0);
            }
            else img.removeAttribute("style", "", 0);
            if (n_align.value != '')  img.align  = n_align.value ;
            else img.removeAttribute("align", "", 0);
            if (n_alt.value != '') img.alt = n_alt.value;
            else img.alt = '';

            if (document.getElementById("isCaption").checked) {
                var id = img.getAttribute("id");
                if (id) {
                    id = id.replace(/image/, 'thumb');
                    var lb = eval("id"+chutil.oname).document.getElementById(id);
                    if (lb) lb.onclick = 'return false';
                }
                img.className = 'chimg_photo';
                img.onload = 'true';
                alert('캡션은 에디터 안에서는 보이지 않습니다.\n글 작성 완료 후 HTML 페이지 상에서 보입니다.');
            }
            else {
                img.removeAttribute("className", "", 0);
                img.removeAttribute("onload", "", 0);
            }
        }
    }
},

modifyCell : function (cell) {
    while (cell != null && cell.tagName.toLowerCase() != "td")
        cell = cell.parentNode;

    var tbl = cell;
    var row = tbl;
    var editorPath = this.config.editorPath;

    while (tbl != null && tbl.tagName.toLowerCase() != "table") tbl = tbl.parentNode;
    while (row != null && row.tagName.toLowerCase() != "tr") row = row.parentNode;

    var t_width  = tbl.style.width  ? tbl.style.width  : tbl.width;
    var t_height = tbl.style.height ? tbl.style.height : tbl.getAttribute("height");
    var t_cellpadding = tbl.cellPadding;
    var t_cellspacing = tbl.cellSpacing;
    var t_bgcolor = tbl.getAttribute("bgcolor") ? tbl.bgColor : '';
    var t_bordercolor = tbl.getAttribute("bordercolor") ? tbl.getAttribute("bordercolor") : '';
    var t_border = tbl.getAttribute("border") ? tbl.border : '';
    var c_width = cell.getAttribute("width") ? cell.getAttribute("width") : '';
    var c_height = cell.getAttribute("height") ? cell.getAttribute("height") : '';
    var c_align = cell.getAttribute("align") ? cell.align : '';
    var c_bgcolor = cell.getAttribute("bgcolor") ? cell.bgColor : '';
    var is_ie = navigator.userAgent.toLowerCase().indexOf("msie") != -1;

    if (t_height == null) t_height = '';
    t_width = t_width.replace(/px/ig, '');
    t_height = t_height.replace(/px/ig, '');

    var html_output = '<table cellpadding="0" cellspacing="0" style="margin-top:5px;">' +
                      '<tr><td><span style="font-size:9pt;">가로 폭: <input type="text" size="4" value="'+t_width+'" id="n_width" />&#160;</span>\n</td>' +
                      '<td>&#160;<span style="font-size:9pt;">셀 패딩: <input type="text" size="1" value="'+t_cellpadding+'" id="n_cellpadding" /></span>\n</td>' +
                      '<td align="right"><span style="font-size:9pt;">테이블 배경 색: <input type="text" size="6" value="'+t_bgcolor+'" id="n_bgcolor" />&#160;</span>\n</td>' +
                      '<td>&#160;<span style="font-size:9pt;">테이블 정렬: <select id="alignment" style="font-size:9pt">' +
                      '<option value="">없음</option>' +
                      '<option value="left">왼쪽</option>' +
                      '<option value="center">가운데</option>' +
                      '<option value="right">오른쪽</option>' +
                      '</select></span></td>' +
                      '</tr><tr>' +
                      '<td><span style="font-size:9pt;">세로 폭: <input type="text" size="4" value="'+t_height+'" id="n_height" />&#160;</span>\n</td>' +
                      '<td>&#160;<span style="font-size:9pt;">셀 간격: <input type="text" size="1" value="'+t_cellspacing+'" id="n_cellspacing" /></span>\n</td>' +
                      '<td align="right"><span style="font-size:9pt;">테이블 테두리 색: <input type="text" size="6" value="'+t_bordercolor+'" id="n_bordercolor" />&#160;</span>\n</td>' +
                      '<td>&#160;<span style="font-size:9pt;">테두리 두께: <input type="text" size="1" value="'+t_border+'" id="n_border" /></span>\n</td>' +
                      '</tr><tr>' +
                      '<td><span style="font-size:9pt;">셀 가로: <input type="text" size="4" value="'+c_width+'" id="c_width" />&#160;</span>\n</td>' +
                      '<td>&#160;<span style="font-size:9pt;">가로 정렬: <select id="c_alignment" style="font-size:9pt;">' +
                      '<option value="">없음</option>' +
                      '<option value="left">왼쪽</option>' +
                      '<option value="center">가운데</option>' +
                      '<option value="right">오른쪽</option>' +
                      '<option value="justify">양쪽</option>' +
                      '</select></span></td>' +
                      '<td align="right"><span style="font-size:9pt;">셀 배경 색: <input type="text" size="6" value="'+c_bgcolor+'" id="c_bgcolor" />&#160;</span>\n</td>' +
                      '<td>&#160;<span style="font-size:9pt;">No Wrap:<input type="checkbox" value="'+t_bgcolor+'" name="nowrap" id="nowrap" />&#160;</span>\n' +
                      '<input type="button" tyle="width:54px;height:21px;font-size:9pt;" name="editcell" id="editcell" value="수정" /></td>' +
                      '</tr><tr>' +
                      '<td><span style="font-size:9pt;">셀 세로: <input type="text" size="4" value="'+c_height+'" id="c_height" />&#160;</span>\n</td>' +
                      '<td>&#160;<span style="font-size:9pt;">세로 정렬: <select id="c_valignment" style="font-size:9pt;">' +
                      '<option value="">없음</option>' +
                      '<option value=top>위쪽</option>' +
                      '<option value=middle>가운데</option>' +
                      '<option value=bottom>아래</option>' +
                      '<option value=baseline>기준선</option>' +
                      '</select></span></td>' +
                      '<td style=padding-left:12px colspan=2>' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/increasecolspan.gif" id="increasecolspan" title="ColSpan 증가" />' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/decreasecolspan.gif" id="decreasecolspan" title="ColSpan 감소" />' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/increaserowspan.gif" id="increaserowspan" title="RowSpan 증가" />' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/decreaserowspan.gif" id="decreaserowspan" title="RowSpan 감소" />&#160;&#160;&#160;&#160;' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/addcol.gif" id="addcol" title="행 삽입" />&#160;' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/addcols.gif" id="addcols" title="셀 삽입" />&#160;' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/removecol.gif" id="removecol" title="행 삭제" />&#160;' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/removecols.gif" id="removecols" title="셀 삭제" />&#160;' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/addrow.gif" id="addrows" title="열 삽입" />&#160;' +
                      '<img style="vertical-align:middle;width:20px;height:20px;cursor:pointer;" src="'+editorPath+'icons/removerow.gif" id="removerow" title="열 삭제" />' +
                      '</td></tr></table>';

    this.$("CHModifyBlock" + this.oname).innerHTML = html_output;
    this.$("nowrap").checked = cell.getAttribute("nowrap") ? true : false;

    if (tbl.getAttribute("align")) { this.$("alignment").value = tbl.getAttribute("align"); }
    if (cell.getAttribute("align")) { this.$("c_alignment").value  = cell.getAttribute("align"); }
    if (cell.getAttribute("valign")) { this.$("c_valignment").value    = cell.getAttribute("valign"); }

    this.$("editcell").onclick = function () {
        var n_width = document.getElementById("n_width");
        var n_height = document.getElementById("n_height");
        var n_align = document.getElementById("alignment");
        var n_cellpadding = document.getElementById("n_cellpadding");
        var n_cellspacing = document.getElementById("n_cellspacing");
        var n_bgcolor = document.getElementById("n_bgcolor");
        var n_border = document.getElementById("n_border");
        var n_bordercolor = document.getElementById("n_bordercolor");
        var c_width = document.getElementById("c_width");
        var c_height = document.getElementById("c_height");
        var c_bgcolor = document.getElementById("c_bgcolor");
        var c_align = document.getElementById("c_alignment");
        var c_valign = document.getElementById("c_valignment");

        tbl.border = parseInt(n_border.value);
        tbl.removeAttribute("width", 0);
        tbl.removeAttribute("height", 0);

        if (n_width.value) tbl.style.width = n_width.value;
        if (n_height.value > 0) tbl.style.height = n_height.value;

        tbl.cellPadding = n_cellpadding.value;
        tbl.cellSpacing = n_cellspacing.value;

        if (n_align.value != "") tbl.align = n_align.value;
        else if (tbl.getAttribute("align")) tbl.removeAttribute("align", 0);

        if (n_bgcolor.value) tbl.bgColor = n_bgcolor.value;
        else tbl.removeAttribute("bgcolor", 0);

        if (n_bordercolor.value) tbl.setAttribute("bordercolor", n_bordercolor.value);
        else tbl.removeAttribute("bordercolor", 0);

        if (c_width.value > 0) cell.width = c_width.value;
        if (c_height.value > 0) cell.height = c_height.value;

        cell.noWrap = document.getElementById("nowrap").checked ? true : false;

        if (c_align.value != "") cell.align = c_align.value;
        else cell.removeAttribute("align", 0);

        if (c_valign.value != "") cell.vAlign = c_valign.value;
        else cell.removeAttribute("valign", 0);

        if (c_bgcolor.value) cell.bgColor = c_bgcolor.value;
        else cell.removeAttribute("bgcolor", 0);

    }

    this.$("increasecolspan").onclick = function () { cell.colSpan++; }
    this.$("decreasecolspan").onclick = function () {
        if (cell.colSpan == 1) cell.removeAttribute("colspan", 0);
        else cell.colSpan = cell.colSpan - 1;
    }
    this.$("increaserowspan").onclick = function () { cell.rowSpan++; }
    this.$("decreaserowspan").onclick = function () {
        if (cell.rowSpan == 1) cell.removeAttribute("rowspan", 0);
        else cell.rowSpan = cell.rowSpan - 1;
    }
    this.$("addcol").onclick = function () {
        for (var i=0; i<tbl.rows.length; i++) {
            var trow = tbl.rows.item(i);
            var col = trow.insertCell(cell.cellIndex);
            if (!GB.MSIE) {
                var br = document.createElement("br");
                col.appendChild(br);
            }
        }
    }
    this.$("addcols").onclick = function () {
        var col = row.insertCell(cell.cellIndex);
        if (!GB.MSIE) {
            var br = document.createElement("br");
            col.appendChild(br);
        }
    }
    this.$("removecol").onclick = function () {
        for (var i=0; i<tbl.rows.length; i++) {
            var trow = tbl.rows.item(i);
            trow.deleteCell(cell.cellIndex);
        }
    }
    this.$("removecols").onclick = function () { row.deleteCell(cell.cellIndex); }
    this.$("addrows").onclick = function () {
        var nrow = tbl.insertRow(row.rowIndex);
        var len = row.cells.length;
        for (var i=0; i<len; i++) {
            var td = nrow.insertCell(i);
            if (!GB.MSIE) {
                var br = document.createElement("br");
                td.appendChild(br);
            }
        }
    }
    this.$("removerow").onclick = function () { tbl.deleteRow(row.rowIndex); }
},

doEditorEvent : function () {
    var self        = this;
    var statusBar   = this.$("CHstatusBar"   + self.oname);
    var modifyBlock = this.$("CHModifyBlock" + self.oname);
    var oEditor     = self.editArea;
    var cmd = null, el, pNode, ancestors = new Array();

    oEditor.focus();
    var rng = self.getRange();
    var nodeType = self.getSelectionType(rng);

    if (GB.MSIE) {
        switch (nodeType) {
        case 'Text' :
        case 'None' :
            pNode = rng.parentElement();
            break;
        case 'Control' :
            pNode = rng.item(0);
            break;
        default :
            pNode = oEditor.document.body;
        }
    }
    else {
        try {
            pNode = rng.commonAncestorContainer;
            if (!rng.collapsed &&
                rng.startContainer == rng.endContainer &&
                rng.startOffset - rng.endOffset < 2 &&
                rng.startContainer.hasChildNodes())
            {
                pNode = rng.startContainer.childNodes[rng.startOffset];
            }

            while (pNode.nodeType == 3) {
                pNode = pNode.parentNode;
            }
        }
        catch (e) { pNode= null; }
    }

    while (pNode && (pNode.nodeType == 1) && (pNode.tagName.toLowerCase() != 'body')) {
        ancestors.push(pNode);
        if (pNode.tagName.toLowerCase() == 'img' && (pNode.src.indexOf('/icons/em/') == -1)) {
            cmd = 'img';
            break;
        }
        else if (pNode.tagName.toLowerCase() == 'td') {
            cmd = 'td';
            break;
        }
        pNode = pNode.parentNode;
    }

    ancestors.push(oEditor.document.body);

    if (cmd != null) {
        switch (cmd) {
        case "img" :
            modifyBlock.style.display = "block";
            self.modifyImage(pNode);
            break;
        case "td" :
            modifyBlock.style.display = "block";
            self.modifyCell(pNode);
            break;
        }
    }
    else {
        modifyBlock.style.display = "none";
        modifyBlock.innerHTML = '';
    }

    if (typeof(statusBar) != 'undefined') {
        statusBar.innerHTML = '';
        statusBar.appendChild(document.createTextNode('<html> <body> '));

        while (el = ancestors.pop()) {
            if (!el || el.tagName.toLowerCase() == 'html' || el.tagName.toLowerCase() == 'body')
                continue;

            var tag = el.tagName.toUpperCase();
            var a = document.createElement("a");
            a.href = "javascript:void%200";
            a.el = el;
            a.className = 'cheditor_tag_path';
            a.title = el.style.cssText;
            a.onclick  = function () { this.$('removeSelected').style.display = 'inline'; self.tagSelector(this.el); };
            a.appendChild(document.createTextNode(tag.toLowerCase()));
            statusBar.appendChild(document.createTextNode('<'));
            statusBar.appendChild(a);
            statusBar.appendChild(document.createTextNode('> '));
        }

        var remove = document.createElement("a");
        remove.href = "javascript:void%200";
        remove.id = "removeSelected";
        remove.style.display = 'none';
        remove.className = 'cheditor_tag_path';
        remove.style.color = '#cc3300';
        remove.appendChild(document.createTextNode('remove'));
        remove.onclick = function () {  oEditor.document.execCommand("RemoveFormat", false, null);
                                        remove.style.display = 'none';
                                        oEditor.focus();
                                        self.doEditorEvent(); };

        var span = document.createElement('span');
        span.style.marginTop = '2px';
        span.appendChild(remove);
        this.$("CHstatusBar" + self.oname).appendChild(span);
    }
},

tagSelector : function (node) {
    this.editArea.focus();
    var rng;

    if (GB.MSIE) {
    	rng = this.doc.body.createTextRange();
        if (rng) {
            rng.moveToElementText(node);
            rng.select();
        }
    }
    else {
        var sel = this.editArea.getSelection();
        if (typeof(sel) == 'undefined')
            return;
        try {
            rng = sel.getRangeAt(0);
        }
        catch(e) { return; }
        
        rng.selectNodeContents(node);
        sel.removeAllRanges();
        sel.addRange(rng);
    }
},

$ : function (id) { 
	return document.getElementById(id); 
}

//----------------------------------------------------------------
};

var DragWindow = {
	obj : null,
	init : function (o, oRoot, minX, maxX, minY, maxY) {
		o.onmousedown = DragWindow.start;
		o.onmouseover = function () { this.style.cursor = 'move'; };
		o.hmode = true ;
		o.vmode = true ;
		o.root = oRoot && oRoot != null ? oRoot : o;
		o.transId = oRoot.id + '_Trans';

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX = typeof minX != 'undefined' ? minX : null;
		o.minY = typeof minY != 'undefined' ? minY : null;
		o.maxX = typeof maxX != 'undefined' ? maxX : null;
		o.maxY = typeof maxY != 'undefined' ? maxY : null;

		o.root.onDragStart 	= new Function();
		o.root.onDragEnd  	= new Function();
		o.root.onDrag    	= new Function();
	},

	start : function (e) {
		var o = DragWindow.obj = this;
		e = DragWindow.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX = e.clientX;
		o.lastMouseY = e.clientY;

		document.onmousemove = DragWindow.drag;
		document.onmouseup   = DragWindow.end;
		
		if (o.root.lastChild.id == o.transId) return false;
		
		var dragTransBg = document.createElement('div');
		dragTransBg.className = 'cheditor_dragWindowTransparent';
		dragTransBg.id = o.transId;
		dragTransBg.style.width = o.root.lastChild.firstChild.style.width;
		dragTransBg.style.height = o.root.lastChild.firstChild.style.height;
		o.root.appendChild(dragTransBg);
		
		return false;
	},

	drag : function (e) {
		e = DragWindow.fixE(e);
		var o = DragWindow.obj;
		var ey = e.clientY;
		var ex = e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		DragWindow.obj.root.style.left = nx + "px";
		DragWindow.obj.root.style.top = ny + "px";
		DragWindow.obj.lastMouseX  = ex;
		DragWindow.obj.lastMouseY  = ey;
		DragWindow.obj.root.onDrag(nx, ny);

		return false;
	},

	end : function () {
		document.onmousemove = null;
		document.onmouseup   = null;
		DragWindow.obj.root.onDragEnd(parseInt(DragWindow.obj.root.style[DragWindow.obj.hmode ? "left" : "right"]), 
				parseInt(DragWindow.obj.root.style[DragWindow.obj.vmode ? "top" : "bottom"]));

		if (DragWindow.obj.root.lastChild.id == DragWindow.obj.transId)
			DragWindow.obj.root.removeChild(DragWindow.obj.root.lastChild);
		DragWindow.obj = null;
	},

	fixE : function (e) {
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

