$(function(){
	
	function initMagicUpload(doc) {
		
		$('FORM', doc).submit(function(){
		
			var form = this;
			
			// ensure we are not in middle of upload whilst submitting form
			// though this ignores the magicupload
			var inProgressCount = 0;
			$('.magicUpload-control').each(function(){
				var swfu = $.swfupload.getInstance(this);
				inProgressCount += swfu.getStats().files_queued + swfu.getStats().in_progress;
				if (swfu.customSettings.ajaxInProgress) {
					inProgressCount++;
				}
			});
			if (inProgressCount > 0) {
				alert('Please wait until all of your uploads are complete');
				return false;
			}
			
			
			
			$('.images.magicUpload.multiple LI', form).each(function(i){
				$('INPUT, SELECT, TEXTAREA', this).attr('name', function(){
					return this.name.replace(/\]\[\d+\]\[/, ']['+i+'][');
				});
			}).otherwise(function(){
				$('.images.magicUpload.multiple UL', form).html('<input type="hidden" name="data[Image][Image][]" value="" />');
			});
			
			// the same as above, but for videos
			// eventually refactor so don't need to duplicate this
			$('.videos.magicUpload.multiple LI', form).each(function(i){
				$('INPUT, SELECT, TEXTAREA', this).attr('name', function(){
					return this.name.replace(/\]\[\d+\]\[/, ']['+i+'][');
				});
			}).otherwise(function(){
				$('.videos.magicUpload.multiple UL', form).html('<input type="hidden" name="data[Video][Video][]" value="" />');
			});
			
			// the same as above, but for documents
			// eventually refactor so don't need to duplicate this
			$('.documents.magicUpload.multiple LI', form).each(function(i){
				$('INPUT, SELECT, TEXTAREA', this).attr('name', function(){
					return this.name.replace(/\]\[\d+\]\[/, ']['+i+'][');
				});
			}).otherwise(function(){
				$('.documents.magicUpload.multiple UL', form).html('<input type="hidden" name="data[Document][Document][]" value="" />');
			});
			
			
			return true;
			
		});
		
		// generic sortables and hookup of remove button
		$('.input.magicUpload.multiple', doc).children('ul')
			.sortable({tolerance: 'pointer'});
		
		$('.input.magicUpload', doc).children('ul')
			.mouseover(function(event){
				if (event.target != this) {
					$target = $(event.target);
					if ($target.is('LI')) {
						$target.addClass('over');
					} else {
						$target.parents('LI:first').addClass('over');
					}
				}
			})
			.mouseout(function(event){
				if (event.target != this) {
					$target = $(event.target);
					if ($target.is('LI')) {
						$target.removeClass('over');
					} else {
						$target.parents('LI:first').removeClass('over');
					}
				}
			})
			.click(function(event){
				if ($(event.target).hasClass('remove')) {
					if (!confirm('Are you sure you want to delete this?')) {
						return false;
					}
					$(event.target).parents('LI:first').fadeOut('normal', function(){ $(this).remove(); });
					return false;
				}
			});
		
		
		$('.magicUpload-control', doc).each(function(){
			var settings = $(this).metadata({type:'attr', name:'data'});
			$(this).swfupload(settings);
		});
		
		
		var listeners = {
			swfuploadLoaded: function(event){
				//console.debug('swfuploadLoaded!!', event);
			},
			
			
			fileQueueError: function(event, file, errorCode, message) {
						
				try {
					var errorName = "";
					if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
						errorName = "You have attempted to queue too many files.";
					}
			
					if (errorName !== "") {
						alert(errorName);
						return;
					}
			
					switch (errorCode) {
						case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
						case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
						case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
						case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
						default:
							alert(message);
							break;
					}
			
				} catch (ex) {
					$(this).swfupload('debug', ex);
				}
			
			},
			
			
			fileDialogComplete: function(event, numFilesSelected, numFilesQueued) {
				try {
					if (numFilesQueued > 0) {
						$(this).swfupload('startUpload');
					}
				} catch (ex) {
					$(this).swfupload('debug', ex);
				}
			},
			
			uploadProgress: function(event, file, bytesLoaded) {
			
				try {
					var percent = Math.ceil((bytesLoaded / file.size) * 100);
					var progress = new FileProgress(file, $('.magicUpload-progress', this), $.swfupload.getInstance(this));
					progress.setProgress(percent);
					if (percent === 100) {
						progress.setStatus("Creating thumbnail...");
						progress.toggleCancel(false);
					} else {
						progress.setStatus("Uploading...");
						progress.toggleCancel(true);
					}
				} catch (ex) {
					$(this).swfupload('debug', ex);
				}
			},
			
			uploadSuccess: function(event, file, serverData) {
				try {
					var progress = new FileProgress(file, $('.magicUpload-progress', this), $.swfupload.getInstance(this));
					var uploadId = $.fromXMLString(serverData).find('upload').attr('id');
					
					if (uploadId) {
						
						var $list = $(this).siblings('.magicUpload:first').children('UL:first');
						var customSettings = $.swfupload.getInstance(this).customSettings;
						
						if (!customSettings.ajaxInProgress) {
							customSettings.ajaxInProgress = 1;
						} else {
							customSettings.ajaxInProgress++;
						}
						
						$.get(customSettings.itemRenderer+uploadId, null, function(result){
							if (result.success) {
								$item = $(result.data);
								if ($list.parent().hasClass('single')) {
									$list.html($item);
								} else {
									$list.append($item);
								}
								$list.parents('.magicUpload:first').trigger('MagicUpload.itemAdded', [$item]);
							} else {
								alert(result.errors.join("\n"));
							}
							customSettings.ajaxInProgress--;
						}, 'json');
						
						progress.setStatus("Thumbnail Created.");
						progress.toggleCancel(false);
					} else {
						progress.setStatus("Error.");
						progress.toggleCancel(false);
						//console.debug('Can\'t get upload id', serverData);
					}
			
			
				} catch (ex) {
					$(this).swfupload('debug', ex);
				}
			},
			
			uploadComplete: function(event, file) {
				try {
					/*  I want the next upload to continue automatically so I'll call startUpload here */
					var swfu = $.swfupload.getInstance(this);
					if (swfu.getStats().files_queued > 0) {
						swfu.startUpload();
					} else {
						var progress = new FileProgress(file, $('.magicUpload-progress', this), $.swfupload.getInstance(this));
						progress.setComplete();
						progress.setStatus("All files received.");
						progress.toggleCancel(false);
						progress.destroy();
					}
				} catch (ex) {
					$(this).swfupload('debug', ex);
				}
			},
			
			
			uploadError: function(file, errorCode, message) {
				var progress;
				try {
					switch (errorCode) {
					case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
						try {
							progress = new FileProgress(file, $('.magicUpload-progress', this), $.swfupload.getInstance(this));
							progress.setCancelled();
							progress.setStatus("Cancelled");
							progress.toggleCancel(false);
						}
						catch (ex1) {
							$(this).swfupload('debug', ex1);
						}
						break;
					case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
						try {
							progress = new FileProgress(file, $('.magicUpload-progress', this), $.swfupload.getInstance(this));
							progress.setCancelled();
							progress.setStatus("Stopped");
							progress.toggleCancel(true);
						}
						catch (ex2) {
							$(this).swfupload('debug', ex2);
						}
					case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
					default:
						alert(message);
						break;
					}
			
				} catch (ex3) {
					$(this).swfupload('debug', ex);
				}
			
			}
		
			
		};
		
		$('.magicUpload-control', doc).bindAll(listeners);
	}
	
	
	initMagicUpload(document);
	
	$(window).bind('ajaxPageLoad', function(event, el){
		setTimeout(function(){
			initMagicUpload(el);
		}, 200);
	});
	
});






