/**
 * @fileoverview
 * cafenAttach v21 레인에디터의 각종 함수입니다.
 * 당 프로그램의 저작권은 http://cafen.net (outmind@cafen.net)에 있습니다
 * 당 프로그램의 수정 후 재 배포는 저작권자의 허락을 득한 후 재배포 할수 있습니다. 
 * 당 프로그램의 이용은 비 상업적인 목적의 경우 무료로 이용할 수 있습니다.
 * 당 프로그램의 이용은 상업적인 목적의 경우 저작권자의 허락을 득한 후 이용할 수 있습니다.
 * 당 프로그램의 설치후 관리자는 outmind@cafen.net 으로 설치하였다는 통보 메일을 발송하여야 합니다.
 * 당 프로그램안에 있는 모든 저작권 표시 영역은 수정할수 없습니다.
 *
 * ------------------------------------------------
 * 설치 방법은 함께 배포된 README 파일 참조 바랍니다.
 * ------------------------------------------------
 *
 * @author Kimjonggab(outmind@cafen.net)
 * @copyright Copyright (c) 2004 Cafen.net (http://cafen.net)
 */


if (typeof SWFUpload == 'undefined') {
	if (cafen.srartLoad)
		cafen.srartLoad(_cafen_service_url+'swfupload.js');
	else
		document.write('<scr'+'ipt TYPE="text/JavaScript" charset="utf-8" LANGUAGE="JavaScript1.2" SRC="'+_cafen_service_url+'swfupload.js"></scr'+'ipt>');
}

var cafenAttach_loader = {
/**
 * 레인 에디터 환경변수
 * @type object
 */
	editorBaseConf : {
		editorURL : _cafen_service_url,
		imageURL : _cafen_service_url + '/images/',
		uploadSCRIPT : null,
		downloadSCRIPT : null,
		uploadURL : cafen.getDomain() +'/uploads/',
		uploadedURL : null,
		uploadDOMAIN : cafen.getDomain(),
		callbackURL : '',
		middlebarset : 'base',
		editorClassName : 'cafenAttachContents',
		editorStyleSheet : _cafen_service_url +'images/blank.css',
		maxUploadSize : 1024*1024*5,
		maxMovieSize : 1024*1024*20,
		maxFileBoxSize : 1024*1024*1,
		singleUploadSize : Math.round(1024*1024*1.5),
		maxFileBoxCnt : 50,
		xmlParse : false,
		usesimpleparser : true,
		useFilebox : true,
		useMediaPlayer : true,
		useImageEditor : true,
		mediaPlayer : {
			logo : _cafen_service_url +'images/logo_media.png',
			backColor : '0x000000',
			frontColor : '0xccCCCC'
		},
		attachAs : false
	},
/**
 * 레인 에디터 환경변수 체크 여부
 * @type boolean
 */
	cafenAttach_check	: false,
/**
 * 레인 에디터 객체 적재
 * @type array
 */
	childNodes : [],
/**
 * Popup 오프젝트
 * @type class
 */
	out_popupobj : null,
/**
 * Popup 오프젝트 콜백
 * @type function
 */
	out_callback : function() {},
/**
 * 이미지 싸인
 * @type string
 */
	img_sign : '',
	navigator_check : null,
	checkNavigator : function() {
		if (this.navigator_check == null) {
			if (navigator.userAgent.indexOf('MSIE') > 0) {
				var ie_version = parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('MSIE') + 5, navigator.userAgent.indexOf('MSIE') + 8));
				this.navigator_check = (ie_version < 5.5) ? false : true;
			} else
				this.navigator_check = true;
		}
		return this.navigator_check;
	},
/**
 * 에디터 환경 체크
 * @return {boolean}
 */
	check : function() {
		if (this.cafenAttach_check) {
			return true;
		} else {
			if (typeof cafenGlobalConf != 'undefined')
				this.editorBaseConf = cafen.extend(this.editorBaseConf,cafenGlobalConf);
			if (this.editorBaseConf.editorURL == null) {
				this.showMsg('설치 안내',' cafenGlobalConf.editorURL 이 설정되지 않았습니다.');
				return false;
			} else if (!this.checkNavigator()) {
				return false;
			} else {
				if (this.checkDomain()) {
					cafen.Attach.Upload.base_upload_script = this.editorBaseConf.uploadSCRIPT;
					cafen.Attach.Upload.base_upload_url = this.editorBaseConf.uploadURL;
					cafen.Attach.Upload.base_uploaded_url = this.editorBaseConf.uploadedURL;
					cafen.Attach.Upload.base_upload_domain = this.editorBaseConf.uploadDOMAIN;
					cafen.Attach.Upload.flash_path = this.editorBaseConf.imageURL;
					cafen.Attach.Upload.base_image_url = this.editorBaseConf.imageURL;
					cafen.Attach.baseConf._editor_url = this.editorBaseConf.editorURL;
					cafen.Ajax_basexmlurl = this.editorBaseConf.uploadSCRIPT;
					cafen.Attach.Upload.use_mediaplayer = this.editorBaseConf.useMediaPlayer;
					cafen.Attach.Upload.use_imageeditor = this.editorBaseConf.useImageEditor;
					cafen.Attach.Upload.mediaplayer_info = this.editorBaseConf.mediaPlayer;
					cafen.SwfUpload.singleupload_max = Math.min(this.editorBaseConf.singleUploadSize,this.editorBaseConf.maxUploadSize);
				} else {
					cafen.Attach.Upload.base_upload_script = '';
					cafen.Attach.Upload.base_upload_url = '';
					cafen.Attach.Upload.base_upload_domain = '';
					cafen.Attach.Upload.flash_path = '';
					cafen.Attach.Upload.base_image_url = '';
					cafen.Attach.baseConf._editor_url = '';
					cafen.Attach.Upload.use_mediaplayer = '';
					cafen.Attach.Upload.use_imageeditor = '';
					cafen.Attach.Upload.mediaplayer_info = '';
					cafen.SwfUpload.singleupload_max = 0;
				}
				cafen.Attach.baseConf.middlebarskin = cafen.extend(cafen.Attach.baseConf.middlebarskin, this.editorBaseConf.middlebarSet);
				cafen.Attach.baseConf.skin = cafen.extend(cafen.Attach.baseConf.skin, this.editorBaseConf.skinSet);
				this.cafenAttach_check = true;
				return true;
			}
		}
	},
/**
 * 업로드 스크립터 체크
 * @return {string} 업로드 파일 위치
 */
	getUploadScript : function() {
		if (_editor_url.indexOf('http://') == 0 || _editor_url.indexOf('/') == 0) 
			return _editor_url ;
		else {
			return document.location.pathname.substring(0,document.location.pathname.lastIndexOf('/') + 1) +_editor_url;
		}
	},
/**
 * 크로스 도메인 체크
 * @return {boolean} true|false
 */
	checkDomain : function() {
		this.checkCallBack()
		this.checkUploadURL();
		if (this.editorBaseConf.uploadSCRIPT == null || this.editorBaseConf.uploadSCRIPT == '')
			return false;
		else if (this.editorBaseConf.uploadSCRIPT.indexOf('http://') == 0) {
			return true;
		} else {
			if (this.editorBaseConf.uploadSCRIPT.indexOf('/') != 0) {
				var theUrl = window.location.href.split('/'); 
				theUrl.pop(); 
				theUrl.push(this.editorBaseConf.uploadSCRIPT); 
				this.editorBaseConf.uploadSCRIPT = theUrl.join('/'); 
			}
			return true;
		}
	},
	checkUploadScript : function() {
		if (this.editorBaseConf.uploadSCRIPT == null || this.editorBaseConf.uploadSCRIPT == '')
			return false;
		else
			return true;
	},
/**
 * CallBack 체크
 * @return {boolean}
 */
	checkCallBack : function() {
		if (this.editorBaseConf.callbackURL.indexOf('http://') == 0) 
			return true;
		else if (this.editorBaseConf.callbackURL.indexOf('/') == 0) {
			this.editorBaseConf.callbackURL = cafen.nodeUtil.getDomain() + this.editorBaseConf.callbackURL;
			return true;
		} else if (this.editorBaseConf.callbackURL != '') {
			var theUrl = window.location.href.split('/'); 
			theUrl.pop(); 
			theUrl.push(this.editorBaseConf.callbackURL); 
			this.editorBaseConf.callbackURL = theUrl.join('/'); 
			return true;
		}
	},
/**
 * UploadScript 체크
 * @return {boolean}
 */
	checkUploadURL : function () {
		if (this.editorBaseConf.uploadURL.indexOf('http://') == 0) 
			return true;
		else if (this.editorBaseConf.uploadURL.indexOf('/') == 0) {
			this.editorBaseConf.uploadURL = cafen.getDomain() + this.editorBaseConf.uploadURL;
			return true;
		} else if (this.editorBaseConf.uploadURL != '') {
			var theUrl = window.location.href.split('/'); 
			theUrl.pop(); 
			theUrl.push(this.editorBaseConf.uploadURL); 
			this.editorBaseConf.uploadURL = theUrl.join('/'); 
			return true;
		}
		
	},
	msgShown : false,
/**
 * 메세지 보이기
 * @param {string} msg 보일 메세지
 */
	showMsg : function(title, msg) {
		if (!this.msgShown) {
			msg = msg.replace(/<br>/gi,'\r\n');
			if (typeof msg.stripTags == 'function')
				msg = msg.stripTags();
			var html = 'Editor [' + title + ']\r\n'
				+ '--------------------------------------------------------------------------------------\r\n'
				+ msg + '\r\n'
				+ '--------------------------------------------------------------------------------------\r\n';
			alert(html);
			this.msgShown = true;
		}
	},
/**
 * 레인에디터 적재
 * @param {object} objname 객체명
 * @param {object} userConfig 환경파일
 */
 	load : function(objname, userConfig) {
 		var obj = null;
		if (this.checkNavigator()) {
			obj = new cafen.Attach(objname, userConfig);
			this.childNodes.push({obj:obj,name:objname});
		} else 
			obj = null;
		return obj;
	},
/**
 * 레인에디터 객체 가져오기
 * @param {string} objname 가져올 객체명
 * @return {cafen.Attach} 에디터 객체
 */
	get : function(objname) {
		for(var i = 0; i < this.childNodes.length; i++) {
			if (obj.name == objname) {
				return obj;
				break;
			}
		}
		return null;
	}
}


function cafenAttach() {
}

cafenAttach.prototype = {
/**
 * 에디터 랜드링하기
 * @param {object}
 */
	render : function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = arguments[i];
			if (typeof element == 'string')
				element = document.getElementById(element);
			if (element != null)
				this._renderElement(element);
		}
	},
	renderElements : function(renderObjs) {
		for(var i=0; i < renderObjs.length; i++) 
			this.renderElement(renderObjs[i]);
	},
/**
 * 에디터 랜드링하기
 * @param {object}
 */
	renderElement : function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = arguments[i];
			if (typeof element == 'string')
				element = document.getElementById(element);
			if (element != null)
				this._renderElement(element);
		}
	},
