Ext.ns('component.gvd');

component.gvd.upload = new function() {
	
	this.path = null;
	this.swfu = null;
	this.base = null;
	this.counter = 0;
	
	this.init = function(path, base) {
		this.path = path;
		this.base = base;
		
		this.swfu = new SWFUpload({
			upload_url : this.base + "components/com_gvd_showcompany/upload.php", 
			flash_url :  "lib/swfupload/Flash/swfupload.swf", 
			
			// Button
			button_placeholder_id : "file-select",
			button_width: "101",
			button_height: "18",
			button_text: '',
			button_cursor : SWFUpload.CURSOR.HAND,
			button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
			
			// Debug
			debug: false,
			
			// Event Handlers
			file_queued_handler: this.fileQueued,
			upload_success_handler: this.uploadSuccess,
			upload_complete_handler: this.uploadComplete,
			upload_progress_handler: this.fileProgress
		});
		
//		this.swfu.addPostParam('path', this.path);
	};
	
	this.fileQueued = function(file) {
		var html = '<div class="file" id="' + file.id + '"><table class="upload"><tr><td class="name"><a href="#" onclick="component.gvd.upload.removeFileFromUpload(\'' + file.id + '\'); return false;">' + file.name + '</a></td><td class="progress" id="progress-' + file.id + '"><div id="progress-bar-' + file.id + '" class="progress-bar"></div></td></tr></table></div>';
		
		if(component.gvd.upload.counter == 0) Ext.get('upload-images').update(' ');
		Ext.get('upload-images').insertHtml('beforeEnd', html);
		component.gvd.upload.counter += 1;
	};
	
	this.removeFileFromUpload = function(id) {
		var field = Ext.get(id);
		
		if(field != null) {
			field.setOpacity(0, {duration: .5});
			field.setHeight(0, {duration: .5, callback: function() { Ext.get(id).remove(); } });
			this.swfu.cancelUpload(id);
		}
	};
	
	this.uploadComplete = function(file) {
		this.startUpload();
	};
	
	this.startUpload = function() {
		this.swfu.addPostParam('path', this.path);
		this.swfu.startUpload();
	};
	
	this.uploadSuccess = function(file, data) {
		if(data != '') {
			var error = Ext.get('progress-' + file.id);
			error.update(data);
		} else {
			//Ext.get(file.id).remove();
			/*setTimeout(function() { 
				var field = Ext.get(file.id);
				
				field.setOpacity(0, {duration: .5});
				field.setHeight(0, {duration: .5, callback: function() { Ext.get(file.id).remove(); } });
				
			}, 1000);*/
			Ext.get('progress-bar-' + file.id).update('Fertig!');
		}
	};
	
	this.fileProgress = function(file, completed, total) {
		var progress = Ext.get('progress-bar-' + file.id);
		
		percent = Math.round((completed/total) * 100);
		
		if(percent == 100) {
			progress.update('Generiere Thumbnails');
			progress.setWidth(200);
		} else {
			progress.update(percent + ' %');
			progress.setWidth(percent * 2);
		}
	};
	
};
