var SingleUploader = Class.create();
Object.extend(Object.extend(SingleUploader.prototype, Window.prototype), {
	initialize : function(option) {
		this._initialize(option);
		this.buildUploadForm();
	},
	buildUploadForm : function() {
		var dummy = this.buildElement(this.contentFooter, null, {display: "none"});
		dummy.innerHTML = "<iframe name='singleUploader'></iframe>";
		this.formUpload = this.buildElement(this.contentFooter, {elementName : "form", method: "post",
		target: "singleUploader"});
		this.btnFile = this.buildElement(this.formUpload, {elementName: "input", type: "file",
		name: "uploadFile"});
		this.btnFile.setStyle({float: "left"});
		this.btnUpload = this.buildElement(this.contentFooter, {elementName: "input", type: "button",
		value : "업로드 시작"});
		Event.observe(this.btnUpload, "click", this.upload.bind(this));
		this.formUpload.encoding = "multipart/form-data";
		this.setStatusMessage("");
		this.setProcessed(0);
	},
	upload : function() {
		var param = $H({uploadPath : this.parent.rootFolderName + this.parent.folderName});
		var action = "content/jsp/file/HelloUploader.jsp?" + param.toQueryString();
		this.formUpload.setAttribute("action", action);
		this.uploadUpdater = new Ajax.PeriodicalUpdater(this.statusmessage, "content/jsp/file/HelloUploaderReport.jsp", {
		frequency : 0.1, onSuccess : function(response) {
			this.displayProcess(response.responseXML.firstChild.firstChild);
		}.bind(this)});
		Event.stopObserving("singleUploader", "load", this.onReadyWrittenFileName);
		Event.observe("singleUploader", "load", this.onReadyWrittenFileName);
		this.formUpload.submit();
	},
	displayProcess : function(elem) {
		while(elem) {
			this[elem.tagName] = elem.firstChild.nodeValue;
			elem = elem.nextSibling;
		}
		this.setProcessed(this.processed); 
		this.setStatusMessage(this.bps);
		if(100 == this.processed) {
			this.count = this.count || 0;
			++this.count;
			if(this.count > 1) {
				this.count = 0;
				this.processed = 0;
				this.uploadUpdater.stop();
				return;
			}
			this.onUploadCompleted();
		}
	},
	onUploadCompleted : function() {
		alert("업로드가 완료 되었습니다.");
		this.parent.request();
	},
	originalFileName : function() {
		var fileName = this.btnFile.getValue();
		var start = fileName.lastIndexOf("/");
		if(-1 == start) start = fileName.lastIndexOf("\\") + 1;
		return fileName.substring(start);	
	},
	onReadyWrittenFileName : function(evt) {
		if(this._onReadyWrittenFileName)
			this._onReadyWrittenFileName(evt);
	},
	_onReadyWrittenFileName : function(evt) {
		var uploaderFrame = $("singleUploader");
		var doc = uploaderFrame.contentWindow || uploaderFrame.contentDocument;
		if(doc.document) doc = doc.document;
		var fileName = doc.body.innerHTML;
		this.writtenFileName = fileName.substring(0, fileName.length-1);
	}
});