/**
 * 에디터 랜드링하기
 * @param {object}
 */
	_renderElement : function(editorObj) {
		if (typeof editorObj.parse != 'undefined')
			return ;
		cafenAttach_loader.check();
		var textAttribObj = new cafen.Attribute(editorObj);
		var config = {
			width : textAttribObj.get('width',editorObj.offsetWidth),
			height : textAttribObj.get('height',editorObj.offsetHeight),
			attachfile_max : textAttribObj.getInt('attachfile_size',1024*1024*10),
			onefile_max : textAttribObj.getInt('onefile_size',0),
			attachfile_cnt : textAttribObj.getInt('attachfile_cnt',20),
			data : textAttribObj.get('oldvalue',null),
			img_sign : textAttribObj.get('usesign',''),
			middlebarset : textAttribObj.get('middlebar',''),
			attachfile_type : textAttribObj.get('attachfile_type','all'),
			attachfile_mode : textAttribObj.getBoolean('attach',true),
			skin : textAttribObj.get('skin','white'),
			canbe_resize : textAttribObj.getBoolean('resize',false) ,
			showattachsize : textAttribObj.getInt('showattachsize',0),
			use_unloadevent : textAttribObj.getBoolean('unloadevent',false),
			onstartclose : textAttribObj.getBoolean('onstartclose',false),
			attachAs : textAttribObj.getBoolean('attachas','null'),
			simpleParse : textAttribObj.getBoolean('simpleparser','null')
		};
		var obj = new cafen.Attach(editorObj, config);
		if (obj == null) {
			editorObj.parse = function() { return (this.value.split(' ').join('') != '')? true : false;}
			editorObj.setUnload = function(bl) {}
			editorObj.getAttach = function() { return ''; }
			editorObj.getAttachSize = function() { return 0; }
			editorObj.getAttachCnt = function() { return 0; }
			editorObj.getAttachImage = function() { return 0; }
		}
	},
	/**
	* render Elements by className
	* @param {string}  className The class name of the Object to do render
	*/
	renderElementsByClassName : function(className) {
		var objs = document.getElementsByTagName('textarea');
		var editorObjs = [];
		for(var i =0; i < objs.length; i++) {
			var child = objs[i];
			if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) 
				editorObjs.push(child);
		}
		this.renderElements(editorObjs);
	},
	/**
	* render Elements by id
	* @param {string}  id The id of the Object to do render
	*/
	renderElementsById : function(id) {
		if (document.getElementById(id) != null) {
			var editorObjs = [];
			var objs = document.getElementsByTagName(document.getElementById(id).tagName);
			for(var i=0;i<objs.length;i++){
				if(objs[i].id==id) 
					editorObjs.push(objs[i]);
			}
			this.renderElements(editorObjs);
		}
	},
	/**
	* render Elements by className
	* @param {string}  className The class name of the Object to do render
	*/
	renderElementsByName : function(objName) {
		var objs = document.getElementsByTagName('textarea');
		var editorObjs = [];
		for(var i =0; i < objs.length; i++) {
			var child = objs[i];
			if (child.getAttribute('name') == objName) 
				editorObjs.push(child);
		}
		this.renderElements(editorObjs);
	}
}


cafen.Attach = function(id, config) {
	this.setOptions({tag : 'div', attribute :{}, style : {width :'auto', height:'auto'}});
	this.initAttach(id, config);
}

cafen.Attach.prototype = cafen.extendClass({
	version : 'A21',
	initAttach : function(id, config) {
		this.obj = cafen.$(id);
		if (this.obj.getAttribute('type') == 'file') {
			config.attachfile_cnt = 1;
			config.onstartclose = true;
			var tmpObj = document.createElement('input');
			tmpObj.setAttribute('type', 'text');
			var copyAttribute = ['name', 'size', 'class','oldvalue','require','title'];
			for(var i = 0; i < copyAttribute.length; i++) {
				var attribName = copyAttribute[i];
				var attribValue = this.obj.getAttribute(attribName);
				if (attribValue != null) 
					tmpObj.setAttribute(attribName, attribValue);
			}
			this.obj.parentNode.insertBefore(tmpObj,this.obj);
			var copyStyle = ['width', 'height'];
			for(var i = 0; i < copyStyle.length; i++) {
				var styleName = copyStyle[i];
				var styleValue = this.obj.style[styleName];
				if (typeof styleValue == 'string') {
					try {
						tmpObj.style[styleName] = styleValue ;
					} catch(ex) {}
				}
			}
			this.obj.parentNode.removeChild(this.obj);
			this.obj = tmpObj;
		}
		if (!cafenAttach_loader.check()) {
			this.obj.parse = function() {return true;};
			this.obj.setUnload = function() {};
			this.obj.getAttach = function() {};
			this.obj.getAttachSize = function() {};
			this.obj.getAttachCnt = function() {};
			this.obj.getAttachImage = function() {};
			this.obj.setSize = function(w, h) {this.style.width = w+'px';this.style.height = h+'px';}
			return ;	
		}
		cafen.checkStyle();
		this._editorObject = {};
		try {
			this.obj.parentNode.insertBefore(this.getElement(), this.obj);
		} catch(ex) {
			this.obj.insertAdjacentElement("beforeBegin",this.getElement())
		}
		this.config = new 	cafen.Attach.Config(this, config);
		this.obj.style.display = 'none';
		this._editorObject.editorSkin = new cafen.TableAuto({attribute : {width : this.config.width}, style : {width :(this.config.width) +'px', height : 'auto'}});
		this.appendChild(this._editorObject.editorSkin);
		this._editorObject.editorPopup = new cafen.XWindow();
		this.appendChild(this._editorObject.editorPopup);
		if (this.config.attachfile_max > 0) {
			this._editorObject.AttachAreaOut = new cafen.TableAuto({className : this.getClassName('buttonarea'), align:'left', attribute : {border:0},style : {width:(this.config.width -6) +'px', position : 'relative'}});
			this._editorObject.editorSkin.addRow(this._editorObject.AttachAreaOut);
			this._editorObject.AttachAreaOut.addRow();
			this._editorObject.editorAttachArea = new cafen.TableAuto({align:'left', attribute : {border:0},style : {width:(this.config.width -29) +'px', position : 'relative'}});
			this._editorObject.AttachAreaOut.addCell(this._editorObject.editorAttachArea);
			this._editorObject.attachToggle = new cafen.XIcon({icon:'r_winset', off :60, on : 14,  over :45, style:{width: '15px', height: '14px'}, event:{click : this.toggleAttach.bind(this)}})
			this._editorObject.AttachAreaOut.addCell(this._editorObject.attachToggle);
			this._editorObject.AttachAreaOut.addStyle({width:'17px', verticalAlign: 'bottom'});
		}
		if (this._editorObject.editorAttachArea != null)
			this.drawAttachMenu();
		if (this.config.use_unloadevent)
			this.setloadUnload(true);
		this.obj.parse = this.end.bind(this);
		this.obj.setUnload = this.setloadUnload.bind(this);
		if (this.editorAttachView != null) {
			this.obj.getAttach = this.editorAttachView.parse.bind(this.editorAttachView);
			this.obj.getAttachSize = this.editorAttachView.getAttachSize.bind(this.editorAttachView);
			this.obj.getAttachCnt = this.editorAttachView.getAttachCnt.bind(this.editorAttachView);
			this.obj.getAttachImage = this.editorAttachView.getImageCnt.bind(this.editorAttachView);
		} else {
			this.obj.getAttach = function() {};
			this.obj.getAttachSize = function() {};
			this.obj.getAttachCnt = function() {};
			this.obj.getAttachImage = function() {};
		}
		this.obj.setSize = this.setSize.bind(this);
		if (this.obj.form != null) {
			if (!(this.obj.form.submitqueue instanceof Array)) 
				this.obj.form.submitqueue = [];
			this.obj.form.submitqueue.push(this.end.bind(this));
			
			if (typeof this.obj.form.onsubmit == 'function' && this.obj.form.oldonsubmit == null) {
				this.obj.form.oldonsubmit = this.obj.form.onsubmit;
				this.obj.form.onsubmit = null;
			} else if (this.obj.form.oldonsubmit == null) {
				this.obj.form.oldonsubmit = function() {return true;};
				this.obj.form.onsubmit = null;
			}
			if (this.obj.form.onsubmit == null) {
				this.obj.form.onsubmit = function() {
					if (this.submitqueue.length > 0) {
						for(var i = 0; i < 	this.submitqueue.length; i++) {
							if (!this.submitqueue[i]())
								return false;
						}
					}
					if (this.oldonsubmit != null)
						return this.oldonsubmit();
					else
						return true;
				}
			}
		}
	},
	getUploadScript : function() {
		return cafenAttach_loader.editorBaseConf.uploadSCRIPT;
	},
	getUploadUrl : function() {
		return cafenAttach_loader.editorBaseConf.uploadURL;
	},
	getUploadedUrl : function() {
		return cafenAttach_loader.editorBaseConf.uploadedURL;
	},
	getMediaPlayerParam : function(use_logo) {
		var params = '';
		if (use_logo && cafenAttach_loader.editorBaseConf.mediaPlayer.logo != '')
			params += '&amp;logo=' + cafenAttach_loader.editorBaseConf.mediaPlayer.logo;
		if (cafenAttach_loader.editorBaseConf.mediaPlayer.backColor != '')
			params += '&amp;backcolor=' + cafenAttach_loader.editorBaseConf.mediaPlayer.backColor;
		if (cafenAttach_loader.editorBaseConf.mediaPlayer.frontColor != '')
			params += '&amp;frontcolor=' + cafenAttach_loader.editorBaseConf.mediaPlayer.frontColor;
		return params;
	},
	end : function(bl) {
		this.obj.value = this.editorAttachView.parse(true);
		if (!bl)
			this.setloadUnload(false);
		return true;
	},
	setloadUnload : function(bl) {
		cafen.setloadUnload(bl, cafenMsg.get('ed_0116'));
	},
	drawAttachMenu : function() {
		this._editorObject.editorAttachArea.addRow();
		this.editorAttachScale = new cafen.Attach.AttachScale(this);
		this._editorObject.editorAttachArea.addCell(this.editorAttachScale);
		this._editorObject.editorAttachArea.addStyle({textAlign:'left'});
		this._editorObject.editorAttachArea.addRow();
		this.editorAttachView = new cafen.Attach.AttachFile(this);
		this._editorObject.editorAttachArea.addCell(this.editorAttachView);
		if (	this.config.onstartclose)
			this.toggleAttach();
		if (this.config.delayRender == 0)
			this.onLoad();
		else
			window.setTimeout(this.onLoad.bind(this), this.config.delayRender);
	},
	onLoad : function() {
		if (this.editorAttachView != null) {
			this.editorAttachView.onload();
			this.editorAttachView.initFiles(this.config.attachtxt);
			if (this.config.onstartclose && this.config.toogleSatus.attach)
				this.toggleAttach();
		}
	},
	execCommand : function(cmd, bl, value) {
		this._lastCommandObj = null;
		this._lastCommand = null;
		switch(cmd.toLowerCase()) {
			case 'attach' :
				if (value !=undefined && this.editorAttachView.chkUploadSize(value.size)) {
					this.editorAttachView.addFile(value);
					this.editorAttachView.updateScale();
					return true;
				} else
					return false;
				break;
		}
		return true;
	},
	getClassName : function(part) {
		switch(part) {
			case 'tab' : 
				return this.config.color_info.class_Tab;
				break;
			case 'box' :
				return this.config.color_info.class_Box;
				break;
			case 'buttonarea' :
				return this.config.color_info.class_ButtonArea;
				break;
			case 'editorarea' :
				return this.config.color_info.class_Editor;
				break;
			case 'buttonbg' :
				return this.config.color_info.class_Button;
				break;
			case 'scale' :
				return this.config.color_info.class_Scale;
				break;
			case 'attachbutton' :
				return this.config.color_info.class_Attach;
				break;
			case 'attach' :
				return _cafen_service_url+'images/'+ this.config.color_info.attachImg;
			default :
				return '';
				break;
		}
	},
	showContents : function(contents, contentstype) {
		if (this._editorObject.contentsViewer == null) 
			this._editorObject.contentsViewer = new cafen.Attach.contentsViewer(this);
		switch(contentstype) {
			case 'image' :
				this._editorObject.contentsViewer.setImage(contents);
				break;
			case 'imageeditor' :
				this._editorObject.contentsViewer.setImageEditor(contents);
				break;
			case 'movie' :
				this._editorObject.contentsViewer.setMovie(contents);
				break;
			case 'movieeditor' :
				this._editorObject.contentsViewer.setMovieEditor(contents);
				break;
			case 'map' :
				this._editorObject.contentsViewer.setMap(contents);
				break;
		}
	},
	toggleAttach : function() {
		this._editorObject.attachToggle.isSelected = !this._editorObject.attachToggle.isSelected;
		this._editorObject.attachToggle.setSelected(this._editorObject.attachToggle.isSelected);
		if (!this._editorObject.attachToggle.isSelected) {
			this.config.toogleSatus.attach = true;
			this.editorAttachView.show();
		} else {
			this.config.toogleSatus.attach = false;
			this.editorAttachView.hide();
		}
//		this.setEditorHeight(this.config.height);
	},
	showConfirm : function(msg, bindFn, pos) {
		if (this._editorObject.confirm == null) {
			this._editorObject.confirm = new cafen.XConfirm({title :cafenMsg.get('com_confirm'), contents :'', sticker : {obj : this._editorObject.editorSkin, x : 'center', y : 'top'}, style : {width: '300px'}, onClose : this.getConfirm.bind(this)});
			this._editorObject.confirm.setContents(msg);
			this._editorObject.editorPopup.addChild(this._editorObject.confirm);
		}
		this._lastConfirmFnc = bindFn;
		this._editorObject.confirm.setContents(msg, pos ? {y : 'top', plus : [0, 40]} : {y : 'top', plus : [0, 40]});
		this._editorObject.confirm.onLoad();
	},
	getConfirm : function(bl) {
		if (this._lastConfirmFnc != null)
			this._lastConfirmFnc(bl);
		this._lastConfirmFnc = null;
	},
	getPaddingText : function(txt) {
		return '<div style="padding:5px;line-height:130%;text-align:center">'+txt+'</div>';
	},
	showMsg : function(msg, pos) {
		if (this._editorObject.alert == null) {
			msg = this.getPaddingText(msg);
			this._editorObject.alert = new cafen.XAlert({title :cafenMsg.get('com_alert'), contents :'', sticker : {obj : this._editorObject.editorSkin, x : 'center', y : 'top'}, style : {width: '300px'}});
			this._editorObject.alert.setContents(msg, null);
			this._editorObject.editorPopup.addChild(this._editorObject.alert);
		}
		this._editorObject.alert.setContents(msg, pos ? {y : 'top', plus : [0, 40]} : {y : 'top', plus : [0, 40]});
		this._editorObject.alert.onLoad();
	}
},cafen.Element.prototype);


