Form.FileInput = Base.extend({
	files: [],
	constructor: function(hiddenInput) {
		this.input = $(hiddenInput);
		this.action = this.input.attr('href');
		this.name = 'file';
		this.findLabelElement();
		this.multiple = this.input.attr('multiple') || false;
		this.params = {};
		this.params.removeUrl = this.input.attr('removeUrl') || null;
		this.params.descriptions = this.input.attr('descriptions') || null;
		
		this.extractImagesFromValue();
		this.draw();
		this.initValums();
	},
	
	draw: function () {
		this.drawButton();
		this.drawImages();
	},
	
	drawButton: function () {
		this.button = $('<button></button>').text(this.getButtonLabel()).addClass('button-element');
		this.input.after(this.button);
	},
	
	drawImages: function () {
		this.input.after($('<div></div>').addClass('clear'));
		this.imagesDiv = $('<div></div>').addClass('ajax-image-element-images');
		this.input.after(this.imagesDiv);
		this.redrawImages();
	},
	
	drawImage: function (image) {
		var self = this;
		var imagePath = image.path;
		var pathParts = imagePath.split('/');
		var basename = pathParts.pop();
		var node = $('<span></span>').addClass('image-wrapper').append(
			$('<a></a>').addClass('image image-link').attr('href', imagePath),
			$('<a>x</a>').addClass('file-remover').click(function () {
				var position = $(this).parent().prevAll('.image-wrapper').length; 
				self.removeImage(position); 
			})
		);
		this.imagesDiv.append(node);
		node.find('.image').append(basename);
		
		if(this.params.descriptions) {
			node.append(this.drawDescription(image));
		}
	},
	
	drawDescription: function (image) {
		var self = this;
		var node = $('<div></div>').text(image.description || '').addClass('image-description');
		if (!image.description) {
			node.text('Brak opisu - kliknij aby edytować').addClass('no-description');
			
		}
		node.click(function () {
			// creating form
			var form = $('<form></form>').append(
				
				// creating text input, assigning description as value
				$('<input />').attr('type', 'text').addClass('text-element').val(
					$(this).hasClass('no-description') ? '' : $(this).html()
				),
				
				// adding submit button
				$('<input />').attr('type', 'submit').addClass('submit-element').val('Zapisz'),
				
				// adding cancel button - which reverses changes, binding cancel action
				$('<button></button>').text('Anuluj').click(function() {
					
					// replacing form with redrawn description div
					var form = $(this).parent();
					form.replaceWith(self.drawDescription(image));
					return false;
				})
			);
			
			// binding on submit function
			form.submit(function () {
				var form = $(this);
				$.ajax({
					url: '/admin/index/set-file-description',
					data: {id: image.id, description: form.find('.text-element').val()},
					success: function (response) {
						var response = jZend.Response(response);
						if (response.isValid()) {
							var position = form.parent().prevAll('.image-wrapper').length;
							self.images[position] = response.file;
							self.redrawImages();
						}
					}
				}) 
				return false;
			});
			
			// replacing div with created form
			$(this).replaceWith(form);
			// focusing first element
			form.find(':input').first().focus();
		});
		
		return node;
	},
	
	extractImagesFromValue: function () {
		this.images = [];
		if (!this.input.val())
			return;
		this.images = $.parseJSON(this.input.val()) || [];
		this.setValueFromImages();
	},
	
	redrawImages: function () {
		this.imagesDiv.html('');
		for (i in this.images) {
			this.drawImage(this.images[i]);
		}
	},
	
	addImage: function (image) {
		if (!this.multiple)
			this.images = [];
		this.images.push(image);
		this.redrawImages();
	},
	
	setValueFromImages: function () {
		var ids = $.map(this.images, function (element) {
			return element.id;
		});
		this.input.val(ids.join(':'));
	},
	
	getButtonLabel: function () {
		return this.input.attr('alt') || 'Dodaj plik';
	},
	
	findLabelElement: function () {
		
		// label search
		if (this.input.prev('label').length)
			this.label = this.input.prev('label');
		if (this.input.parent().prev('label').length)
			this.label = this.input.parent().prev('label');
		if (this.input.parent().prev().find('label').length)
			this.label = this.input.parent().prev().find('label');
	},
	
	initValums: function () {
		var self = this;
		new AjaxUpload(this.button, {
			action: this.action, 
			name: this.name,
			responseType: 'json',
			onSubmit: function (file, extension) {
				self.onSubmit.call(self, file, extension);
			},
			onComplete: function (file, response) {
				self.onComplete.call(self, file, response);
			}
		});
	},
	
	onSubmit: function (file, extension) {
		
	},
	
	onComplete: function (file, response) {
		var response = new jZend.Response(response);
		if (response.isValid()) {
			this.addImage(response.file);
			this.setValueFromImages();
		}
	},
	removeImage: function (position) {
		var pos = position;
		var self = this;
		if(this.params.removeUrl) {
			$.ajax({
				url: this.params.removeUrl,
				type: 'POST',
				data: {id: this.images[position].id},
				success: function (response) {
					var response = new jZend.Response(response);
					if (response.isValid()) {
						self._removeImage(pos);
					}
				}
			});
		} else {
			this._removeImage(pos);
		}
	},
	_removeImage: function (position) {
		var images = [];
		for (i in this.images) {
			if (i != position)
				images.push(this.images[i]);
		}
		this.images = images;
		this.redrawImages();
	}
});


