/**
 * FancyUpload.Attach - Flash meets Ajax for powerful and elegant uploads.
 *
 * @version		3.0 rc3
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */

if (!window.FancyUpload3_single4redigo) var FancyUpload3_single4redigo = {};

FancyUpload3_single4redigo.Attach = new Class({

	Extends: Swiff.Uploader,
	
	options: {
		queued: false,
		instantStart: true,
		fileSizeMax: 16 * 1024 * 1024,		
		verbose: true	
	},

	initialize: function(list, selects, options) {
		this.list = $(list);
		this.selects = $(selects) ? $$($(selects)) : $$(selects);
				
		options.target = this.selects[0];
		options.fileClass = options.fileClass || FancyUpload3_single4redigo.Attach.File;
		
		this.parent(options);

		/**
		 * Button state
		 */
		var self = this;
		
		this.selects.addEvents({
			click: function() {
				return false;
			},
			mouseenter: function() {
				this.addClass('hover');
				self.reposition();
			},
			mouseleave: function() {
				this.removeClass('hover');
				this.blur();
			},
			mousedown: function() {
				this.focus();
			}
		});
		
		if (this.selects.length == 2) {
			this.selects[1].setStyle('display', 'none');
			this.addEvents({
				'selectSuccess': this.onSelectSuccess,
				'fileRemove': this.onFileRemove
			});
		}
	},
	
	onSelectSuccess: function() {
		if (this.fileList.length > 0) {
			this.selects[0].setStyle('display', 'none');
			this.selects[1].setStyle('display', 'inline');
			this.target = this.selects[1];
			this.reposition();
		}
	},
	
	onFileRemove: function() {
		if (this.fileList.length == 0) {
			this.selects[0].setStyle('display', 'inline');
			this.selects[1].setStyle('display', 'none');
			this.target = this.selects[0];
			this.reposition();
		}
	},
	
	start: function() {
		this.selects[0].setStyle("display","none");
// 		if (Browser.Platform.linux && window.confirm(MooTools.lang.get('FancyUpload', 'linuxWarning'))) return this;
		return this.parent();
	}
	
});