cafen.Attach.AttachScale = function(obj) {
	this._editorObj = obj;
	this.baseWidth = this._editorObj.config.width -124;
	this.maxUpload = this._editorObj.config.attachfile_max;
	this.setOptions({tag : 'div', attribute :{}, style : {width :(this._editorObj.config.width-35)+'px', height:'22px', marginLeft : '8px'}});
	this.initAttachScale()
}


cafen.Attach.AttachScale.prototype = cafen.extendClass({
	initAttachScale : function() {
		var tmpTable = new cafen.TableAuto({style : {width : 'auto', tableLayout :'fixed'}});
		this.appendChild(tmpTable);
		tmpTable.addCell();
		tmpTable.addStyle({backgroundPosition: '1px -40px', fontSize : '1px', width:'2px', lineHeight:'1px'});
		tmpTable.addAttribute({className : this._editorObj.getClassName('scale')});
		tmpTable.addText('&nbsp;');
		this._scalePointer = new cafen.Div({attribute :{className : this._editorObj.getClassName('scale')}, style : {width :(this.baseWidth +10)+'px', height:'20px', backgroundPosition : '-1000px 0',backgroundColor : 'transparent', backgroundRepeat : 'no-repeat'}});
		tmpTable.addCell(this._scalePointer);
		tmpTable.addStyle({verticalAlign: 'bottom'});
		this._uploadPointer = new cafen.Div({attribute :{className : this._editorObj.getClassName('scale')}, style : {width :(this.baseWidth +10)+'px', height:'20px', backgroundPosition : '-1000px -20px',backgroundColor : 'transparent', backgroundRepeat : 'no-repeat'}});
		this._scalePointer.appendChild(this._uploadPointer);

		tmpTable.addCell();
		tmpTable.addStyle({backgroundPosition: '-2px -40px', fontSize : '1px', width:'2px', lineHeight:'1px'});
		tmpTable.addAttribute({className : this._editorObj.getClassName('scale')});
		tmpTable.addText('&nbsp;');
		var iconMargin = '0 0 0 1px';
		this.attachFileButton  = new cafen.Div({style:{width:'72px', height:'22px', margin : iconMargin, overflow: 'hidden', overflowX : 'hidden', overflowY : 'hidden'},attribute :{unselectable : 'on'}});
		this._attachStatus = tmpTable.addCell(this.attachFileButton);
		tmpTable.addStyle({width:'80px', paddingLeft :'3px'});
		this.setScale(50,1024*1024*5, 1024*1024*10);
	},
	reSize : function() {
		this.baseWidth = this._editorObj.config.width -130;
		this.setStyle({width : (this._editorObj.config.width-35) +'px'});
		this._scalePointer.setStyle({width : (this.baseWidth+10) +'px'});
		this._uploadPointer.setStyle({width : (this.baseWidth+10) +'px'});
	},
	setProcessRemote : function(bl) {
		if (this.setProcessRemoteTimer != null) 
    		window.clearTimeout(this.setProcessRemoteTimer);
    	if (bl) {
			this.processSeqn = 0;
			if (this.setProcessRemoteTimeoutBind == null)
				this.setProcessRemoteTimeoutBind = this.setProcessRemoteTimeout.bind(this);
			this.setProcessRemoteTimeout();
		}
	},
	setProcessRemoteTimeout : function() {
		this.processSeqn += 2;
		this.processSeqn = this.processSeqn % 200;
		var po = (this.processSeqn > 100) ? (this.baseWidth * (200 - this.processSeqn) / 100) : (this.baseWidth * this.processSeqn / 100);
		this._uploadPointer.setStyle({backgroundPosition : (po-1000) + 'px -20px'});
		this.setProcessRemoteTimer = window.setTimeout(this.setProcessRemoteTimeoutBind, 50);
	},
	setScale : function(per, useSize, maxSize) {
		this.setProcessRemote(false);
		if (per > 100)
			per = 100;
		this._scalePointer.setAttribute({title :cafen.getSize2Short(useSize)+' / '+cafen.getSize2Short(maxSize) +'('+ cafenMsg.get('ed_0024',Math.round(per)) +' / '+cafenMsg.get('ed_0025',Math.round(100 - per)) +')'});
		this.options.moveSchedule = [];
		if (this.options.animateStartBind == null)
			this.options.animateStartBind = this.setScaleTime.bind(this);
		var x = (this.baseWidth * per / 100) ;
		var aniBind = [0, -1, -2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,19,18,17,18];
		var bg_pos = this._scalePointer.getStyle('backgroundPosition').split(' ');
		var pos_x = 1000 + parseInt(bg_pos[0]);
		var pos = [pos_x, 0];
    	var posStepX = (x != null) ? x - pos[0] : 0;
		for(var i = 0; i < aniBind.length; i++) {
			var moveRate = Math.sin(Math.PI * aniBind[i]/36);
			if (aniBind[i] > 18)
				moveRate = 2 - moveRate;
			var moveX =  (posStepX != 0) ? Math.round(pos[0] + posStepX * moveRate) : null;
			this.options.moveSchedule.push(moveX+6);
		}
    	if (this.timer != null)
    		window.clearTimeout(this.timer);
    	if (this.options.moveSchedule.length > 0)
			this.setScaleTime();
	},
	setScaleTime : function() {
		var x = this.options.moveSchedule[0];
		this.options.moveSchedule.shift();
		this._scalePointer.setStyle({backgroundPosition: (x - 1000)+'px 0'});
    	if (this.options.moveSchedule.length > 0) 
			this.timer = setTimeout(this.options.animateStartBind, 5);
	},
	setProcess : function(per) {
		var po = (this.baseWidth * per / 100);
		this._uploadPointer.setStyle({backgroundPosition : (po-1000) + 'px -20px'});
	}
},cafen.Element.prototype);