/*

var AjaxUploadButton = Base.extend({
	constructor: function (element, params) {
		var self = this, defaults = {
			action: '/upload',
			name: 'file'
		};
	
		this.button = $(element);
		this.enable();
		this.extend( extend(defaults, params) );
		this.action = this.url || this.action;
		
		if (this.callback) {
			var callback = new this.callback(this);
			new AjaxUpload(this.button, {
				action: this.action, 
				name: this.name,
				responseType: 'json',
				onSubmit: function (file, extension) {
					if (callback.pre(file, extension) === false)
						return false;
				},
				onComplete: function (file, response) {
					callback.post(response, file);
					callback.takeAction(response, file);
				}		
			});
			
		} else {
			
		}
	},
	onSubmit: function (file, extension) {
		// starting action
		this.disable();
	},
	onComplete: function (file, response) {
		// action on complete
		this.enable();
	},
	enable: function () {
		this.button.attr('disabled', false);
	},
	disable: function () {
		this.button.attr('disabled', true);
	}
});

var AjaxFileInput = Base.extend({
	params: {
		multiple: false,
		url: '/admin/index/upload-file',
		buttonLabel: 'Dodaj plik',
		callback: FileUploadCallback
	},
	constructor: function (element, params) {
		this.input = $(element);
		// label search
		if (this.input.prev('label').length)
			this.label = this.input.prev('label');
		if (this.input.parent().prev('label').length)
			this.label = this.input.parent().prev('label');
		if (this.input.parent().prev().find('label').length)
			this.label = this.input.parent().prev().find('label');
		
		if (this.input.attr('src'))
			this.params.callback = eval(this.input.attr('src'));
		
		if (this.input.attr('href'))
			this.params.url = this.input.attr('href');

		this.params = extend(this.params, params);
		this.files = this.input.val() ? this.input.val().split(':') : [];
		this.area = ui.div().addClass('ajax-file-area');
		this.button = ui.button(this.input.attr('alt') || this.params.buttonLabel).addClass('ajax-file-button');
		this.input.after(this.area, ui.div().addClass('clear'), this.button);
		// this.area.sortable({items: '.thumb'});
		new AjaxUploadButton(this.button, this.extend(this.params));
	},
	addFile: function (file) {
		if (!this.params.multiple) {
			this.setFile(file);
		} else {
			this.files.push(file);
			this.input.val(this.files.join(':'));
		}
	},
	setFile: function (file) {
		this.removeFile();
		this.files = [file];
		this.input.val(this.files.join(':'));
	}, 
	removeFile: function (number) {
		if (this.params.multiple) {
			var files = [], deleted = false;
			for (i in this.files) {
				if (i == number) {
					deleted = true;
				} else {
					files.push(this.files[i]);
				}
			}
			if (!deleted)
				new Error('Cannot find file.');
			this.files = files;
		} else {
			this.area.empty();
			this.files = [];
			var deleted = true;
		}
		this.input.val(this.files.join(':'));
		return deleted;
	}
});

var AjaxImageInput = AjaxFileInput.extend({
	params: {
		multiple: false,
		url: '/admin/index/upload-image',
		callback: ImageUploadCallback
	}
});
*/
