/* This is an example of how to cancel all the files queued up.  It's made somewhat generic.  Just pass your SWFUpload
object in to this method and it loops through cancelling the uploads. */
function cancelQueue(instance) {
	jQuery("#" + instance.customSettings.cancelButtonId).attr("disabled", "disabled");
	instance.stopUpload();
	var stats;
	
	do {
		stats = instance.getStats();
		instance.cancelUpload();
	} while (stats.files_queued !== 0);
	
}

/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */

function swfuploadLoaded() {
	
	var oSelf = this;
	
	// Assign link for temporary files
	jQuery("a.upload_del_file", "#temp_progress").add("a.upload_del_file", "#temp_thumb").click(function(e) {
			
		var rel_hash = jQuery(this).attr("rel");
		var parent_progress = jQuery("#temp_progress").find("[rel='" + rel_hash + "']").parents()[0];
		
		jQuery(parent_progress).removeClass("blue").addClass("red");
		jQuery(".progressBarStatus", parent_progress).html(progress_status_deleting);
		
		jQuery.post(oSelf.customSettings.delete_url, { file: rel_hash }, function(data){
			
			jQuery(parent_progress).fadeOut(1000);
			
			if ((oSelf.customSettings.image_upload > 0) || (oSelf.customSettings.mixt_upload > 0)) {
				
				var parent_thumb = jQuery("#temp_thumb").find("[rel='" + rel_hash + "']").parents()[0];
				jQuery(parent_thumb).fadeOut(1000);
			}
		});
		
		return false;
	});
	
	if ((this.customSettings.image_upload > 0) || (this.customSettings.mixt_upload > 0)) {
		jQuery(".cell_prev", "#temp_thumb").hover(function() {
			jQuery(".upload_del_file", this).fadeIn(100);
		}, function() {
			jQuery(".upload_del_file", this).fadeOut(100);
		});
	}
}


function fileDialogStart() {
	/* I don't need to do anything here */
	
}
function fileQueued(file) {
	try {
		// You might include code here that prevents the form from being submitted while the upload is in
		// progress.  Then you'll want to put code in the Queue Complete handler to "unblock" the form
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus(progress_status_pending);
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}

}