cafen.Attach.AttachFile = function(obj) {
	this._editorObject = obj;
	this.baseHeight = obj.config.height -15;
	this.baseWidth = obj.config.width -33;
	if (obj.config.showattachsize == null || obj.config.showattachsize < 1)
		this.baseAttachHeight = this.baseHeight;
	else
		this.baseAttachHeight = obj.config.showattachsize * 26;
	if (	this.baseAttachHeight > 200)
		this.baseAttachHeight = 200;
	if (	this.baseAttachHeight < 52)
		this.baseAttachHeight = 52;
	this.baseAttachHeight -= 4;
	this.previewHeight = this.baseAttachHeight;
	if (this.previewHeight > 100)
		this.previewHeight = 100;
	this.maxUpload = this._editorObject.config.attachfile_max;
	this.attachType = this._editorObject.config.attachfile_type;
	this.maxAttachCnt = this._editorObject.config.attachfile_cnt;
	this.setOptions({tag : 'div', attribute :{}, style : {width :this.baseWidth+'px', textAlign : 'left',position: 'relative', margin : '3px 0 1px 8px'}});
	this.initAttachFile()
}
cafen.Attach.AttachFile.prototype = cafen.extendClass({
	attachSize : 0,
	initAttachFile : function() {
		var tmpTable = new cafen.TableAuto({attribute :{border : 0, cellSpacing: 0 },style : {width :this.baseWidth+'px'}});
		this.appendChild(tmpTable);
		tmpTable.addRow();
		this.previewArea = new cafen.Div({className : this._editorObject.getClassName('box'),style : {width : '94px', height : this.previewHeight+'px', overflowX : 'hidden', overflowY : 'hidden'}}); 
		tmpTable.addCell(this.previewArea);
		tmpTable.addStyle({verticalAlign: 'top'});
		this.attachArea = new cafen.XMenu([], this.baseWidth -185, {style: {height: this.baseAttachHeight +'px', overflowY : this._editorObject.config.canbe_resize ? 'visible' :'auto', overflowX : 'hidden', marginLeft: '3px'}, event : {select : this.setSelect.bind(this)}, buttonClass : this._editorObject.getClassName('attachbutton')}); 
		tmpTable.addCell(this.attachArea);
		tmpTable.addStyle({verticalAlign: 'top'});
		var buttonTable = new cafen.TableAuto({attribute :{border : 0, cellSpacing: 0, cellPadding : 0},style : {width :'auto'}});
		tmpTable.addCell(buttonTable);
		tmpTable.addStyle({textAlign:'left',verticalAlign: 'top'});
		var iconMargin = null;
		if(cafen.browser.isIE) 
			iconMargin = '0 0 0 3px';
		else if(cafen.browser.isFF) 
			iconMargin = '-1 0 0 0px';
		else
			iconMargin = '3px 0px 3px 2px';
		var buttonSet = [];
		for(var i = 0 ; i < Math.min(6, this._editorObject.config.middlebar.length); i++) 
			buttonSet.push(this._editorObject.config.middlebar[i]);
		for(var i = 0; i < buttonSet.length; i++) {
			if (i % 3 == 0) {
				buttonTable.addRow();
				if (i > 0) {
					buttonTable.addCell();
					buttonTable.addAttribute({colSpan :3});
					buttonTable.addStyle({height:'2px'});
					buttonTable.addRow();
				}
			}
			var currButton = (i < buttonSet.length ) ? buttonSet[i] : '';
			var bgPos = 330;
			var currPos = i % 3;
			if (currPos == 0 && i == buttonSet.length - 1)
				bgPos = 462;
			else if (i == buttonSet.length - 1 || currPos == 2) 
				bgPos = 396;
			else if (currPos == 0) 
				bgPos = 264;
			switch(currButton) {
				case 'del' :
					var icon = new cafen.XImage({className :'r_editorset',x: 142,y : 48}, {style:{width:'16px', height:'16px', margin : iconMargin},attribute :{unselectable : 'on'}});
					tmpButton = new cafen.XIcon({icon : this._editorObject.getClassName('buttonbg'), off : bgPos, on : 22 , over : 100, style :{width: '24px'}, attribute :{unselectable : 'on', title : cafenMsg.get('ed_0014')}, event :{click:this.confirmDelete.bind(this)}, childNodes : [icon]}) ;
					buttonTable.addCell(tmpButton);
					break;
				case 'chart' :
					var buttonInfo = cafenMsg.getObject('ed_buttonInfo');
					var icon = new cafen.XImage({className :'r_editorset',x: 15,y : 48}, {style:{width:'16px', height:'16px', margin : iconMargin},attribute :{unselectable : 'on'}});
					tmpButton = new cafen.XIcon({icon : this._editorObject.getClassName('buttonbg'), off : bgPos, on : 22 , over : 100, style :{width: '24px'}, attribute :{unselectable : 'on', title : buttonInfo['insertchart'][1]}, event :{click:this.attachChart.bind(this)}, childNodes : [icon]}) ;
					buttonTable.addCell(tmpButton);
					break;
				case 'map' :
					var buttonInfo = cafenMsg.getObject('ed_buttonInfo');
					var icon = new cafen.XImage({className :'r_editorset',x: 15,y : 32}, {style:{width:'16px', height:'16px', margin : iconMargin},attribute :{unselectable : 'on'}});
					tmpButton = new cafen.XIcon({icon : this._editorObject.getClassName('buttonbg'), off : bgPos, on : 22 , over : 100, style :{width: '24px'}, attribute :{unselectable : 'on', title : buttonInfo['insertmap'][1]}, event :{click:this.attachMap.bind(this)}, childNodes : [icon]}) ;
					buttonTable.addCell(tmpButton);
					break;
				case 'image' :
					var buttonInfo = cafenMsg.getObject('ed_buttonInfo');
					var icon = new cafen.XImage({className :'r_editorset',x: 78,y : 32}, {style:{width:'16px', height:'16px', margin : iconMargin},attribute :{unselectable : 'on'}});
					tmpButton = new cafen.XIcon({icon : this._editorObject.getClassName('buttonbg'), off : bgPos, on : 22 , over : 100, style :{width: '24px'}, attribute :{unselectable : 'on', title : buttonInfo['insertimaged'][1]}, event :{click:this.attachImage.bind(this)}, childNodes : [icon]}) ;
					buttonTable.addCell(tmpButton);
					break;
				case 'movie' :
					var buttonInfo = cafenMsg.getObject('ed_buttonInfo');
					var icon = new cafen.XImage({className :'r_editorset',x: 142,y : 32}, {style:{width:'16px', height:'16px', margin : iconMargin},attribute :{unselectable : 'on'}});
					tmpButton = new cafen.XIcon({icon : this._editorObject.getClassName('buttonbg'), off : bgPos, on : 22 , over : 100, style :{width: '24px'}, attribute :{unselectable : 'on', title : buttonInfo['insertmediad'][1]}, event :{click:this.attachMovie.bind(this)}, childNodes : [icon]}) ;
					buttonTable.addCell(tmpButton);
					break;
				default :
					tmpButton = new cafen.XIcon({icon : this._editorObject.getClassName('buttonbg'), off : bgPos, on : 22 , over : 100, style :{width: '24px'}, attribute :{unselectable : 'on'}, event :{}, attribute : {innerHTML :'&nbsp;'}}) ;
					buttonTable.addCell(tmpButton);
					break;
			}
		}
		this.updateScale();
	},
	reSize : function() {
		this.baseWidth = this._editorObject.config.width -35;
		this.setStyle({width : this.baseWidth +'px'});
		this.childNodes[0].setStyle({width : this.baseWidth +'px'});
		this.attachArea.setStyle({width : (this.baseWidth -185)+'px'});
		this.attachArea.reSize(this.baseWidth -185);
		this.updateScale();
	},
	attachChart : function() {
		this._editorObject.showMsg(cafenMsg.get('ed_0037') , true);
	},
	attachMap : function() {
		if (cafenAttach_loader.editorBaseConf.useStaticMap && this._editorObject.config.attachAs) 
			this._editorObject.showContents(null, 'map');
		else 
			this._editorObject.showMsg(cafenMsg.get('ed_0036') , true);
	},
	attachImage : function() {
		if (cafenAttach_loader.editorBaseConf.useImageEditor) {
			this._editorObject.showContents(null,'imageeditor');
		} else
			this._editorObject.showMsg(cafenMsg.get('ed_0036') , true);
	},
	attachMovie : function() {
		if (this.attachType.indexOf('all') > -1 || this.attachType.indexOf('video') > -1) {
			if (cafenAttach_loader.editorBaseConf.useMediaPlayer) {
				this._editorObject.showContents(null,'movieeditor');
			} else
				this._editorObject.showMsg(cafenMsg.get('ed_0036') , true);
		} else {
			this._editorObject.showMsg(cafenMsg.get('ed_0036') , true);
		}
	},
	initFiles : function(attachtxt) {
		var attachFiles = this.attachArea.getItems();
		for(var i = 0; i < attachFiles.length; i++)
			this.attachArea.removeItem(attachFiles[i]);
		if (attachtxt != undefined && attachtxt != '') {
			var attach_txt = attachtxt.split("#");
			for(var i = 0; i < attach_txt.length; i++) {
				var arr_val = attach_txt[i];
				var attach_info = arr_val.split('|');
				if (attach_info.length >= 4 ) {
					var attach_obj = new Object();
					attach_obj = {server:attach_info[0], size : parseInt(attach_info[1]), extension : attach_info[2], fileName :  attach_info[3], extra :  (attach_info[4] != null)?attach_info[4]:''};
					this.addFile(attach_obj);
				}
			}
		} 
		this.updateScale();
	},
	onload : function() {
		if (this._editorObject.editorAttachScale.attachFileButton != null) {
			this._attachbuttonID = this._editorObject.editorAttachScale.attachFileButton.getAttribute('id');
			if (this._attachbuttonID == null || typeof this._attachbuttonID == 'undefined' || this._attachbuttonID == '') {
				this._attachbuttonID = cafen.getUniqID('attach');
				this._editorObject.editorAttachScale.attachFileButton.setAttribute({id : this._attachbuttonID});
			}
			cafen.Attach.Upload.upload_local({
				upload_max_size : this._editorObject.config.attachfile_max,
				upload_one_size : this._editorObject.config.onefile_max,
				button_placeholder_id : this._editorObject.editorAttachScale.attachFileButton.getElement(),
				upload_filetypes : this.attachType,
				handleErrors : this.uploadError.bind(this),
				uploadProgress : this.uploadProgress.bind(this),
				button_action : (this.maxAttachCnt > 1) ? -110 : -100,
				uploadFileComplete : this.uploadFileComplete.bind(this),
				uploadQueueComplete : this.uploadQueueComplete.bind(this),
				fileQueued : this.fileQueued.bind(this),
				button_image_url : this._editorObject.getClassName('attach'),
				button_text : '<span class="theFont">'+cafenMsg.get('ed_0051') +'<span>',
				button_text_left_padding : '18',
				button_text_top_padding : '2',
				backgroundcolor : this._editorObject.config.color_info.attach_bg ,
				button_text_style : '.theFont {color: '+this._editorObject.config.color_info.attach_font+'; font-size: 11px;}',
				fileDialogStart : this.fileDialogStart.bind(this),
				button_window_mode : 'transparent'
			});
		}
	},
	uploadRemote : function (remote_url, saveName) {
		this.attachHtmlTags = [];
		cafen.Attach.Upload.upload_remote({
			handleErrors : this.uploadError.bind(this),
			uploadProgress : this.uploadProgress.bind(this),
			uploadFileComplete : this.uploadFileComplete.bind(this),
			uploadQueueComplete : this.uploadQueueComplete.bind(this),
			remote_url : remote_url,
			save_name : saveName,
			move : 'Y'
		});
		this._editorObject.editorAttachScale.setProcessRemote(true);
	},
	uploadError : function(msg, detail, contents) {
		this._editorObject.showMsg(detail +'<hr>'+contents, true);
	},
	fileDialogStart : function() {
		this.attachHtmlTags = [];
		this.uploadQueue = [];
		this.uploadQueueSize = 0;
		this.uploadedSize = 0;
	},
	fileQueued : function(ufile) {
		this.uploadQueueSize += parseInt(ufile.size);
		this.uploadQueue.push(ufile);
	},
	uploadProgress : function(ufile, bytes_complete, bytes_total) {
		this._editorObject.editorAttachScale.setProcess((this.uploadedSize + bytes_complete)/this.uploadQueueSize*100);
	},
	uploadFileComplete : function(ufile) {
		if (this.addFile(ufile)) {
			this.uploadedSize += parseInt(ufile.size);
			if (ufile.html_tag != '')
				this.attachHtmlTags.push(ufile.html_tag);
		}
	},
	uploadQueueComplete : function() {
		this._editorObject.editorAttachScale.setProcess(0);
		this.updateScale();
	},
	uploadFileTag : function(bl) {},
	setPreview : function(obj) {
		var fileOption = obj.options.itemOptions;
		if (cafen.Attach.Upload.isImage(fileOption)) {
			if (this.showImageContentsBind == null)
				this.showImageContentsBind = this.showImageContents.bind(this);
			this.lastSelectedObj = fileOption;
			this.previewArea.getElement().innerHTML = "";
			if (fileOption.previewObj == null) 
				fileOption.previewObj = new cafen.Image(fileOption.img.src, {fileOption : fileOption, scale : 'max', style : {width : '94px', height :  (this.previewHeight)+'px', cursor : cafen.getCursor()}, event : {click : this.showImageContentsBind}});
			this.previewArea.appendChild(fileOption.previewObj);
			fileOption.previewObj.playAnimate();
		} else if (cafenAttach_loader.editorBaseConf.useMediaPlayer && cafen.Attach.Upload.isMovie(fileOption)) {
			if (this.showMovieContentsBind == null)
				this.showMovieContentsBind = this.showMovieContents.bind(this);
			this.lastSelectedObj = fileOption;
			this.previewArea.getElement().innerHTML = "";
			if (fileOption.previewObj == null) 
				fileOption.previewObj = new cafen.Image(_cafen_service_url+'images/ico_movie.gif', {fileOption : fileOption, scale : 'min', style : {width : '94px', height : (this.previewHeight)+'px', cursor : cafen.getCursor()}, event : {click : this.showMovieContentsBind}});
			this.previewArea.appendChild(fileOption.previewObj);
			fileOption.previewObj.playAnimate();
		}
	},
	showImageContents : function(obj) {
		if (!cafenAttach_loader.editorBaseConf.useImageEditor)
			this._editorObject.showContents(obj.getElement().src,'image');
		else {
			this._editorObject.showContents(obj.options.fileOption,'imageeditor');
		}
	},
	showMovieContents : function(obj) {
		if (cafenAttach_loader.editorBaseConf.useMediaPlayer)
			this._editorObject.showContents(obj.options.fileOption,'movieeditor');
	},
/**
 * 첨부 파일 parse
 */
	parse : function(bl) {
		var attachFiles = this.attachArea.getItems();
		if (attachFiles.length > 0) {
			if (bl == null || !bl) {
				var contents = this._editorObject.getContents();
				var attachfileHtml = '<select style="display:none">';
				for(var i = 0 ; i < attachFiles.length; i++) {
					var fileinfo = attachFiles[i].options.itemOptions;
					var isIncluded = (contents.indexOf(fileinfo.server) > -1) ? '1' : '0';
					attachfileHtml += '<option isincluded='+isIncluded+' server="'+fileinfo.server+'" size="'+fileinfo.size+'" ext="'+fileinfo.ext+'" extra="'+fileinfo.extra+'">'+fileinfo.fileName +'</option>';
				}
				attachfileHtml += '</select>';
				return attachfileHtml;
			} else {
				var attachfileHtml = '';
				if (bl == 'xml') {
					for(var i = 0 ; i < attachFiles.length; i++) {
						var fileinfo = attachFiles[i].options.itemOptions;
						var tmpObj = {
							'server' : 	fileinfo.server,
							'size' : fileinfo.size,
							'ext' : fileinfo.ext,
							'name' : fileinfo.fileName,
							'extra' : fileinfo.extra
						}
						attachfileHtml += '<item>\r\n'
						for (var idx in tmpObj) {
							attachfileHtml += '<'+idx+'><![CDATA['+tmpObj[idx]+']]></'+idx+'>\r\n';
						}
						attachfileHtml += '</item>\r\n';
					}
				} else {
					var tmpData = [];
					for(var i = 0 ; i < attachFiles.length; i++) {
						var fileinfo = attachFiles[i].options.itemOptions;
						tmpData.push(fileinfo.server + '|' + fileinfo.size + '|' + fileinfo.extension + '|' + fileinfo.fileName + '|' + fileinfo.extra);
					}
					attachfileHtml = tmpData.join('#');
				}
				return attachfileHtml;
			}
		} else
			return '';
	},
/**
 * 첨부된 이미지 갯수
 * @return {int} 첨부된 이미지 갯수
 */
	getImageCnt : function() {
		var cnt = 0;
		var attachFiles = this.attachArea.getItems();
		for(var i =0; i< attachFiles.length; i++) {
			var fileOption = attachFiles[i].options.itemOptions;
			if (cafen.Attach.Upload.isImage(fileOption)) 
				cnt++;
		}
		return cnt;
	},
/**
 * 첨부 파일 크기 가져오기
 */
	getAttachSize : function() {
		return this.attachSize;
	},
/**
 * 첨부 파일 갯수 가져오기
 */
	getAttachCnt : function() {
		return this.attachArea.getItems().length;
	},

/**
 * 첨부 파일 추가 가능 여부 확인
 * @param {int} add_cnt  추가될 크기
 * @return {boolean} 추가가능여부
 */
	chkUploadSize : function (add_size) {
		if (this.maxAttachCnt == 1) 
			return (this.maxUpload > add_size) ? true : false;
		else 
			return (this.getRemindSize() > add_size) ? true : false;
	},
/**
 * 남은 첨부 용량가져오기
 * @return {int} 남은첨부가능용량
 */
	getRemindSize : function() {
		return (this.maxUpload - this.attachSize);
	},
	addFile : function(obj) {
		obj = cafen.extend({fileName :'', size : 0, extension : '', server : ''}, obj);
		if (this.maxAttachCnt == 1) {
			if (obj.size <= this.maxUpload) {
				var selectedObj = this.attachArea.getItems();
				for(var i =0; i < selectedObj.length ; i++) 
					this.attachArea.removeItem(selectedObj[i]);
				var buttonObj = this.attachArea.appendItem({text : obj.fileName +' ('+cafen.getSize2Short(obj.size,2)+')', icon : this.getFileIcon(obj.extension) , options : obj});
				obj.linkObj = buttonObj;
				return true;
			} else {
				this._editorObject.showMsg(cafenMsg.get('ed_0019', cafen.getSize2Short(this.attachSize,2), cafen.getSize2Short(this.maxUpload,2), cafen.getSize2Short(obj.size,2)), true);
				return false;
			}
		} else {
			if (this.maxAttachCnt > this.getAttachCnt() && this.attachSize + obj.size <= this.maxUpload) {
				var buttonObj = this.attachArea.appendItem({text : obj.fileName +' ('+cafen.getSize2Short(obj.size,2)+')', icon : this.getFileIcon(obj.extension) , options : obj});
				obj.linkObj = buttonObj;
				if (obj.orgName != null && obj.orgName != '') 
					this.replaceFileConfirm(obj.orgName, obj.server);			
				return true;
			} else {
				this._editorObject.showMsg(cafenMsg.get('ed_0019', cafen.getSize2Short(this.attachSize,2), cafen.getSize2Short(this.maxUpload,2), cafen.getSize2Short(obj.size,2)), true);
				return false;
			}
		}
	},
	_lastReplaceFileObj : [null, null],
	replaceFileConfirm : function(orgName, repName) {
		this._lastReplaceFileObj = [orgName, repName];
		this._editorObject.showConfirm(cafenMsg.get('ed_0141'), this.replaceFile.bind(this), true);
	},
	replaceFile : function(bl) {
		if (bl) {
			var orgName = this._lastReplaceFileObj[0];
			var repName = this._lastReplaceFileObj[1];
			var selectedObj = this.attachArea.getItems();
			var replaceObj = [];
			for(var i =0; i < selectedObj.length ; i++) {
				if (selectedObj[i].options.itemOptions.server == orgName) {
					replaceObj.push(selectedObj[i].options.itemOptions.server);
					this.attachArea.removeItem(selectedObj[i]);
				}
			}
		}
	},
	attach_icon : {
		avi:171, mov:171, flv:171, wma:171, asf:171, wav:171, mp3:179,
		com:176, exe:176, dll:176, 
		htm:174, html:174, docx:178, doc:178, hwp:173, 
		bmp:180, gif:175,jpg:172, png:172, jpeg:172, psd:187, tif:185, 
		pdf:188, ppt:187, pptx:187, txt:189, xls:184,xlsx:184,
		zip:183, mcast : 181, etc:177 
	},
	getFileIcon : function(ext) {
		var pos = (this.attach_icon[ext] != null) ? this.attach_icon[ext] : this.attach_icon['etc'];
		var x = (pos % 10) * 16;
		var y = Math.floor(pos / 10)*16;
		return {className : 'r_editorset', x : x, y : y};
	},
	updateScale : function() {
		this.attachSize = 0;
		var attachFiles = this.attachArea.getItems();
		for(var i = 0; i < attachFiles.length; i++)
			this.attachSize += attachFiles[i].options.itemOptions.size;
		if (this.maxUpload > 0) 
			this._editorObject.editorAttachScale.setScale(this.attachSize/this.maxUpload*100, this.attachSize ,this.maxUpload);
		else
			this._editorObject.editorAttachScale.setScale(0, 0 ,100);
	},
	confirmDelete : function() {
		var selectedLen = 0;
		var selectedLen = this.attachArea.getSelected().length;
		if (selectedLen == 0)
			this._editorObject.showMsg(cafenMsg.get('ed_0017'), true);
		else
			this._editorObject.showConfirm(cafenMsg.get('ed_0018', selectedLen), this.deleteSelected.bind(this), true);
	},
	deleteSelected : function(bl) {
		if (bl) {
			var selectedObj = this.attachArea.getSelected();
			var error_file = [];
			for(var i =0; i < selectedObj.length ; i++) {
				this.attachArea.removeItem(selectedObj[i]);
			}
			if (error_file.length > 0)
				this._editorObject.showMsg(cafenMsg.get('ed_0020', error_file.join('<br>')), true);
			this.previewArea.getElement().innerHTML = "";
			this.updateScale();
		}
	},
	setSelect : function(tmp, obj) {
		this.attachArea.setSelectToggle(obj);
		this.setPreview(obj);
	}
},cafen.Element.prototype);

