/* ******************************************************
   Author: Fingerpaint
   Date: 1/30/2011
   Summary: Contains event handlers and utility functions
   for uploading videos to Vzaar's Amazon S3 bucket using
   the Vzaar API and SWFUpload.
 ***************************************************** */

/* ----------------------------------
   ---- SWFUpload Event Handlers ----
   ---------------------------------- */

/* **********************
   Called when the SWFUpload button has been loaded on the page
   ********************** */
function swfUploaded() {
	// get the exact with and height of the normal browser button
	var width = $('#fakeButton').outerWidth() + 2;
	var height = $('#fakeButton').outerHeight() + 2;
	
	// set the SWFUpload button's width and height accordingly
	swfu.setButtonDimensions(width, height);
}
   
/* **********************
   Add the selected files name to the display.
   ********************** */
function fileQueued(file) {
	try {
		$('#video').val(file.name);
		clearMessage();
	} catch (ex) {
		this.debug(ex);
	}
} // end fileQueued

/* **********************
   onclick listener for the "Upload..." button. Begins the upload
   to the Vzaar Amazon S3 bucket.
   ********************** */
function uploadVideo() {
	// make sure the user entered an email address
	if($('#vzaar-email').val().length == 0) {
		// display the error message
		$('#upload-message p').text('Please enter your email address to continue.');
		$('#upload-message').addClass('upload-error-message');
		$('#upload-message').show();
		
		// change focus to the email input field
		$('#vzaar-email').focus();
	}
	// make sure the email address is in a valid format
	else if(isValidEmailAddress($('#vzaar-email').val())) {
		// clear the error message
		clearMessage();
		
		// make sure they selected a file
		if(swfu.getStats().files_queued === 0) {
			showWarningMessage("You haven't chosen a video to upload yet.");
			return false;
		}
		
		// start the upload
		swfu.startUpload();
	}
	// if they didn't, notify them the email address is wonky
	else {
		// display the error message
		$('#upload-message p').text("Your email address doesn't seem right. Please try again.");
		$('#upload-message').addClass('upload-error-message');
		$('#upload-message').show();
		
		// change focus to the email input field
		$('#vzaar-email').focus();
	}
} // end uploadVideo

/* **********************
   When the upload starts, update the UI accordingly.
   ********************** */
function uploadStart(file) {
	try {
		// update the "uploading video" text
		$('#upload-video-name').text("Uploading video \"" + file.name + "\"");
		
		// set up the event handler for the cancel button
		$('.cancelUpload').click(function () {
			// show a message that the upload was canceled
			showWarningMessage("You canceled your upload. You can choose a different video if you'd like.");
			
			// reset the progress bar
			$('#upload-video-name').text("");
			$('.progressBar').width(0);

			// clear the "select a video" text field
			$('#video').val("");
			
			// cancel the upload
			swfu.cancelUpload(file.id, false);
			
			// remove the even handler from the cancel button
			$(this).unbind('click');
		});
	}
	catch (ex) {}
	
	// return true indicates upload should continue
	return true;
} // end uploadStart

/* **********************
   Handle the FileDialogStart event.
   ********************** */
function fileDialogStart() {
	// check if there's already a file in the queue
	if(swfu.getStats().files_queued > 0) {
		// cancel the currently queued file
		swfu.cancelUpload(null, false);
		
		// show a warning message
		showWarningMessage("You may only upload one video. You're previous selection has been removed.");
		
		// clear the video name
		$('#video').val("");
	}
}
   
/* **********************
   Handle errors when adding a file to the queue.
   ********************** */