function fileQueueError(file, errorCode, message) {
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			Boxy.alert(alert_queue_limit);
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus(progress_status_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:
			progress.setStatus(progress_status_zero);
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus(progress_status_invalid_type);
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			Boxy.alert(alert_upload_error);
			break;
		default:
			if (file !== null) {
				progress.setStatus(progress_status_unhandled);
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (this.getStats().files_queued > 0) {
			jQuery("#" + this.customSettings.cancelButtonId).removeAttr("disabled");
			jQuery("#" + this.customSettings.submit_btn).attr("disabled", "disabled");
		}
		
		/* I want auto start and I can do that here */
		this.startUpload();
		
	} catch (ex)  {
        this.debug(ex);
	}
}

function uploadStart(file) {
	try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and return true to indicate that the upload should start */
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus(progress_status_uploading);
		progress.toggleCancel(true, this);
	}
	catch (ex) {
	}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {

	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		
		if ((percent === 100) && ((this.customSettings.image_upload > 0) || (this.customSettings.mixt_upload > 0))) {
			jQuery("#" + this.customSettings.cancelButtonId).attr("disabled", "disabled");
			progress.setStatus(progress_status_thumbnail);
			progress.toggleCancel(false, this);
		} else {
			jQuery("#" + this.customSettings.cancelButtonId).removeAttr("disabled");
			progress.setStatus(progress_status_uploading);
			progress.toggleCancel(true, this);
		}
		
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		var sts = this.getStats();
		// alert("files_queued:" + sts.files_queued + "\n successful_uploads: " + sts.successful_uploads + "\n upload_errors: " + sts.upload_errors + "\n upload_cancelled: " + sts.upload_cancelled + "\n queue_errors: " + sts.queue_errors);
		
		var uploader = this;
		
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		var hash = serverData;
		
		if (serverData == "image_conversion_failure") {
			progress.setError();
			progress.toggleCancel(false);
			progress.setStatus(progress_status_conversion_failure);
			
			sts.successful_uploads --;
			if (typeof(updateUploadStats) == "function") {
				updateUploadStats(sts.successful_uploads);
			}
			uploader.setStats(sts);
		}
		else {
			progress.setComplete();
			progress.setStatus(progress_status_complete);
			progress.toggleCancel(false);
			
			if (typeof(updateUploadStats) == "function") {
				updateUploadStats(sts.successful_uploads);
			}
			
			jQuery(".progressContainer", "#" + file.id).prepend("<a href='#' rel='" + hash + "' class='upload_del_file'><img src='" + PATH_STATIC + "/img/site/spacer.gif' class='trash' /></a>");
			
			if ((this.customSettings.image_upload > 0) || (this.customSettings.mixt_upload > 0)) {
				
				var preview_src = do_link("site.remote", "request=load_thumb&load=" + hash + "&type=" + file.type.substr(1));
				
				jQuery("#" + this.customSettings.thumbTarget).append("<div id=\"prev_" + file.id + "\" class=\"cell_prev\"><a href=\"#\" rel=\"" + hash + "\" class=\"upload_del_file\" style=\"display: none;\"><img src=\"" + PATH_STATIC + "/img/site/spacer.gif\" class=\"trash\" /></a><img src=\"" + preview_src + "\" class=\"preview\" style=\"display: none;\" /></div>").find("img.preview:last").fadeIn(1000);
				
				jQuery(".cell_prev", "#" + this.customSettings.thumbTarget).hover(function() {
					jQuery(".upload_del_file", this).fadeIn(100);
				}, function() {
					jQuery(".upload_del_file", this).fadeOut(100);
				});
			}
			
			var oSelf = this;
			jQuery("a.upload_del_file", "#" + file.id).add(jQuery("a.upload_del_file", "#prev_" + file.id)).click(function(e) {
				
				jQuery(".progressContainer", "#" + file.id).removeClass("blue").addClass("red");
				jQuery(".progressBarStatus", "#" + file.id).html(progress_status_deleting);
				
				jQuery.post(oSelf.customSettings.delete_url, { file: hash }, function(data){
					
					if (data == "done") {
						if ((oSelf.customSettings.image_upload > 0) || (oSelf.customSettings.mixt_upload > 0)) {
							jQuery("#prev_" + file.id).fadeOut(1000);
						}
						
						jQuery("#" + file.id).fadeOut(1000);
						
						sts.successful_uploads --;
						if (typeof(updateUploadStats) == "function") {
							updateUploadStats(sts.successful_uploads);
						}
						uploader.setStats(sts);
					}
				});
				
				return false;
			});
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued === 0) {
			jQuery("#" + this.customSettings.cancelButtonId).attr("disabled", "disabled");
			jQuery("#" + this.customSettings.submit_btn).removeAttr("disabled");
		} else {	
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}

}

function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus(progress_status_upload_error + ": " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			progress.setStatus(progress_status_configuration_error);
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus(progress_status_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:
			progress.setStatus(progress_status_io_error);
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus(progress_status_security_error);
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus(progress_status_upload_limit);
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
			progress.setStatus(progress_status_file_not_found);
			this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus(progress_status_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:
			if (this.getStats().files_queued === 0) {
				jQuery("#" + this.customSettings.cancelButtonId).attr("disabled", "disabled");
			}
			progress.setStatus(progress_status_cancelled);
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			
			var oSelf = this;
			jQuery.post(oSelf.customSettings.delete_url_error, { pkd: oSelf.customSettings.pkd, file_name: file.name }, function(data){
				
			});
			
			progress.setStatus(progress_status_stopped);
			break;
		default:
			progress.setStatus(progress_status_unhandled + ": " + error_code);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}