cafen.Attach.Config = function(editObj, config) {
	this.initConfig(editObj, config);
}

cafen.Attach.Config.prototype = {
	initConfig : function(editor_obj, userConfig) {
		if (userConfig == undefined) { var userConfig = new Object(); }
		this.width = parseInt((userConfig.width == undefined)?(editor_obj.obj.offsetWidth?editor_obj.obj.offsetWidth:editor_obj.obj.style.width):userConfig.width);
		this.height = parseInt((userConfig.height == undefined )?(editor_obj.obj.offsetHeight?editor_obj.obj.offsetHeight:editor_obj.obj.style.height):userConfig.height);
		if (this.width == undefined || this.width < 300) this.width = 300;
		if (this.height == undefined || this.height < 50) this.height = 50;
		this.attachfile_max = (userConfig.attachfile_max == undefined)?1024*30:userConfig.attachfile_max;
		this.attachfile_type = (userConfig.attachfile_max == undefined)?'all':userConfig.attachfile_type;
		this.attachfile_cnt = (userConfig.attachfile_cnt == undefined)?10:userConfig.attachfile_cnt;
		this.onefile_max = (userConfig.onefile_max == undefined)?1024*30:userConfig.onefile_max;
		this.attachAs = (userConfig.attachAs == undefined || userConfig.attachAs == null)? cafenAttach_loader.editorBaseConf.attachAs :userConfig.attachAs;
		this.onstartclose = (userConfig.onstartclose == undefined)?false:userConfig.onstartclose;
		this.skin = (userConfig.skin == undefined)?'hani':userConfig.skin;
		this.toogleSatus = {tool : true, attach : true};
		this.toogleSize = {tool : 50, attach : 70};
		try {
			this.attachtxt = (userConfig.data == null || userConfig.data == '') ? editor_obj.obj.value : userConfig.data;
			
		} catch(ex) {
			this.attachtxt = '';
		}
		this.use_unloadevent = (userConfig.use_unloadevent == undefined)?false:userConfig.use_unloadevent;
		if (userConfig.middlebar == undefined) {
			this.middlebarset = (userConfig.middlebarset == undefined || cafen.Attach.baseConf.middlebarskin[userConfig.middlebarset] == undefined)? cafenAttach_loader.editorBaseConf.middlebarset :userConfig.middlebarset;
			this.middlebar = cafen.Attach.baseConf.middlebarskin[this.middlebarset];
		} else 
			this.middlebar = userConfig.middlebar;
		this.color_info = cafen.extend(cafen.Attach.baseConf.skin[this.skin], userConfig.color_info);
		this.canbe_resize = (userConfig.canbe_resize == null) ? false : userConfig.canbe_resize;
		this.showattachsize = (userConfig.showattachsize == null) ? 0 : userConfig.showattachsize;
		this.img_sign = (userConfig.img_sign == undefined)?'':userConfig.img_sign;
	}
}

