/**
 * FancyUpload - Flash meets Ajax for powerful and elegant uploads.
 * 
 * Updated to latest 3.0 API. Hopefully 100% compat!
 *
 * @version		3.0
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <http://digitarald.de>
 * @copyright	Authors
 */

var FancyUpload2 = new Class({

	Extends: Swiff.Uploader,
	options: {
		queued: 1,
		// compat
		limitSize: 0,
		limitFiles: 0,
		validateFile: $lambda(true)
	},

	initialize: function(status, list, options) {
		this.status = $(status);
		this.list = $(list);

		// compat
		options.fileClass = options.fileClass || FancyUpload2.File;
		options.fileSizeMax = options.limitSize || options.fileSizeMax;
		options.fileListMax = options.limitFiles || options.fileListMax;

		this.parent(options);

		this.addEvents({
			'load': this.render,
			'select': this.onSelect,
			'cancel': this.onCancel,
			'start': this.onStart,
			'queue': this.onQueue,
			'complete': this.onComplete
		});
	},

	render: function() {
		this.overallTitle = this.status.getElement('.overall-title');
		this.currentTitle = this.status.getElement('.current-title');
		this.currentText = this.status.getElement('.current-text');

		var progress = this.status.getElement('.overall-progress');
		this.overallProgress = new Fx.ProgressBar(progress, {
			text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after')
		});
		progress = this.status.getElement('.current-progress')
		this.currentProgress = new Fx.ProgressBar(progress, {
			text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after')
		});
				
		this.updateOverall();
	},

	onSelect: function() {
		this.status.removeClass('status-browsing');
	},
	
	onSelectSuccess: function() {
		if (this.size && $('job_type').value == 'print') {
			var fname = MooTools.lang.get('FancyUpload', 'fileName').substitute(this) + '_' + $('current_batch').value;
			 this.el = new Element('li', {'class': 'file-options'}).adopt(
				new Element('span', {'class': 'dummy1', 'html': ''}),
				new Element('span', {'class': 'dummy2', 'html': ''}),
				new Element('select', {
							'class': 'product-select',
							'name': 'product_' + MooTools.lang.get('FancyUpload', 'fileName').substitute(this)
						}),
				new Element('span', {'class': 'product-select-label', 'html': 'product'}),
				new Element('select', {
					'class': 'qty-select',
					'name': 'qty_' + MooTools.lang.get('FancyUpload', 'fileName').substitute(this)
				}),
				new Element('span', {'class': 'qty-select-label', 'html': 'qty'}),
				new Element('span', {'class': 'batch-label', 'html': 'Batch Change'}),
				new Element('input', {
					'type': 'hidden',
					'name': 'main-batch',
					'id': 'main-batch',
					'value': $('current_batch').value
				}),
				new Element('input', {
					'type': 'text',
					'class': 'custom-product',
					'name': 'custom_' + MooTools.lang.get('FancyUpload', 'fileName').substitute(this)
				}),
				new Element('span', {
					'class': 'custom-label',
					'html': 'custom product'
				})
			);

			this.list.adopt(this.el);
			
			
				new Request({
				method: 'post',
				url: '/products/getproducts/',
				onRequest: function() {  },
				onComplete: function(response)
				{
		
					var select = new Element('select', {
						'class': 'product-select',
						'name': 'product_' + MooTools.lang.get('FancyUpload', 'fileName').substitute(this)
					});
					
					
					var children = this.el.getChildren();
					var custom = children[8];
					var custom_label = children[9];
					var batch = children[7];
					var select = children[2];
					var qty = children[4];
					var qty_label = children[5];
					var select_label = children[3];
					
					//add event to spread
					custom.addEvent('keyup', function(e){
						$$('.batch').each(function(el) {
							if(el.value == batch.value)
							{
								//get that lis select
								var kids = el.getParent().getChildren();

								var child_custom = kids[7];
								var child_custom_label = kids[8];
								
								child_custom.value = custom.value;
							}
						});
					});
					
					
					//setup change functionality
					select.addEvent('change', function(e){
						$$('.batch').each(function(el) {
							if(el.value == batch.value)
							{
								//get that lis select
								var kids = el.getParent().getChildren();
								var sel = kids[2];
								var child_custom = kids[7];
								var child_custom_label = kids[8];
								
								//set the option
								 var options = sel.getElements('option');
								 options.each(function(option) {
									if(option.value == select.value)
									{
										option.selected = true;
									}
								});
								
								
								//if other show textbox
								if(select.value == 0)
								{
									custom.setStyle('display','block');
									custom_label.setStyle('display','block');
									child_custom.setStyle('display','block');
									child_custom_label.setStyle('display','block');
								}
								else
								{
									custom.setStyle('display','none');
									custom_label.setStyle('display','none');
									child_custom.setStyle('display','none');
									child_custom_label.setStyle('display','none');
								}
							}
						});
					});
					
					qty.addEvent('change', function(e){
						$$('.batch').each(function(el) {
							if(el.value == batch.value)
							{
								//get that lis select
								var kids = el.getParent().getChildren();
								var q = kids[4];
								
								//set the option
								 var options = q.getElements('option');
								 options.each(function(option) {
									if(option.value == qty.value)
									{
										option.selected = true;
									}
								});
							}
						});
					});
					
					//this.element.adopt(select);
					
					var products = response.split(",");
					
					 var arLen=products.length;
					 for ( var i=0, len=arLen; i<len; ++i )
					 {

						  if(products[i] != '')
						  {
							  
								  var bits = products[i].split("_");
								  
								  var id = bits[0];
								  var name = bits[1];
								  
							
								//insert option into select
								var new_el = new Element('option', {'value': id});
								new_el.set('html', name);
								new_el.inject(select,'top');
				  			}

						}
						
						//insert option into select
						var new_el = new Element('option', {'value': '0'});
						new_el.set('html', 'other');
						new_el.inject(select,'top');
						
						//inject the qty options
						for(var i=1;i<51;i++)
						{
							//insert option into select
							var new_qty_el = new Element('option', {'value': i});
							new_qty_el.set('html', i);
							new_qty_el.inject(qty,'bottom');

						}
						
						if (typeof ie7=="undefined") {
							var ie7 = false;
						}
						
						if(ie7)
						{
							qty.setStyle('width', qty.getStyle('width').toInt());
							select.setStyle('width', select.getStyle('width').toInt());
						}
						
						//check for print or proof
						if($('job_type').value == 'proof')
						{
							qty.setStyle('display', 'none');
							select.setStyle('display', 'none');
							qty_label.setStyle('display', 'none');
							select_label.setStyle('display', 'none');
						}
				}.bind(this) 	
			}).send();
		}
		$('current_batch').value++;		
	},

	onCancel: function() {
		this.status.removeClass('file-browsing');
	},

	onStart: function() {
	
		$('generalProgress').setStyle('display','block');
		
				new Request({
				method: 'post',
				url: '/jobs/setToUploading/'+ $('job_id').value,
				onRequest: function() {  },
				onComplete: function(response)
				{}.bind(this) 	
			}).send();
		
		this.status.addClass('file-uploading');
		this.overallProgress.set(0);
	},

	onQueue: function() {
		this.updateOverall();	
	},

	onComplete: function() {
		this.status.removeClass('file-uploading');
		if (this.size) {
			this.overallProgress.start(100);
		} else {
			this.overallProgress.set(0);
			this.currentProgress.set(0);
		}
		
	},

	updateOverall: function() {
		this.overallTitle.set('html', MooTools.lang.get('FancyUpload', 'progressOverall').substitute({
			total: Swiff.Uploader.formatUnit(this.size, 'b')
		}));
		if (!this.size) {
			this.currentTitle.set('html', MooTools.lang.get('FancyUpload', 'currentTitle'));
			this.currentText.set('html', '');
		}
		
	},
	
	/**
	 * compat
	 */
	upload: function() {
		this.start();
	},
	
	removeFile: function() {
		return this.remove();
		
		//remove the options bar as well
		
	}

});

