/* Demo Note:  This demo uses a FileProgress class that handles the UI for displaying the file name and percent complete.
The FileProgress class is not part of SWFUpload.
*/


/* **********************
   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 swfUploadPreLoad() {
	var self = this;
	var loading = function () {
		//document.getElementById("divSWFUploadUI").style.display = "none";
		document.getElementById("divLoadingContent").style.display = "";

		var longLoad = function () {
			document.getElementById("divLoadingContent").style.display = "none";
			document.getElementById("divLongLoading").style.display = "";
		};
		this.customSettings.loadingTimeout = setTimeout(function () {
				longLoad.call(self)
			},
			15 * 1000
		);
	};

	this.customSettings.loadingTimeout = setTimeout(function () {
			loading.call(self);
		},
		1*1000
	);
}
function swfUploadLoaded() {
	var self = this;
	clearTimeout(this.customSettings.loadingTimeout);
	//document.getElementById("divSWFUploadUI").style.visibility = "visible";
	//document.getElementById("divSWFUploadUI").style.display = "block";
	document.getElementById("divLoadingContent").style.display = "none";
	document.getElementById("divLongLoading").style.display = "none";
	document.getElementById("divAlternateContent").style.display = "none";

	//document.getElementById("btnBrowse").onclick = function () { self.selectFiles(); };
	document.getElementById("btnCancel").onclick = function () { self.cancelQueue(); };
}

function swfUploadLoadFailed() {
	clearTimeout(this.customSettings.loadingTimeout);
	//document.getElementById("divSWFUploadUI").style.display = "none";
	document.getElementById("divLoadingContent").style.display = "none";
	document.getElementById("divLongLoading").style.display = "none";
	document.getElementById("divAlternateContent").style.display = "";
}

function attachmentsFileQueued(file) {
	try {
		var progress = new FileProgress(file, this.customSettings.swf_upload_progress_id);
		progress.setStatus("Pending...");
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}
}

function attachmentsFileQueueError(file, errorCode, message) {
	try {
		if(file == null)
		{
			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;
		}

		var progress = new FileProgress(file, this.customSettings.swf_upload_progress_id);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				progress.setStatus("Queue limit exceeded.");
				this.debug("Error Code: Queue limit exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				progress.setStatus("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:
				progress.setStatus("Cannot upload zero byte files.");
				this.debug("Error Code: Cannot upload zero byte files, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				progress.setStatus("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) {
					progress.setStatus('Unhandled error with code: '+errorCode+' vs '+SWFUpload.ERROR_CODE_FILE_EXCEEDS_SIZE_LIMIT);
				}
				this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function attachmentsFileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if(numFilesQueued > 0) {
			$('#'+this.customSettings.swf_button_cancel_id).css({opacity: 1.0});
		}
		
		/* I want auto start the upload and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function attachmentsUploadStart(file) {
	try {
		// add the upload key
		this.addPostParam('upload_key', upload_key);

		var progress = new FileProgress(file, this.customSettings.swf_upload_progress_id);
		progress.setStatus("Uploading...");
		progress.toggleCancel(true, this);
	}
	catch (ex) {
	}
	
	return true;
}
	
function attachmentsUploadProgress(file, bytesLoaded, bytesTotal) {
	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.swf_upload_progress_id);
		progress.setProgress(percent);
		progress.setStatus("Uploading...");
	} catch (ex) {
		this.debug(ex);
	}
}

function attachmentsUploadSuccess(file, serverData) {
	try {
		// parse json
		data = eval("(" + serverData + ")");
		// check errors
		if(data['errors'].length > 0)
		{
			uploadError.apply(this, [file, SWFUpload.UPLOAD_ERROR.HTTP_ERROR, data['errors'][0]]);
			return;
		}
		upload_key = data['upload_key'];

		// initiate adding the file
		add_attachment(data);

		var progress = new FileProgress(file, this.customSettings.swf_upload_progress_id);
		progress.setComplete();
		progress.setStatus("Complete.");
		progress.toggleCancel(false);

	} catch (ex) {
		this.debug(ex);
	}
}


function attachmentsUploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.swf_upload_progress_id);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Upload Error: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("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("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("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:
			progress.setStatus("Failed Validation.  Upload skipped.");
			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 there aren't any files left (they were all cancelled) disable the cancel button
			if (this.getStats().files_queued === 0) {
				$('#'+this.customSettings.swf_button_cancel_id).css({opacity: .3});
			}
			progress.setStatus("Cancelled");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stopped");
			break;
		default:
			progress.setStatus("Unhandled Error: " + errorCode);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function attachmentsUploadComplete(file) {
	if (this.getStats().files_queued === 0) {
		$('#'+this.customSettings.swf_button_cancel_id).css({opacity: .3});
	}
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
	var status = document.getElementById("upload_status");
	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
}

function attachmentsUpdateDisplay(file) {
	this.customSettings.swf_current_speed.innerHTML        = SWFUpload.speed.formatBPS(file.currentSpeed);
	this.customSettings.swf_average_speed.innerHTML        = SWFUpload.speed.formatBPS(file.averageSpeed);
	this.customSettings.swf_moving_average_speed.innerHTML = SWFUpload.speed.formatBPS(file.movingAverageSpeed);
	this.customSettings.swf_time_remaining.innerHTML       = SWFUpload.speed.formatTime(file.timeRemaining);
	this.customSettings.swf_time_elapsed.innerHTML         = SWFUpload.speed.formatTime(file.timeElapsed);
	this.customSettings.swf_percent_uploaded.innerHTML     = SWFUpload.speed.formatPercent(file.percentUploaded);
	this.customSettings.swf_size_uploaded.innerHTML        = SWFUpload.speed.formatBytes(file.sizeUploaded);
}