cafen.Attach.contentsViewer = function(parentNode) {
	this.parentNode = parentNode;
	this.initcontentsViewer();
};
cafen.Attach.contentsViewer.prototype = {
	initcontentsViewer : function() {
		this.obj = new cafen.Div({style:{position : 'absolute', textAlign : 'left', zIndex : '500000'}, attribute : {}});
		this.parentNode.appendChild(this.obj);
		var obj_width = this.parentNode.config.width - 30;
		var obj_height = this.parentNode.config.height - 10;
		if (obj_width < 200)
			obj_width = 300;
		else if (obj_width > 500)
			obj_width = 500;
		if (obj_height < 100)
			obj_height = 200;
		else if (obj_height > 500)
			obj_height = 500;
		this.baseSize = [obj_width, obj_height];
	},
	hideLastObj : function(obj) {
		if (this.lastObj != null && this.lastObj != obj)
			this.lastObj.hide();
		this.lastObj = obj;
		if (this.lastObj != null && this.lastObj.onLoad)
			this.lastObj.onLoad();
	},
	setImageEditor  : function(imgurl) {
		if (this.imageEditor == null) {
			var maxSize = Math.min(this.parentNode.config.onefile_max, this.parentNode.config.attachfile_max);
			var signTxt = this.parentNode.config.img_sign || '';
			this.imageEditor = new cafen.XImageViewer({maxSize : maxSize , signTxt : signTxt , style : {width : '550px', height : '375px'}, sticker : {obj : this.parentNode._editorObject.editorSkin, x : 'center', y : 'top'}}, this.parentNode);
			this.obj.appendChild(this.imageEditor);
		}
		this.hideLastObj(this.imageEditor);
		this.imageEditor.setFileObj(imgurl);
	},
	setImage : function(imgurl) {
		if (this.imageViewer == null) {
			this.imageViewer = new cafen.XImageViewer({style : {width : this.baseSize[0] +'px', height : this.baseSize[1] +'px'}, sticker : {obj : this.parentNode._editorObject.editorSkin, x : 'center', y : 'top'}});
			this.obj.appendChild(this.imageViewer);
		}
		this.hideLastObj(this.imageViewer);
		this.imageViewer.setImage(imgurl);
	},
	setMovie : function(imgurl) {
		if (this.movieViewer == null) {
			this.movieViewer = new cafen.XMovieViewer({style : {width : this.baseSize[0]  +'px', height : Math.round(this.baseSize[0]*0.7) +'px'}, sticker : {obj : this.parentNode._editorObject.editorSkin, x : 'center', y : 'top'}});
			this.obj.appendChild(this.movieViewer);
		}
		this.hideLastObj(this.movieViewer);
		this.movieViewer.setMovie(imgurl);
	},
	setMovieEditor : function(imgurl) {
		if (this.movieEditor == null) {
			var maxSize = Math.min(this.parentNode.config.onefile_max, this.parentNode.attachfile_max);
			this.movieEditor = new cafen.XMovieViewer({maxSize : maxSize, style : {width : '550px', height : '321px'}, sticker : {obj : this.parentNode._editorObject.editorSkin, x : 'center', y : 'top'}}, this.parentNode);
			this.obj.appendChild(this.movieEditor);
		}
		this.hideLastObj(this.movieEditor);
		this.movieEditor.setFileObj(imgurl);
	},
	setMap : function(mapInfo) {
		if (cafen.checkAPI('GMap')) {
			if (this.mapViewer == null) {
				var base_height = Math.max(this.baseSize[1], 300);
				this.mapViewer = new cafen.XMapViewer({style : {width : this.baseSize[0] +'px', height : base_height +'px'}, sticker : {obj : this.parentNode._editorObject.editorSkin, x : 'center', y : 'top'}, event : {done : this.insertMap.bind(this)}});
				this.obj.appendChild(this.mapViewer);
			}
			this.hideLastObj(this.mapViewer);
			this.mapViewer.setMap(mapInfo);
		} else 
			this.parentNode.showMsg(cafenMsg.get('com_nullkey'));
	},
	insertMap : function(obj) {
		if (this.parentNode.editorAttachView != null && this.parentNode.config.attachAs)
			this.parentNode.editorAttachView.uploadRemote(obj.getMap(), cafen.getUniqID('map')+'.' + (obj.getApi() == 'daum' ? 'gif' : 'jpg'));
		this.hideLastObj(null);
	}
}

cafen.Attach.baseConf = {
/**
 * 기본 에디터 경로
 * @type string
 */
	_editor_url : 'http://service.cafen.net/',
/**
 * 브라우즈 IE 여부
 * @type boolean
 */
	isIE : window.ActiveXObject ? true : false,
	boundary : '@4d4e81d3f9219886bcadb3dc9b503f82@',
/**
 * 에디터 스킨
 * @type object
 */
	skin : {
		base : {
			attachImg : 'ico_attach.png', attach_bg : '#c8d8ed', attach_font : '#464646',
			class_Tab : 'r_tab', class_Box : 'r_boxblue', class_ButtonArea : 'r_boxblue', class_Editor : 'r_boxwhite', class_Button : 'r_wordset', class_Scale : 'r_editorattach', class_Attach : 'r_boxblue'
		},
		black : {
			attachImg : 'ico_attach_black.png', attach_bg : '#000000', attach_font : '#464646',
			class_Tab : 'r_tabblack', class_Box : 'r_boxblack', class_ButtonArea : 'r_boxblack', class_Editor : 'r_boxblack', class_Button : 'r_wordset-black', class_Scale : 'r_editorattach-black', class_Attach : 'r_tbtnskin-black'
		},
		white : {
			attachImg : 'ico_attach_gray.png', attach_bg : '#f5f5f5', attach_font : '#464646',
			class_Tab : 'r_tabwhite', class_Box : 'r_boxwhite', class_ButtonArea : 'r_boxwhite', class_Editor : 'r_boxwhite', class_Button : 'r_wordset-gray', class_Scale : 'r_editorattach-gray', class_Attach : 'r_tbtnskin-white'
		},
		silver : {
			attachImg : 'ico_attach_gray.png', attach_bg : '#dfdfdf', attach_font : '#464646',
			class_Tab : 'r_tabgray', class_Box : 'r_boxgray', class_ButtonArea : 'r_boxgray', class_Editor : 'r_boxgray', class_Button : 'r_wordset-gray', class_Scale : 'r_editorattach-gray', class_Attach : 'r_tbtnskin-white'
		},
		whitenblack : {
			attachImg : 'ico_attach_white.png', attach_bg : '#000000', attach_font : '#464646',
			class_Tab : 'r_tabblack', class_Box : 'r_boxwhite', class_ButtonArea : 'r_boxblack', class_Editor : 'r_boxwhite', class_Button : 'r_wordset-gray', class_Scale : 'r_editorattach-white'
		},
		blue : {
			attachImg : 'ico_attach_white.png', attach_bg : '#cfdff0', attach_font : '#464646',
			class_Tab : 'r_tabblue', class_Box : 'r_boxblue', class_ButtonArea : 'r_boxblue', class_Editor : 'r_boxgray', class_Button : 'r_wordset-blue', class_Scale : 'r_editorattach-blue', class_Attach : 'r_tbtnskin-blue'
		},
		green : {
			attachImg : 'ico_attach_gray.png', attach_bg : '#bff4ad', attach_font : '#464646',
			class_Tab : 'r_tabgreen', class_Box : 'r_boxgreen', class_ButtonArea : 'r_boxgreen', class_Editor : 'r_boxgreen', class_Button : 'r_wordset-green', class_Scale : 'r_editorattach-green', class_Attach : 'r_tbtnskin-green'
		},
		red : {
			attachImg : 'ico_attach_gray.png', attach_bg : '#f5e3d7', attach_font : '#464646',
			class_Tab : 'r_tab-r', class_Box : 'r_boxred', class_ButtonArea : 'r_boxred', class_Editor : 'r_boxgray', class_Button : 'r_wordset-red', class_Scale : 'r_editorattach-red', class_Attach : 'r_tbtnskin-red'
		}
	},
	middlebarskin : {
		base : [
			'del','image','map'
		],
		simple : [
			'del'
		],
		movie : [
			'movie','image','del'
		],
		map : [
			'map','image','del'
		]
	}
	
}

/**
 * cafen.Upload
 * 파일 업로드
 */