/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */

function FileProgress(file, $target, swfupload) {
	
	this.$target = $target;
	
	if (!$target.data('inited')) {
		
		$target.append(
			'<div class="progressWrapper"> \
				<div class="progressContainer"> \
					<a href="#" class="progressCancel" style="visibility:hidden;"> </a> \
					<div class="progressName">'+file.name+'</div> \
					<div class="progressBar"></div> \
					<div class="progressBarStatus">&nbsp;</div> \
				</div> \
			</div>').fadeIn();
		
		$('.progressCancel', $target).click(function(){
			swfupload.cancelUpload();
			return false;
		});
		
		$target.data('inited', 1);
		
	} else {
		
		$('.progressName', $target).html(file.name);

	}

	//this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.setProgress = function (percentage) {
	$('.progressContainer', this.$target).removeClass('blue red').addClass('green');
	$('.progressBar', this.$target)
		.removeClass('progressBarComplete progressBarError')
		.addClass('progressBarInProgress')
		.css({width:percentage+'%'});
};
FileProgress.prototype.setComplete = function () {
	$('.progressContainer', this.$target).removeClass('green red').addClass('blue');
	$('.progressBar', this.$target)
		.removeClass('progressBarInProgress progressBarError')
		.addClass('progressBarComplete')
		.css({width:''});
};
FileProgress.prototype.setError = function () {
	$('.progressContainer', this.$target).removeClass('green blue').addClass('red');
	$('.progressBar', this.$target)
		.removeClass('progressBarInProgress progressBarComplete')
		.addClass('progressBarError')
		.css({width:''});
};
FileProgress.prototype.setCancelled = function () {
	$('.progressContainer', this.$target).removeClass('green blue red');
	$('.progressBar', this.$target)
		.removeClass('progressBarInProgress progressBarComplete')
		.addClass('progressBarError')
		.css({width:''});
};
FileProgress.prototype.setStatus = function (status) {
	$('.progressBarStatus', this.$target).html(status);
};

FileProgress.prototype.toggleCancel = function (show) {
	if (show) {
		$('.progressCancel', this.$target).show();
	} else {
		$('.progressCancel', this.$target).hide();
	}
};

FileProgress.prototype.destroy = function() {
	this.$target.empty();
	this.$target.data('inited', false);
};