FancyUpload2.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;
		}
		
		this.addEvents({
			'start': this.onStart,
			'progress': this.onProgress,
			'complete': this.onComplete,
			'error': this.onError,
			'remove': this.onRemove
		});

		var fname = MooTools.lang.get('FancyUpload', 'fileName').substitute(this) + '_' + $('current_file').value;
		
		this.info = new Element('span', {'class': 'file-info'});
		this.element = new Element('li', {'class': 'file'}).adopt(
			new Element('a', {
				'class': 'file-remove',
				href: '#',
				html: MooTools.lang.get('FancyUpload', 'remove'),
				title: MooTools.lang.get('FancyUpload', 'removeTitle'),
				events: {
					click: function() {
						this.remove();
						
						//code to remove options bar
						var children = this.element.getChildren();
						var batch = children[6].value;
						var files_in_batch = 0;
						
						//count the files in the batch
						var images = $$('.file');
						images.each(function(image) {
							var fields = image.getChildren();
							if(fields[6].value == batch)
							{
								files_in_batch++;
							}
						});
						
						//remove batch box when last file removed
						if(files_in_batch == 1)
						{
							 var options = $$('.file-options');
							 options.each(function(option) {
								kids = option.getChildren();
								if(kids[7].value == batch)
								{
									option.destroy();
								}
							});
						}
						
						return false;
					}.bind(this)
				}
			}),
			new Element('span', {'class': 'file-size', 'html': Swiff.Uploader.formatUnit(this.size, 'b')}),
			new Element('select', {
						'class': 'product-select',
						'name': 'product_' + fname
					}),
				
				new Request({
				method: 'post',
				url: '/products/getproducts/',
				onRequest: function() {  },
				onComplete: function(response)
				{
		
					var select = new Element('select', {
						'class': 'product-select',
						'name': 'product_' + fname
					});
					
					
					var children = this.element.getChildren();
					var select = children[2];
					var select_label = children[3];
					var qty = children[4];
					var qty_label = children[5];
					var custom = children[7];
					var custom_label = children[8];
					
					
					//setup change functionality
					select.addEvent('change', function(){
						if(this.value == 0)
						{
							custom.setStyle('display','block');
							custom_label.setStyle('display','block');
						}
						else
						{
							custom.setStyle('display','none');
							custom_label.setStyle('display','none');
						}
					});
					
					
					//this.element.adopt(select);
					
					var products = response.split(",");
					
					 var arLen=products.length;
					 for ( var i=0, len=arLen; i<len; ++i )
					 {

						  if(products[i] != '')
						  {
							  
								  var bits = products[i].split("_");
								  
								  var id = bits[0];
								  var name = bits[1];
								  
							
								//insert option into select
								var new_el = new Element('option', {'value': id});
								new_el.set('html', name);
								new_el.inject(select,'top');
					  		}

					
						}
						
						//insert option into select
						var new_el = new Element('option', {'value': '0'});
						new_el.set('html', 'other');
						new_el.inject(select,'top');
						
						//inject the qty options
						for(var i=1;i<51;i++)
						{
							
							var num = String(i);
							//insert option into select

							
							var new_qty_el = new Element('option', {'value': num});
							
							if(i == 1)
							{
								new_qty_el.set('selected', 'selected');
							}
							
							new_qty_el.set('html', num);
							new_qty_el.inject(qty,'top');
							
						}
						
						if (typeof ie7=="undefined") {
							var ie7 = false;
						}
						
						if(ie7)
						{
							qty.setStyle('width', qty.getStyle('width').toInt());
							select.setStyle('width', select.getStyle('width').toInt());
						}
												
						//check for print or proof
						if($('job_type').value == 'proof')
						{
							qty.setStyle('display', 'none');
							select.setStyle('display', 'none');
							qty_label.setStyle('display', 'none');
							select_label.setStyle('display', 'none');
						}
						
				}.bind(this) 	
			}).send(),
			new Element('span', {'class': 'product-select-label', 'html': 'product'}),
			new Element('select', {
				'class': 'qty-select',
				'name': 'qty_' + fname
			}),
			new Element('span', {'class': 'qty-select-label', 'html': 'qty'}),
			new Element('input', {
				'type': 'hidden',
				'name': 'batch',
				'class': 'batch',
				'value': $('current_batch').value
			}),
			new Element('input', {
				'type': 'text',
				'class': 'custom-product',
				'name': 'custom_' + fname
			}),
			new Element('span', {
				'class': 'custom-label',
				'html': 'custom product'
			}),
			this.info,
			new Element('span', {'class': 'file-name', 'html': MooTools.lang.get('FancyUpload', 'fileName').substitute(this)})
		).inject(this.base.list);		
		
		
		
		$('current_file').value++;	
	},
	
	validate: function() {
		return (this.parent() && this.base.options.validateFile(this));
	},
	
	onStart: function() {
		this.element.addClass('file-uploading');
		this.base.currentProgress.cancel().set(0);
		this.base.currentTitle.set('html', MooTools.lang.get('FancyUpload', 'currentFile').substitute(this));
	},

	onProgress: function() {
		this.base.overallProgress.start(this.base.percentLoaded);
		this.base.currentText.set('html', MooTools.lang.get('FancyUpload', 'currentProgress').substitute({
			rate: (this.progress.rate) ? Swiff.Uploader.formatUnit(this.progress.rate, 'bps') : '- B',
			bytesLoaded: Swiff.Uploader.formatUnit(this.progress.bytesLoaded, 'b'),
			timeRemaining: (this.progress.timeRemaining) ? Swiff.Uploader.formatUnit(this.progress.timeRemaining, 's') : '-'
		}));
		this.base.currentProgress.start(this.progress.percentLoaded);
	},
	
	onComplete: function() {
		this.element.removeClass('file-uploading');
		
		this.base.currentText.set('html', 'Upload completed');
		this.base.currentProgress.start(100);
		
		if (this.response.error) {
			var msg = MooTools.lang.get('FancyUpload', 'errors')[this.response.error] || '{error} #{code}';
			this.errorMessage = msg.substitute($extend({
				name: this.name,
				size: Swiff.Uploader.formatUnit(this.size, 'b')
			}, this.response));
			var args = [this, this.errorMessage, this.response];
			
			this.fireEvent('error', args).base.fireEvent('fileError', args);
		} else {
			this.base.fireEvent('fileSuccess', [this, this.response.text || '']);
		}
	},

	onError: function() {
		this.element.addClass('file-failed');
		var error = MooTools.lang.get('FancyUpload', 'fileError').substitute(this);
		this.info.set('html', '<strong>' + error + ':</strong> ' + this.errorMessage);
	},

	onRemove: function() {
		this.element.getElements('a').setStyle('visibility', 'hidden');
		this.element.fade('out').retrieve('tween').chain(Element.destroy.bind(Element, this.element));
	}
	
});

// Avoiding MooTools.lang dependency
(function() {
	var phrases = {
		'progressOverall': 'Overall Progress ({total})',
		'currentTitle': 'File Progress',
		'currentFile': 'Uploading "{name}"',
		'currentProgress': 'Upload: {bytesLoaded} with {rate}, {timeRemaining} remaining.',
		'fileName': '{name}',
		'remove': 'Remove',
		'removeTitle': 'Click to remove this entry.',
		'fileError': 'Upload failed',
		'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>#{code}</code>',
			'securityError': 'Security error occured ({text})',
			'ioError': 'Error caused a send or load operation to fail ({text})'
		}
	};
	
	if (MooTools.lang) {
		MooTools.lang.set('en-US', 'FancyUpload', phrases);
	} else {
		MooTools.lang = {
			get: function(from, key) {
				return phrases[key];
			}
		};
	}
})();

