/**
 * Adds file upload functionality to the Media Manager.
 */
MediaManager.Upload = function () {
	var options = {};
	var	defaults = {
			'uploader' : '#uploader',
			'width'   : 500,
			'height'  : 400,
			'title'   : 'Media Uploader',
			'currentGallery' : null,
			'manager' : null
		};
	
	
	/**
	 * Opens the uploader dialog.
	 */
	var open = function () {
		$( options.uploader ).dialog('open');
	};


	/**
	 * Closes the uploader dialog.
	 */
	var close = function () {
		$( options.uploader ).dialog('close');
	};


	/**
	 * Initializes the uploader.
	 *
	 * @param object config
	 */
	var init = function ( config ) {
		$.extend( options, defaults, config );
		
		// Create an uploader container if it doesn't exist (which it probably won't)
		if ( $( options.uploader ).length == 0 ) {
			$('body').append('<div id="' + options.uploader.split('#')[1] + '" class="hidden"></div>');
		}
		
		$( options.uploader ).dialog({
			autoOpen  : false,
			title     : options.title,
			width     : options.width,
			height    : options.height,
			minWidth  : 500,
			minHeight : 400,
			modal     : true,
			resizable : false,
			buttons   : {
				Close  : function () {
					$(this).dialog('close');
				}
			}
		});

		$(options.uploader).find('#media-uploader').remove();
		
		$( options.uploader ).append('\
			<div id="media-uploader">\
				<p class="quiet">Most common image, audio, and video file types are supported, including: bmp, jpg/jpeg, gif, png, tif/tiff (image); avi, flv, mov, mp4, mpg/mpeg, wmv (video); flac, mp3, real, vorbis, wma, wav (audio).</p>\
				<form action="' + baseUrl + 'gallery/ajax/process-media/gallery/' + options.currentGallery + '" method="POST" enctype="multipart/form-data">\
					<input type="file" name="Filedata" multiple>\
					<button type="submit">Upload</button>\
					<table></table>\
				</form>\
			</div>');


		// Initialize jQuery File Upload:
		$('#media-uploader').fileUploadUI({
			// Wait for user interaction before starting uploads:
			autoUpload: false,
			// Upload bigger files in chunks of 10 MB (remove or set to null to disable):
			maxChunkSize: 10000000,
			// Open download dialogs via iframes, to prevent aborting current uploads:
			forceIframeDownload: true,
			uploadTable: $('#media-uploader table'),
			buildUploadRow: function (files, index, handler) {
				return $('<tr><td>' + files[index].name + '<\/td>' +
						'<td class="file_upload_progress" colspan="2"><div><\/div><\/td>' +
						'<td class="file_upload_cancel">' +
						'<button class="ui-state-default ui-corner-all" title="Cancel">' +
						'<span class="ui-icon ui-icon-cancel">Cancel<\/span>' +
						'<\/button><\/td><\/tr>');
			},
			buildDownloadRow: function (file, handler) {

				return $('<tr>' +
					'<td class="file_download_preview"><a href="' + file.url + '" target="_blank"><img src="' + file.previewUrl + '" /></a></td>' +
					'<td><a href="' + file.url + '" target="_blank">' + file.name + '</a><\/td>' +
					'<td class="file_size">' + formatFileSize(file.size) + '</td>' +
					'<td class="file_download_delete"><a class="button" href="' + file.deleteUrl + '"><span class="ui-button-icon-primary ui-icon ui-icon-trash">Delete</span></a></td>' +
					'</tr>');
			},
			// Change 'Skip this step' link text to 'Continue' after file upload:
			onComplete:	function (event, files, index, xhr, handler) {
				$( options.manager ).trigger('onQueueComplete');
			}

		});

		// Hide the submit button, since upload will be handled asynchronously
		$('#media-uploader button').hide();

		// Attach handler to delete buttons
		$('#media-uploader .file_download_delete a')
			.live('load', function (event) {
				$(this).button({icons: {primary: 'ui-icon-trash'}, text: false})
			})
			.live('click', function (event) {
				var row = $(this).closest('tr');
				$.ajax({
					url: this.href,
					type: 'DELETE',
					success: function () {
						row.fadeOut(function () {
							row.remove();
						});
					}
				});
				event.preventDefault();
			});

		/**
		 * Returns human-readable file size.
		 *
		 * @param float bytes
		 */
		function formatFileSize(bytes) {
			if (typeof bytes !== 'number' || bytes === null) {
				return '';
			}
			var e = Math.floor(Math.log(bytes) / Math.log(1024));
			return (bytes / Math.pow(1024, e)).toFixed(2) + " KB MB GB TB PB".split(" ")[e];
		};		

		
	};
	
	return {
		init  : init,
		open  : open,
		close : close
	}
}