FancyUpload3_single4redigo.Attach.File = new Class({

	Extends: Swiff.Uploader.File,

	render: function() {
		
		if (this.invalid) {
			if (this.validationError) {
				var msg = MooTools.lang.get('FancyUpload', 'validationErrors')[this.validationError] || this.validationError;
				this.validationErrorMessage = msg.substitute({
					name: this.name,
					size: Swiff.Uploader.formatUnit(this.size, 'b'),
					fileSizeMin: Swiff.Uploader.formatUnit(this.base.options.fileSizeMin || 0, 'b'),
					fileSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileSizeMax || 0, 'b'),
					fileListMax: this.base.options.fileListMax || 0,
					fileListSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileListSizeMax || 0, 'b')
				});
			}
			this.remove();
			return;
		}
		
		if (this.name.length>this.base.options.fileNameSize){
			var bottone=this.base.target.id;
			this.remove();
			var myFunction = function(){ $(bottone).setStyle("display","block"); };
			myFunction.delay(500);
			return;
		}
		
		this.addEvents({
			'open': this.onOpen,
			'remove': this.onRemove,
			'requeue': this.onRequeue,
			'progress': this.onProgress,
			'stop': this.onStop,
			'complete': this.onComplete,
			'error': this.onError
		});
		
		this.ui = {};

		this.ui.element = new Element('li', {'class': 'file', id: this.base.id+'_file-' + this.id});
		this.ui.title = new Element('span', {'class': 'file-title', text: this.name});
		this.ui.size = new Element('span', {'class': 'file-size', text: Swiff.Uploader.formatUnit(this.size, 'b')});
		
		this.ui.cancel = new Element('a', {'class': 'file-cancel', text: 'Cancel', href: '#'});
		this.ui.cancel.addEvent('click', function() {
			this.remove();
			this.ui.element.getParent().getParent().getElement("a.attach-button").setStyle("display","block");
			return false;
		}.bind(this));
		
		this.ui.element.adopt(
			this.ui.title,
			this.ui.size,
			this.ui.cancel
		).inject(this.base.list).highlight();
		
		var progress = new Element('img', {'class': 'file-progress', src: 'http://redigo.gonet.it/libraries/FancyUpload3/assets/progress-bar/bar.gif'}).inject(this.ui.size, 'after');
		this.ui.progress = new Fx.ProgressBar(progress, {
			fit: true
		}).set(0);
					
		this.base.reposition();

		return this.parent();
	},

	onOpen: function() {
		this.ui.element.addClass('file-uploading');
		if (this.ui.progress) this.ui.progress.set(0);
	},

	onRemove: function() {
		this.ui = this.ui.element.destroy();
	},

	onProgress: function() {
		if (this.ui.progress) this.ui.progress.start(this.progress.percentLoaded);
	},

	onStop: function() {
		this.remove();
	},
	
	onComplete: function() {
		this.ui.element.removeClass('file-uploading');

		if (this.response.error) {
			var msg = MooTools.lang.get('FancyUpload', 'errors')[this.response.error] || '{error} #{code}';
			this.errorMessage = msg.substitute($extend({name: this.name}, this.response));
			
			this.base.fireEvent('fileError', [this, this.response, this.errorMessage]);
			this.fireEvent('error', [this, this.response, this.errorMessage]);
			return;
		}

		
		var php_return = JSON.decode(this.response.text);
		
		HTML_ID=$(this.ui.element.id).getParent().id.replace("attach-list_","");
		fileName4get=php_return.sysRedigoDIR_uploadedfiles+php_return.newname;
		
		temp_A = new Element('a', {text: php_return.name, href: 'fileupload.get.php?fileName='+fileName4get});
		$(this.ui.element.id).getElement('span.file-title').empty();
		temp_A.inject($(this.ui.element.id).getElement('span.file-title'));
		
		if (this.ui.progress) this.ui.progress = this.ui.progress.cancel().element.destroy();
		if (this.ui.cancel) this.ui.cancel = this.ui.cancel.destroy();

		if($(this.ui.element.id).getElement('img.file-progress')) $(this.ui.element.id).getElement('img.file-progress').destroy();
		if($(this.ui.element.id).getElement('a.file-cancel')) $(this.ui.element.id).getElement('a.file-cancel').destroy();

		this.ui.unlink = new Element('a', {'class': 'file-remove', text: 'Rimuovi', href: '#'});
		this.ui.unlink.addEvent('click', function() {
			// UNLINK
			$(this.ui.element.id).getParent().getParent().getElement("a.attach-button").setStyle("display","block");
			this.base.list.empty();
			$(HTML_ID).value="";
			return false;
		}.bind(this));	
		
		$(this.ui.element.id).adopt(
			this.ui.unlink
		).inject(this.base.list).highlight();

		$(HTML_ID).value=php_return.newname;
		
		var response = this.response.text || '';
		this.base.fireEvent('fileSuccess', [this, response]);
	},

	onError: function() {
		this.ui.element.addClass('file-failed');		
	},

	onSelectFail: function(files) {
		files.each(function(file) {
			new Element('li', {
				'class': 'file-invalid',
				events: {
					click: function() {
						this.destroy();
					}
				}
			}).adopt(
				new Element('span', {html: file.validationErrorMessage || file.validationError})
			).inject(this.list, 'bottom');
		}, this);	
	},
	
	onFileSuccess: function(file) {
		file.ui.element.highlight('#e6efc2');
	},
	
	onFileError: function(file) {
		file.ui.cancel.set('html', 'Retry').removeEvents().addEvent('click', function() {
			file.requeue();
			return false;
		});
		
		new Element('span', {
			html: file.errorMessage,
			'class': 'file-error'
		}).inject(file.ui.cancel, 'after');
	},
	
	onFileRequeue: function(file) {
		file.ui.element.getElement('.file-error').destroy();
		
			file.ui.cancel.set('html', 'Cancel').removeEvents().addEvent('click', function() {
			file.remove();
			this.ui.element.getParent().getParent().getElement("a.attach-button").setStyle("display","block");
			return false;
		});
		
		this.start();
	}
});

//Avoiding MooTools.lang dependency
(function() {
	
	var phrases = {
		'fileName': '{name}',
		'cancel': 'Cancel',
		'cancelTitle': 'Click to cancel and remove this entry.',
		'validationErrors': {
			'duplicate': 'File <em>{name}</em> is already added, duplicates are not allowed.',
			'sizeLimitMin': 'File <em>{name}</em> (<em>{size}</em>) is too small, the minimal file size is {fileSizeMin}.',
			'sizeLimitMax': 'File <em>{name}</em> (<em>{size}</em>) is too big, the maximal file size is <em>{fileSizeMax}</em>.',
			'fileListMax': 'File <em>{name}</em> could not be added, amount of <em>{fileListMax} files</em> exceeded.',
			'fileListSizeMax': 'File <em>{name}</em> (<em>{size}</em>) is too big, overall filesize of <em>{fileListSizeMax}</em> exceeded.'
		},
		'errors': {
			'httpStatus': 'Server returned HTTP-Status #{code}',
			'securityError': 'Security error occured ({text})',
			'ioError': 'Error caused a send or load operation to fail ({text})'
		},
		'linuxWarning': 'Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nDo you want to start the upload anyway?'
	};
	
	if (MooTools.lang) {
		MooTools.lang.set('it-IT', 'FancyUpload', phrases);
	} else {
		MooTools.lang = {
			get: function(from, key) {
				return phrases[key];
			}
		};
	}
	
})();