uploads = {};
lang.fupload = {
	'es':{load_prev:'Cargando prevista',
		  browse:'Elegir',
		  no_file:'Ningun archivo seleccionado...'},
	'en':{load_prev:'Loading preview',
		  browse:'Browse',
		  no_file:'No file selected'}
};

FileUpload = Class.create();
FileUpload.prototype = {
	
	initialize: function(parent, id, app, preview, format, options) {
		//var cur_lang = cur_lang || 'en';
		this.id = id;
		this.self = $(this.id);
		
		this.options = options || {};
		
		this.app = app;
		this.format = format;
		this.input = $(this.id + '_input');
		this.parent = parent;
		this.cur_file = $(this.id + '_cur_file');
		this.preview = $(preview) || null;
		this.browse = new ButtonComponent(this, this.id+'_browse', 'browse', lang.fupload[cur_lang].browse, '');
		
		
		var me = this;
		page_init.scripts['lister_'+this.id] = function() {
			if (ax_forms[me.parent]) ax_forms[me.parent].register(me);
		};
		
		
		this.injectBehaviours();
		
		
	},
	
	injectBehaviours: function() {
		//if (console) console.log(this.form.id);
		//if (console) console.log("BROWSE BUTTON: " + this.browse.id);
		this.input.onchange = this.changeHandler.bindAsEventListener(this);	
	},
	
	changeHandler: function(e) {
		this.submitTo('/services/system.getImagePreview' + '?id=' + this.id + '&name=' + this.input.name + '&app=' + this.app + '&format=' + this.format);
		this.cur_file.innerHTML = ApexUtil.formatLabel(this.input.value, 40);
	},
	
	previewResults: function(html, tmp_name) {
		if (typeof(this.parent) == 'string') this.parent = ax_forms[this.parent];
		if (typeof(this.parent.status) != 'undefined') this.parent.status.hide();
		this.preview.innerHTML = html;	
		var val = $(this.id+'_hidden_field').value;
		if (tmp_name) $(this.id+'_hidden_field').value = tmp_name;
		if (console) console.log('field saved: ' + tmp_name);
	},
	
	onClearForm: function() {
		this.cur_file.innerHTML = lang.fupload[cur_lang].no_file;
		this.input.value = '';
		this.preview.innerHTML = '&nbsp;';
	},
	
	submitTo: function(action) {
		if (typeof(this.parent) == 'string') this.parent = ax_forms[this.parent];
		this.form = this.parent.form || this.parent.self;
		
		if (this.preview && this.form) {
			if (typeof(this.parent.status) != 'undefined') this.parent.status.show(lang.fupload[cur_lang].load_prev);
			var prev_form = {action:this.form.action,
							 target:this.form.target
							};
			this.form.action = action;
			this.form.target = this.id + '_hidden_frame';
			this.form.submit();
			this.form.action = prev_form.action;
			this.form.target = prev_form.target;
		}
	}
		
};
