/*
This object is based from booeep.swfupload.js... customized for UGC upload
*/

var BooeepUGCUpload =
{
	swfObj:			undefined,
	defParams:		{
		itemContainer: 'itemList',
		flash_url: '/global/swfupload/swfupload.swf',
		upload_url: '/global/ajax/Media/UGCUpload/',
		file_post_name: 'uploadFile',
		file_size_limit: '500 MB',
		file_types: "*.*",
		file_types_description: 'All Files',
		file_upload_limit:  1,
		file_queue_limit: 0,
		
		// TODO: turn this off for production
		debug: false,
		
		// lame button stuff
		button_image_url: "/global/images/modal/browse_btn_sprite.gif",	// Relative to the Flash file
		button_width: "62",
		button_height: "25",
		button_placeholder_id: "swfUpload_button",
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT
	},
	params:			undefined,
	status:			'inactive',
	progressBar:	undefined,
	
	init: function( userDefinedParams )
	{
		var me = this;
		
		// build params from default
		me.params = jQuery.extend(
			{
				file_dialog_start_handler:	me.fileDialogStart,
				file_queued_handler:		me.fileQueued,
				file_queue_error_handler:	me.fileQueueError,
				upload_start_handler:		me.startFile,
				upload_progress_handler:	me.uploadProgress,
				upload_error_handler:		me.uploadError,
				upload_complete_handler:	me.uploadComplete
			}
			, me.defParams
		);

		// overwrite default params with user-defined params
		jQuery.extend( me.params, userDefinedParams );
		
		// create object
		me.swfObj = new SWFUpload( me.params );
		
		// cache the progressBar
		me.progressBar = $('#upload_modal_container #status_bar');
	},
	
	fileDialogStart: function()
	{
		$('#file_box').empty();	
		this.cancelUpload();
	},
	
	fileQueued: function( file )
	{
		var me = BooeepUGCUpload;
		
		try {
			// empty and append
			$('#file_box')
				.empty()
				.tplAppend( { filename: file.name }, me.fileboxItemTpl );
			
		} catch (ex) {
			this.debug(ex);
		}
	},
	
	fileboxItemTpl: function()
	{
		// distinguish file type
		if ( this.filename.match( /(avi|dv|mov|qt|mpe?g|mp4|3gp|flv)$/i ) ) {
			// this is a movie
			var mediaType = 'video';
		}
		else if ( this.filename.match( /(png|jpe?g|gif)$/i ) ) {
			// this is an image
			var mediaType = 'image';
		}
		else if ( this.filename.match( /(mp3|wav)$/i ) ) {
			// this is an audio file
			var mediaType = 'audio';
		}
		else {
			// misc
			var mediaType = 'misc';
		}
	
		var tpl = [
			'div', { className: ( 'icon ' + mediaType ) },
			'div', { className: 'file_name' }, [ $.trunc( this.filename, 30 ) ]
		];
		
		return tpl;
	},
	
	fileQueueError: function( file, errorCode, message )
	{
		try {
			if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
				alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
				return;
			}
	
			switch (errorCode)
			{
				case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
					alert("File is too big.");
					this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
					alert("Cannot upload Zero Byte files.");
					this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
					alert("Invalid File Type.");
					this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				default:
					if (file !== null) {
						alert("Unhandled Error");
					}
					this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
			}
		} catch (ex) {
			this.debug(ex);
		}
	},
	
	startUpload: function( file )
	{
		var me = this;
	
		// this happens when the queue starts
		if ( me.status != 'active' ) {
		
			var ugcForm = document.forms['ugc_upload_form'];
			
			try {
					if ( ugcForm ) {
						// validation
						if ( !ugcForm.media_name.value ) {
							alert('Please enter a title.');
							return false;
						}
						if ( !ugcForm.media_desc.value ) {
							alert('Please enter a description.');
							return false;
						}
						
						me.swfObj.addFileParam( 'SWFUpload_0_0', 'media_name', ugcForm['media_name'].value );
						me.swfObj.addFileParam( 'SWFUpload_0_0', 'media_desc', ugcForm['media_desc'].value );
					}
			} catch(e) { alert(e) };
		
			// show progress pane
			$('#upload_modal_container #uploadOverlay').show();
			$('#upload_modal_container #upload_status').show();
			
			// kick it off
			this.swfObj.startUpload();
			this.status = 'active';
			
			// hide Flash elem
			//$('#swfUpload_container').hide();
		}
	},

	startFile: function( file )
	{
		ugcForm = document.forms['ugc_upload_form'];

		if ( ugcForm ) {
			var fields = {
				media_name: ugcForm.media_name.value,
				media_desc: ugcForm.media_desc.value
			}
			
			for( var key in fields )
			{
				this.addFileParam( file.id, key, fields[key] );
			}
		}

	},
	
	uploadProgress: function( file, bytesLoaded, bytesTotal )
	{
		var me = BooeepUGCUpload;
	
		try {
			var ratio = (bytesLoaded / bytesTotal);
			var parentWidth = me.progressBar[0].parentNode.offsetWidth;
			me.progressBar.css( 'width', Math.ceil( parentWidth * ratio ) + 'px' );
		} catch (ex) {
			this.debug(ex);
		}
	},
	
	uploadError: function( file, errorCode, message )
	{
		try {
			switch (errorCode)
			{
				case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
					this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
					this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.IO_ERROR:
					this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
					this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
					this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
					this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
				case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
					// do nothing
					break;
				case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
					this.debug("Error Code: Upload Stopped, Message: " + message);
					break;
				default:
					this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
					break;
			}
		} catch (ex) {
			this.debug(ex);
		}
	},
	
	uploadComplete: function( file )
	{
		BooeepUGCUpload.status = 'inactive';
		
		// load thank you pane
		$('#upload_modal_container #upload_status').hide();
		$('#upload_modal_container #upload_completion').show();
	},
	
	/**
	 * MODALS CONTROLLER SECTION
	 */
	
	showModal: function( jqmUrl )
	{
		// load the url
		$('#modalContainer').jqm({
			ajax:	jqmUrl,
			modal:	true,
			overlay: 60,
			overlayClass: 'modalOverlay'
		})
		// show the modal
		.jqmShow();
	},
	
	hideModal: function( jqmUrl )
	{
		// hide it
		$('#modalContainer').jqmHide();
	},
	
	/**
	 * UPLOADER SECTION
	 */
	
	loadUploader: function( site_id, type, coll_id )
	{
		if ( !FavoritesWidget.enforceLogin() )
			return;
	
		var jqmUrl	= '/global/UGC/upload_form.php';
		
		var qString = new Array();
		if ( site_id ) {
			qString.push( 'site_id=' + site_id );
		}
		if ( type ) {
			qString.push( 'media_type=' + type );
		}
		if ( coll_id ) {
			qString.push( 'coll_id=' + coll_id );
		}
		
		if ( qString.length > 0 ) {
			jqmUrl += '?';
			for( var i=0; i<qString.length; i++)
			{
				if ( i > 0 )
					jqmUrl += '&';
					
				jqmUrl += qString[i];
			}
		}
		
		// load the url
		this.showModal( jqmUrl );
	},
	
	cancelUploader: function()
	{
		var me = this;
		
		try {
			me.swfObj.cancelUpload();
		} catch(e) {};
		
		me.hideModal();
	}
};