cafen.Attach.Upload = {
/**
 * 기본 업로드 SCRIPT
 * @type string
 */
	base_upload_script : '/UPLOADS/upload_fileswf.php',
/**
 * 기본 업로드 URL
 * @type string
 */
	base_upload_url : '/UPLOADS/uploads/',
	base_uploaded_url : null,
/**
 * 기본 업로드 URL Domain
 * @type string
 */
	base_upload_domain : '',
/**
 * SWFUPLOAD.swf 파일 위치
 * @type string
 */
	flash_path : _cafen_service_url+'/images/',
/**
 * 이미지 경로
 * @type string
 */
	base_image_url : _cafen_service_url +"editor/images/",
/**
 * 미디어 플레이어 사용여부
 * @type boolean
 */
	use_mediaplayer : false,
/**
 * 이미지 편집기 사용여부
 * @type boolean
 */
	use_imageeditor : false,
/**
 * 미디어 플레이어 정보
 * @type object
 */
	mediaplayer_info : {
		logo : 'http://service.cafen.net/images/logo_media.png',
		backColor : '0x000000',
		frontColor : '0xCCCCCC'
	},
/**
 * 싸인 앞첨자
 * @type string
 */
	imgsign_pre : '',
/**
 * 싸인 뒤첨자
 * @type string
 */
	imgsign_tail : '',
/**
 * 마지막 프리로드 함수
 * @type function
 */
	lastpreload_callback : null,
/**
 * 마지막 프리로드 ALERT 함수
 * @type function
 */
	lastpreload_alert : null,
/**
 * 이미지 프레임 정보
 * @type object
 */
	image_skin : null,
/**
 * 이미지 프레임 랜덤정보
 * @type array
 */
	image_skinrandom : null,
/**
 * 미디어 파일 자동 넣기
 * @type boolean
 */
	media_autotag : true,
/**
 * 이미지 회전 정보
 * @type object
 */
	image_rotate : cafenMsg.getObject('ed_imgrotate'),
/**
 * 마지막 접근 옵션
 * @type object
 */
	last_options : {upload_max_size:0, upload_filetypes:null},
/**
 * 마지막 생성 swfupload Object
 * @type object
 */
	last_swfuploadobj : null,
/**
 * 컴퓨터 파일 업로드
 * @param {object} options  옵션 정보
 */
	upload_local : function(options,replaceObj) {
		options = cafen.extend({
			upload_max_size : 1024*1024*100,
			upload_one_size : 1024*1024*1,
			autoBrowse : function() {},
			fileQueued : function() {},
			fileDialogStart : null,
			uploadFileStart : function() {},
			handleErrors : function() {},
			uploadProgress : function() {},
			uploadFileComplete : function() {},
			uploadQueueComplete : function() {},
			uploadCancel : function() {},
			upload_filetypes : 'all',
			use_frame : '',
			sign_txt : '',
			mybox_dir : '',
			button_placeholder_id : null,
			button_width : 72,
			button_height : 22,
			button_image_url : '',
			button_text_style : '',
			button_text: '',
			button_action : -110,
			button_text_left_padding : 0,
			button_text_top_padding : 0,
			backgroundcolor : '#ffffff',
			button_window_mode : 'window'
		}, options);
		var last_options = {upload_max_size : options.upload_max_size, upload_filetypes : options.upload_filetypes}
		this.last_options = last_options;
		this.options = options;
		if (options.button_placeholder_id != null && typeof options.button_placeholder_id == 'object') {
			this.options.button_width = parseInt(options.button_placeholder_id.style.width);
			this.options.button_height =parseInt(options.button_placeholder_id.style.height);
			options.button_placeholder_id = options.button_placeholder_id.getAttribute('id');
		}
		var fileTypeData = cafen.SwfUpload.getFileType(this.options.upload_filetypes);
		var filetypes_ext = fileTypeData[0];
		var filetypes_description = fileTypeData[1];
		var upload_url = (this.base_upload_script.indexOf('http://') == 0) ? this.base_upload_script : this.base_upload_script;
		var upload_options = {
			upload_url : upload_url,
			flash_url : this.flash_path+"swfupload.swf",
			file_size_limit : Math.round(Math.min(this.options.upload_one_size,this.options.upload_max_size)/1024),
			file_types : filetypes_ext,
			file_types_description : filetypes_description ,
			file_upload_limit : 1000,
			file_queue_limit : 100,
			button_action : options.button_action || -110,
			swfupload_loaded_handler : this.autoBrowse.bind(this),
			file_dialog_start_handler : this.fileDialogStart.bind(this),
			file_queued_handler : this.fileDialogQueued.bind(this),
			file_dialog_complete_handler : this.fileDialogComplete.bind(this),
			upload_progress_handler : this.uploadProgress.bind(this),
			upload_success_handler : this.uploadFileComplete.bind(this),
			upload_complete_handler : this.uploadComplete.bind(this),
			file_queue_error_handler : this.handleErrors.bind(this),
			upload_error_handler : this.uploadError.bind(this),
//			button_placeholder : options.button_placeholder_id,
			button_placeholder_id : options.button_placeholder_id,
			button_width: options.button_width,
			button_height: options.button_height,
			button_text_style : options.button_text_style,
			button_text: '<span>'+options.button_text +'</span>',
			button_text_left_padding : options.button_text_left_padding,
			button_text_top_padding : options.button_text_top_padding,
			button_window_mode : options.button_window_mode,
			backgroundcolor : options.backgroundcolor,
			button_cursor : -2,
			button_image_url : options.button_image_url,
			debug : (typeof window.debug_mode == 'undefined') ? false : window.debug_mode
		};
		try {
			var uploadObj = new SWFUpload(upload_options);
		} catch(ex) {
			return ;
		}
		if (options.button_placeholder_id != null && options.button_placeholder_id != '' ) {
			var tmpObj = cafen.$(options.button_placeholder_id);
			tmpObj.uploadObj = uploadObj;
			tmpObj.uploadOptions = this.options;
			tmpObj.fileDialogStart = this.options.fileDialogStart;
			if (tmpObj.uploadObj != null && tmpObj.uploadObj.destroy) 
				tmpObj.uploadObj.destroy();
			tmpObj.uploadObj = uploadObj;
		}
		if (replaceObj != null) {
			replaceObj.uploadOptions = this.options;
			replaceObj.uploadObj.setFileUploadLimit(Math.round(this.options.upload_max_size/1024));
			replaceObj.uploadObj.setStats({
				in_progress: 0,
				files_queued: 0,
				successful_uploads: 0,
				upload_errors: 0,
				uploads_cancelled: 0,
				queue_errors: 0
			});
			if (replaceObj.uploadObj != this.last_swfuploadobj)
				this.last_swfuploadobj = replaceObj.uploadObj;
		} else {
			this.last_swfuploadobj = uploadObj;
		}
		return uploadObj;
	},
	fileDialogStart : function(obj) {
		if (obj != null && obj.uploadObj != null && obj.uploadOptions != null) {
			this.last_swfuploadobj = obj.uploadObj;
			this.options = obj.uploadOptions;
			if (obj.fileDialogStart != null) 
				obj.fileDialogStart();
		}
	},
/**
 * 리모터 파일 업로드
 * @param {object} options  옵션 정보
 */
	upload_remote : function(options) {
		this.options = cafen.extend({
			upload_max_size : 1024*1024,
			fileQueued : function() {},
			uploadFileStart : function() {},
			handleErrors : function() {},
			uploadProgress : function() {},
			uploadFileComplete : function() {},
			uploadQueueComplete : function() {},
			upload_filetypes : 'all',
			use_frame : '',
			sign_txt : '',
			mybox_dir : '',
			remote_url : '',
			save_name : '',
			move : 'N'
		}, options);
	 	new cafen.Ajax(
	 		{
				mode : 'remote',
	 			remote_url: this.options.remote_url, 
	 			move: this.options.move, 
	 			use_frame : this.options.use_frame ,
	 			save_name : this.options.save_name,
	 			use_sign : this.options.sign_txt
	 		}, this.remoteUploadEnd.bind(this)
	 		, ''
	 		,'get'
	 	);
	},
/**
 * 리모터 파일 업로드 종료
 * @param {cafen.xmlParser.Channel} channel  채널
 * @param  {string} msg  오류메세지
 */
	remoteUploadEnd : function(channel, msg) {
		var ufile = {}
		if (channel != null) {
			var item = null;
			var msg = null;
			var uploaded_seqn = 0;
			while(item = channel.getNext()) {
				if (item.getNode('fileext') != '') {
					if (this.options.move == 'Y') {
						ufile =	{
							size : parseInt(item.getNode('filesize')),
							extension : item.getNode('fileext'),
							server : item.getNode('fileserver'),
							sorce : item.getNode('filesorce'),
							fileName: item.getNode('filename'),
							width : parseInt(item.getNode('imgwidth')),
							height : parseInt(item.getNode('imgheight')),
							extra : ''
						};
					} else {
						ufile =	{
							size : 0,
							extension : item.getNode('fileext'),
							server : item.getNode('fileserver'),
							sorce : item.getNode('filesorce'),
							fileName: item.getNode('filename'),
							width : parseInt(item.getNode('imgwidth')),
							height : parseInt(item.getNode('imgwidth')),
							extra : ''
						};
					}
					if (this.options.upload_filetypes == 'image' && !this.isImage(ufile)) 
						msg = cafenMsg.get('ed_0096');
					else {
						ufile.html_tag = this.makeTag(ufile, 'C', true);
						this.options.uploadFileComplete(ufile);
						uploaded_seqn++;
					}
				}
			}
			if (uploaded_seqn == 0)
				this.options.handleErrors(cafenMsg.get('ed_0097'), '', ((msg)?msg:cafenMsg.get('ed_0098')));
		} else {
			this.options.handleErrors(cafenMsg.get('ed_0097'), '', cafenMsg.get('ed_0098'));
		}
		this.options.uploadQueueComplete(ufile);
	},
/**
 * 옵션 지정
 * @param {object} options  옵션
 */
	setOption : function(options) {
		this.options = cafen.extend(this.options, options);
	},
/**
 * 업로드 다이아로그 종료
 * @type object
 */
	uploadStat : {
		in_progress: 0,
		files_queued: 0,
		successful_uploads: 0,
		upload_errors: 0,
		uploads_cancelled: 0,
		queue_errors: 0
	},
/**
 * 자동 브라우징
 */
	autoBrowse : function() {
//		try {
//			if (typeof this.last_swfuploadobj.setPostParams == 'function')
				this.last_swfuploadobj.setPostParams({domain : document.domain});
//			if (typeof this.last_swfuploadobj.selectFiles == 'function')
//				this.last_swfuploadobj.selectFiles();
//		} catch(ex) {
//			
//		}
	},
/**
 * 업로드 다이아로그 대기열 종료
 * @param {int} queuelength  파일선택수
 */
	fileDialogQueued : function(fileobj) {
//		if(fileobj.size > cafen.SwfUpload.singleupload_max) {
		if(fileobj.size > 100000000) {
			this.last_swfuploadobj.cancelUpload(fileobj.id);
			this.handleErrors(fileobj, -500, '');
		} else {
			this.options.fileQueued(fileobj);
			this.last_swfuploadobj.addFileParam(fileobj.id, 'save_name',cafen.getUniqID('ed'));	
		}
	},
/**
 * 업로드 다이아로그 종료
 * @param {int} queuelength  파일선택수
 */
	fileDialogComplete : function(queuelength) {
		this.uploadComplete();
	},
/**
 * Upload 시작 
 * @param {string} id  파일ID
 */
	uploadComplete : function(ufile) {
		this.uploadStat = this.last_swfuploadobj.getStats();
		var uploaded_len = this.uploadStat.successful_uploads + this.uploadStat.upload_errors + this.uploadStat.upload_cancelled + this.uploadStat.queue_errors;
		var total_len = this.uploadStat.files_queued + this.uploadStat.successful_uploads + this.uploadStat.upload_errors + this.uploadStat.upload_cancelled + this.uploadStat.queue_errors;
		this.uploadFileStart(ufile, uploaded_len, total_len);
		if (this.uploadStat.files_queued > 0)
			this.last_swfuploadobj.startUpload();
		else 
			this.uploadQueueComplete(ufile);
	},
/**
 * 파일 Queue
 * @param {object} ufile  파일 Object
 * @param {int} queuelength  파일 Queue 갯수
 */
	fileQueued : function (ufile, queuelength) {
		this.options.fileQueued(ufile, queuelength);
	},
/**
 * 파일 업로드 시작
 * @param {object} ufile  파일 Object
 * @param {int} position  파일 위치
 * @param {int} queuelength  파일 Queue 갯수
 */
	uploadFileStart : function (ufile, position, queuelength) {
		this.options.uploadFileStart(ufile, position, queuelength);
	},
/**
 * 파일 업로드 진행
 * @param {object} ufile  파일 Object
 * @param {int} bytesLoaded  Upload 된 파일 크기
 */
	uploadProgress : function (ufile, bytes_complete, bytes_total) {
		this.options.uploadProgress(ufile, bytes_complete, bytes_total);
	},
/**
 * 파일 업로드 완료
 * @param {object} ufile  파일 Object
 * @param {string} response  결과값
 */
	uploadFileComplete : function (infile, response) {
		var channel, xml = new cafen.xmlParser(response);
		if (channel = xml.getNext()) {
			var item , msg = null;
			if (channel.checkMsg()) {
				var msg = channel.getMsg();
				this.options.handleErrors(msg.title, msg.domain, msg.contents);
			}
			while(item = channel.getNext()) {
				if (item.getNode('fileext') != '') {
					var ufile =	{
						size : parseInt(item.getNode('filesize')),
						extension : item.getNode('fileext'),
						server : item.getNode('fileserver'),
						sorce : item.getNode('filesorce'),
						fileName: item.getNode('filename'),
						width : parseInt(item.getNode('imgwidth')),
						height : parseInt(item.getNode('imgheight')),
						extra :  item.getNode('extra')
					}
					if (ufile.fileName == '') 
						ufile.fileName = infile.name;
					ufile = this.getFileObj(ufile);
					if (cafen.checkFileFilter(ufile)) {
						this.options.uploadFileComplete(ufile);
					}
				}
			}
		}
	},
/**
 * 파일 업로드 취소
 */
	uploadCancel : function() {
		this.options.uploadCancel();
	},
/**
 * 파일 정보 가져오기
 * @param {object} fileobj  파일 Object
 */
	getFileObj : function (imgobj) {
		if (this.isImage(imgobj))
			imgobj.html_tag = this.makeTag(imgobj, 'C');
		else
			imgobj.html_tag = '';
		return imgobj;
	},
/**
 * 파일 업로드 종료
 * @param {object} ufile  파일 Object
 */
	uploadQueueComplete : function (ufile) {
		this.options.uploadQueueComplete(ufile);
		this.last_options = {upload_max_size : -1, upload_filetypes : ''}
	},
/**
 * 파일 업로드 오류
 * @param {int} errno  오류번호
 */
	uploadError : function (file, error_code, message) {
		this.handleErrors(file, error_code, message);
	},
/**
 * 업로드 가능 파일 여부
 * @param {string} fileName  파일명
 * @return  {boolean} true|false
 */
	isUploadable : function(fileName) {
		return !cafen.find('(html|htm|php|php3|cgi|phtml|shtml|jsp|asp|exe|com|dll)$', fileName);
	},
/**
 * 오류 처리
 * @param {object} file  파일 Object
 * @param  {int} error_code  오류 코드
 * @param {int} msg_code  메세지 코드
 */
	handleErrors : function(ofile, error_code, msg_code) {
		if (ofile == null)
			ofile = {name :''}
		var error_info = cafen.SwfUpload.getErrorMsg(ofile, error_code);
		if (error_info.msg != '')
			this.options.handleErrors(error_info.title, ofile.name, error_info.msg);
	},
/**
 * 파일 아이콘 정보
 * @type object
 */
	attach_icon : {
		avi:'avi.gif', mov:'mov.gif', flv:'avi.gif', wma:'avi.gif', asf:'avi.gif', wav:'avi.gif', mp3:'mp3.gif',
		com:'com.gif', exe:'exe.gif', dll:'com.gif', 
		htm:'htm.gif', html:'htm.gif', docx:'doc.gif', doc:'doc.gif', hwp:'hwp.gif', 
		bmp:'bmp.gif', gif:'gif.gif',jpg:'jpg.gif', png:'jpg.gif', jpeg:'jpg.gif', psd:'psd.gif', tif:'tif.gif', 
		pdf:'pdf.gif', ppt:'ppt.gif', pptx:'ppt.gif', txt:'txt.gif', xls:'xls.gif',xlsx:'xls.gif',
		zip:'zip.gif', mcast : 'mcast.gif', etc:'etc.gif' 
	},
/**
 * 첨부 파일 아이콘 가져오기
 * @param {string} ext  확장자
 * @param {string} iconsize  아이콘 크기
 * @return {string} 아이콘 URL
 */
	getAttachIcon : function(ext, iconsize) {
		ext = ext.toLowerCase();
		var icon =  (this.attach_icon[ext] == null)?this.attach_icon.etc:this.attach_icon[ext]; 
		return this.base_image_url + 'ext/' + ((iconsize == null)?'s':'')+icon;
	},
/**
 * 썸네일 이미지 가져오기
 * @param {string} img_url  이미지 URL
 * @param {int} max_width  장축 크기
 * @return {string} 썸네일 URL
 */
	getNailImage : function(img_url, max_width) {
		return this.base_upload_url + 'thumb/' + img_url + '_M' + max_width +'.png';
	},
/**
 * 채널 파싱
 * @param {cafen.xmlParser} channel  채널
 * @return {object} 파싱된 Object
 */
	parseChannel : function(channel) {
		var item = null;
		var imgobj = {fileName:'',size:0,ext:'',server:'',width:0,height:0,extra : ''};
		while(item = channel.getNext()) {
			if (item.getNode('fileext') != '') {
				imgobj.size = parseInt(item.getNode('filesize'));
				imgobj.extension = item.getNode('fileext');
				imgobj.server = item.getNode('fileserver');
				imgobj.width = parseInt(item.getNode('imgwidth'));
				imgobj.height = parseInt(item.getNode('imgheight'));
				imgobj.extra = item.getNode('extra');
			}
		}
		if (imgobj.server == ''){
			return false;
		} else 
			return imgobj;
	},
/**
 * 이미지 여부 확인
 * @param {object} imgobj  파일 Object
 * @return  {string} 이미지 Object || null
 */
	isImage : function(imgobj) {
		if (imgobj != null && imgobj.extension != null && imgobj.extension.match(/(gif|jpg|png|jpeg)$/i)) {
			if (imgobj.img == null) {
				imgobj.img = new Image();
				if (this.base_uploaded_url != null && this.base_upload_url != this.base_uploaded_url) {
					if (	imgobj.server.indexOf("junk/") == 0) 
						imgobj.img.src = this.base_upload_url + imgobj.server;
					else 
						imgobj.img.src = this.base_uploaded_url + imgobj.server;
				} else {
					imgobj.img.src = this.base_upload_url + imgobj.server;
				}
			}
			return imgobj.img;
		} else
			return null;
	},
/**
 * 
 * 동영상 여부 확인
 * @param {object} imgobj  파일 Object
 * @return  {string} 동영상 경로 || null
 */
	isMovie : function(imgobj) {
		if (imgobj.extension != null && imgobj.extension.match(/(asf|mp3|mpeg|avi|wav|asx|wmv|wma|flv)$/i)) {
			return this.base_upload_url + imgobj.server;
		} else
			return null;
	},
/**
 * IE 7 버그 확인
 * @return  {boolean} ie7 & xp 여부 확인
 */
	checkIE7XP : function() {
		var UserAgentState = navigator.userAgent.toLowerCase();
		if (UserAgentState.indexOf('msie 7.0') != -1 && UserAgentState.indexOf('windows nt 5.1') != -1)
			return true;
		else
			return false;
	},
/**
 * 음악 파일 여부 확인
 * @param {object} imgobj  파일 Object
 * @return  {string} 음악 파일 경로 || null
 */
	isMusic : function(imgobj) {
		if (imgobj.extension != null && imgobj.extension.match(/(mp3|wav|wma)$/i)) {
			return this.base_upload_url + imgobj.server;
		} else
			return null;
	},
/**
 * 업로드 된파일 여부 확인
 * @param  {object} imgobj  파일 Object
 * @return  {boolean} true|false
 */
	isUploaded : function(imgobj) {
		return !(imgobj.server.match(/(^http:)|(^ftp:)|(^https:)|(^mms:)/i));
	},
/**
 * 태그 만들기
 * @param  {object} imgobj  파일 Object
 * @param  {string} tagalign  정렬
 * @param  {boolean} download  다운로드 적용여부
 * @param  {boolean} use_exra  Extra 정보 사용여부
 * @param  {int} img_width  이미지|동영상가로
 * @param  {int} img_height 이미지|동영상세로
 * @param  {string} sign 싸인
 * @return  {string} html
 */
	makeTag : function (imgobj, tagalign, download, use_exra, img_width, img_height, sign) {
		var str = '' , file_url = '', movie_url_img = '';
		var base_width = 400, base_height = 300;
		if (imgobj.server != '') {
			if (img_width != undefined)
				base_width = img_width;
			if (img_height != undefined)
				base_height = img_height;
			if (this.isUploaded(imgobj)) {
				if (this.use_mediaplayer && imgobj.extension =='flv') {
					file_url = this.base_upload_url + imgobj.server;
					if (imgobj.extra != '')
						movie_url_img = this.base_upload_url + imgobj.extra;
				} else  
					file_url = this.base_upload_url+imgobj.server;
			} else
				file_url = imgobj.server;
			var file_align = '', tag_pre = '', tag_end = '' ;
			switch(tagalign) {
				case 'L' : 
					file_align = ' align=left ';
					break;
				case 'C' : 
					tag_pre = '<div align=center width=100%>';
					tag_end = '</div><br>';
					break;
				case 'R' : 
					file_align = ' align=right ';
					break;
				default : 
					file_align = '';
					break;
			}
			if (file_url == '') {
				return '';
			} else if (this.isImage(imgobj)) {
				str = tag_pre + '<img src="' + file_url + '" alt="'+imgobj.fileName+'"  border=0 class=cafenimg_resize  '+file_align+'>' + tag_end;
			} else if (this.media_autotag && this.isMusic(imgobj)) {
				str = this.getMediaPlayer(file_url, '', base_width, 20, file_align, tag_pre, tag_end);
			} else if (this.media_autotag && this.isMovie(imgobj)) {
				str = this.getMediaPlayer(file_url, movie_url_img, base_width, base_height, file_align, tag_pre, tag_end);
			} else if (this.media_autotag && imgobj.extension.match(/swf$/i)) {
				str = tag_pre + '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="'+imgobj.width+'" height="'+imgobj.height+'"'+file_align+'>'
					+ '<param name="movie" value="' + file_url + '">'
					+ '<param name="quality" value="high">'
					+ '<param name="wmode" value="transparent">'
					+ '<embed src="'+ file_url +'" width="'+base_width+'" height="'+base_width+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent"></embed>'
					+ '</OBJECT>' + tag_end;
			} else if(download) {
				if (cafenAttach_loader.editorBaseConf.downloadSCRIPT != null && cafenAttach_loader.editorBaseConf.downloadSCRIPT != '')
					file_url = cafenAttach_loader.editorBaseConf.downloadSCRIPT + '?fn=' + imgobj.server + '&dn=' +encodeURIComponent(imgobj.fileName);
				var filetxt = '<img src='+this.getAttachIcon(imgobj.extension, true)+' border=0 hspace=2 vspace=2 align=absmiddle> <a href="'+file_url+'">' + imgobj.fileName;
					+ '</a>';
				if (file_align != '')
					str = '<div '+file_align+'>'+filetxt+'</div>';
				else
					str = tag_pre + filetxt +tag_end ;
			} else 
				str = '';
		}
		return str;
		
	},
	getMediaPlayerParam : function(use_logo) {
		var params = '';
		if (use_logo && this.mediaplayer_info.logo != '')
			params += '&amp;logo=' + this.mediaplayer_info.logo;
		if (this.mediaplayer_info.backColor != '')
			params += '&amp;backcolor=' + this.mediaplayer_info.backColor;
		if (this.mediaplayer_info.frontColor != '')
			params += '&amp;frontcolor=' + this.mediaplayer_info.frontColor;
		return params;
	},

/**
 * 미디어 태그 만들기
 * @param {string} file_url  파일 Object
 * @param {string} movie_url_img  정렬
 * @param {int} img_width  이미지|동영상가로
 * @param  {int} img_height 이미지|동영상세로
 * @param  {string} file_align  정렬
 * @param  {string} tag_pre  태그 앞첨자
 * @param  {string} tag_end  태그 뒤첨자
 * @return  {string} html
 */
	getMediaPlayer : function(file_url, movie_url_img, base_width, base_height, file_align,tag_pre, tag_end) {
		var str = '';
		if (this.use_mediaplayer && file_url.match(/\.flv$/i)) {
			if (movie_url_img != '') {
				str = tag_pre + '<embed  id=cafenmedia_resize src="'+this.base_image_url+'mediaplayer.swf" '
					+ 'width="'+ base_width +'" height="'+ base_height +'" allowfullscreen="true" '
					+ 'flashvars="file='+ file_url+'&amp;image='+ movie_url_img+'&amp;height='+base_height + this.getMediaPlayerParam(true)
					+ '&width='+base_width+'&autostart=false&overstretch=true"'
					+ ' wmode="transparent" '+file_align+'></embed>' + tag_end;
			} else {
				str = tag_pre + '<embed id=cafenmedia_resize src="'+this.base_image_url+'mediaplayer.swf" '
					+ 'width="'+base_width+'" height="20" allowfullscreen="true" '
					+ 'flashvars="file='+ file_url+'&amp;height=20'+ this.getMediaPlayerParam(true)
					+ '&amp;width='+base_width+'&amp;autostart=false"'
					+ ' wmode="transparent" '+file_align+'></embed>' + tag_end;
			}
		} else {
			if (	movie_url_img != '') {
				str = tag_pre + '<embed  src="'+file_url+'" '
					+ 'width="'+base_width+'" height="'+base_height+'" autostart=false '
					+ ' wmode="transparent" '+file_align+'></embed>' + tag_end;
			} else {
				str = tag_pre + '<embed  src="'+file_url+'" '
					+ 'width="'+base_width+'" height="20"  autostart=false '
					+ ' wmode="transparent" '+file_align+'></embed>' + tag_end;
			}
		}
		return str;
	},
	/**
 * Upload 초기화
 */
	initUpload : function() {}
}


var cafenAttach_HTC = new cafenAttach();

cafen.checkLoad();