function fileQueueError(file, errorCode, message) {
	try {
		switch (errorCode) {
			// tried to select a second file without canceling the first one
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				// show a warning message that the file selection has been changed
				showErrorMessage("You may only upload one video. To upload a different video, cancel the current upload or refresh the page.");
				break;
			// the file they chose is too big
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				// show an error message that the file chosen is too big
				showErrorMessage("The video you chose is too big. Maximum size is 1 GB.");
				this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			// the file is empty (zero bytes)
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				// show an error message that the file chosen is empty
				showErrorMessage("The video you chose is empty! Why upload that?");
				this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			// the file chosen is not the right file type
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				// show an error message that the file chosen is the wrong type
				showErrorMessage("The file you chose doesn't seem to be a video. Please try again.");
				this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			// we don't know what happened, but we can't upload your file
			default:
				// show an error message saying we don't know what happend
				showErrorMessage("We're not really sure what went wrong. Please try it again. If it still doesn't work" +
					" send us an email and we'll see what we can do.");
				this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
		}
	} catch (ex) {
        this.debug(ex);
    }
} // end fileQueueError

/* **********************
   Display the upload progress to the user.
   ********************** */
function uploadProgress(file, bytesLoaded, bytesTotal) {
	try {
		// calculate percent complete of upload
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		// set the width of the progress bar to the percent complete
		$('.progressBar').css('width', percent + '%');
	} catch (ex) {
		this.debug(ex);
	}
} // end uploadProgress

/* **********************
   Display an upload complete message and process the video on Vzaar.
   ********************** */
function uploadSuccess(file, serverData) {
	// some platforms won't get the totalBytes during progress, set indicator to 100%
	$('.progressBar').css('width', '100%');
	
	s3Response = $.xmlToJSON(serverData);
	
	var arrKey = s3Response.find('Key')[0].val().split('/');
	var guid = arrKey[arrKey.length-2];

	showSuccessMessage("You're video has been uploaded. It will now be processed by our video service.");

	//calling Process Video service
	$.post('/wp-content/custom-php/vzaar-uploads/scripts/processVideo.php', {
		guid: guid,
		title: $('#vzaar-email').val() + " - "+ file.name,
		description: ''
	});
} // end uploadSuccess

/* **********************
   Inform the user that there has been an error uploading their file.
   ********************** */				
function uploadError(file, errorCode, message) {
	try {
		clearMessage();
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			showErrorMessage("The server didn't get the whole file. Please try again.");
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			showErrorMessage("We could not begin your upload. Please try again.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			showErrorMessage("There was an error reading the file you'd like to upload. Please try again.");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			showErrorMessage("The upload stopped because of a security concern.");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			showErrorMessage("You have exceeded the upload limit. You may only upload one video. If you need to upload another video, please refresh the page and try again.");
			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:
			showErrorMessage("We don't like this file, so we skipped it. Please choose another file.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			showErrorMessage("Your upload has been stopped.");
			break;
		default:
			showErrorMessage("We have no idea what happened. Contact the site admin and tell them you got an error code: " + errorCode + ".");
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
} // end uploadError



/* ---------------------------
   ---- Utility Functions ----
   --------------------------- */
   
/* **********************
   Perform basic email validation on the given string
   ********************** */
function isValidEmailAddress(emailAddress) {
	var pattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$/i;
	return pattern.test(emailAddress);
} // end isValidEmailAddress

/* **********************
   Show an error message to the user
   ********************** */
function showErrorMessage(message) {
	clearMessage();
	$('#upload-message p').text(message);
	$('#upload-message').addClass('upload-error-message');
	$('#upload-message').show();
} // end showErrorMessage

/* **********************
   Show a warning message to the user
   ********************** */
function showWarningMessage(message) {
	clearMessage();
	$('#upload-message p').text(message);
	$('#upload-message').addClass('upload-warning-message');
	$('#upload-message').show();
} // end showWarningMessage

/* **********************
   Show a success message to the user
   ********************** */
function showSuccessMessage(message) {
	clearMessage();
	$('#upload-message p').text(message);
	$('#upload-message').addClass('upload-success-message');
	$('#upload-message').show();
} // end showSuccessMessage

/* **********************
   Clear all messages.
   ********************** */
function clearMessage() {
	$('#upload-message').hide();
	$('#upload-message').removeClass('upload-error-message');
	$('#upload-message').removeClass('upload-warning-message');
	$('#upload-message').removeClass('upload-success-message');
	$('#upload-message p').text('');
} // end clearMessage
