/************************************************************************************************************************************
admin_upload.js

This JS file contains functions that are specific to content uploading in the media manager.

	
	enableUpload
	disableUpload
	uploadFormOk
	resetUploadProgressIndicators
	doUpload
	abortUpload
	startUploadMeter
	tickUploadMeter
	stopUploadMeter
	logSWFUploadStatus
	randomFileId
	
************************************************************************************************************************************/

var oSWFU;
var bUploadSWFLoaded = false;			// whether or not the flash uploader is loaded and ready
var nUploadMeter;						// keeps track of how many "ticks" we show on our upload meter
var iUploadMeter;						// upload meter interval ID
var nUploadStartTime;					// used to estimate how much longer is left on an upload
var nUploadBytesComplete;				// used to estimate how much longer is left on an upload
var nUploadBytesTotal;					// used to estimate how much longer is left on an upload
var aUploadAssociation = [];			// array of associations the user wants to add to this upload file
var nMediaItemUploadId = 0;				// the value returned by the preupload event iif the upload is successful


var sMMUploadURL = "http://" + sJIServicesDomain + "/MediaManager/ajax.cfm";
var sMMIncludesURL = "http://" + sJIServicesDomain + "/MediaManager/includes/";
var sUniqueUploadId = randomFileId();




String.prototype.repeat = function(num) {
	return new Array(num+1).join(this);
}


function enableUpload() {
	// enable the upload controls
	$("#btnSubmitUpload").removeAttr("disabled");
	if (bUploadSWFLoaded) {
		try {
			oSWFU.setButtonDisabled(false);
			oSWFU.setButtonCursor(SWFUpload.CURSOR.HAND);
		}
		catch (e) {
			// probably FireFox -- wait for enableUpload() to be called by SWFUpload's "onLoaded" event
		}
	}
}


function disableUpload() {
	// disable the upload controls (to prevent multiple simultaneous uploads
	$("#btnSubmitUpload").attr("disabled", "disabled");
	if (bUploadSWFLoaded) {
		oSWFU.setButtonDisabled(true);
		oSWFU.setButtonCursor(SWFUpload.CURSOR.ARROW);
	}
}


function addUploadParameter(name, value) {
	oSWFU.removePostParam(name);
	oSWFU.addPostParam(name, value);
}


function addUploadAssociation(atypeid, targetid, targetsubid, english) {
	aUploadAssociation[aUploadAssociation.length] = {
		atypeid:		atypeid
		, targetid:		targetid
		, targetsubid:	targetsubid
		, english:		english
	};
}


function doUpload() {
	// when the user submits the upload form, we start our process
	if (oSWFU.getStats().files_queued<=0) {
		alert("* You must select a file to upload.\n");
	} else {
		// reset the media item upload id
		nMediaItemUploadId = 0;
		// disable the ability to submit the form again
		disableUpload();
		// make a new file ID for this upload
		var sFileId = randomFileId();
		// add new post params
		addUploadParameter("folderid", nUploadFolderId);
		addUploadParameter("fileid", sFileId);
		addUploadParameter("_ct", new Date().getTime());
		// add custom settings so that we can issue a result ajax call after the upload finishes
		oSWFU.customSettings.uploadid = sUniqueUploadId;
		oSWFU.customSettings.fileid = sFileId;
		// set up the initial parameters to pass
		var params = {
			urltarget:			sMMUploadURL
			, method:			"publicpreupload"
			, uploadid:			sUniqueUploadId
			, fileid:			sFileId
			, folderid:			nUploadFolderId
			, _ct:				new Date().getTime()
		};
		// add any custom associations that have been set up
		for (var i=0; i<aUploadAssociation.length; i++) {
			eval("params.assoc_atypeid"+i+" = aUploadAssociation["+i+"].atypeid");
			eval("params.assoc_targetid"+i+" = aUploadAssociation["+i+"].targetid");
			eval("params.assoc_targetsubid"+i+" = aUploadAssociation["+i+"].targetsubid");
			eval("params.assoc_english"+i+" = aUploadAssociation["+i+"].english");
		}
		// do the pre-upload to record the user's intention to upload something
		$.post(sAJAXProxyURL, params, function(response) {
				try {
					var stResponse = eval("("+response+")");
					if (stResponse.BERROR) {
						(stResponse.SERROR=="" || alert(stResponse.SERROR));
						$("#spanSelectedUploadFile").html("");
						resetUploadProgressIndicators();
						enableUpload();
					} else {
						// success, now upload the actual file with the flash control
						nMediaItemUploadId = stResponse.MEDIAITEMUPLOADID;
						oSWFU.startUpload();
					}
				}
				catch (e) {
					alert("An unknown error occurred during this operation: " + e);
				}
			}
		);
	}
}


function abortUpload() {
	$("#spanUploadDescription").html("Aborting...");
	oSWFU.cancelUpload();
}


function resetUploadProgressIndicators() {
	$("#spanUploadProgressNumerator").html("");
	$("#spanUploadProgressDenominator").html("");
	$("#spanUploadProgressPercent").html("");
	$("#spanUploadDescription").html("");
	$("#spanUploadProgressMeter").html("");
	$("#spanUploadTimeLeft").html("");
}


function startUploadMeter() {
	nUploadMeter = 0;
	iUploadMeter = setInterval("tickUploadMeter()", 500);
}


function tickUploadMeter() {
	if (nUploadBytesTotal>0 && nUploadBytesTotal > nUploadBytesComplete) {
		var nPercentDone = parseFloat(nUploadBytesComplete/nUploadBytesTotal);
		var nSecondsPassed = parseInt((new Date().getTime() - nUploadStartTime)/1000);
		var nTotalSecondsExpected = parseInt(nSecondsPassed/nPercentDone);
		var nSecondsLeft = nTotalSecondsExpected - nSecondsPassed;
		var nTransferRate = parseInt(nUploadBytesComplete/nSecondsPassed);
		var html = "";
		html += "Seconds Elapsed: " + nSecondsPassed + "<br />";
		html += "Total Seconds Expected: " + nTotalSecondsExpected + "<br />";
		html += "Seconds Left: " + nSecondsLeft + "<br />";
		html += "Rate: " + size_format(nTransferRate) + "/s<br />";
		$("#spanUploadTimeLeft").html(html);
	} else {
		$("#spanUploadTimeLeft").html("");
	}
	nUploadMeter++
	$("#spanUploadProgressMeter").html("*".repeat((nUploadMeter%5)+1));
}


function stopUploadMeter() {
	clearInterval(iUploadMeter);
}


function logSWFUploadStatus(uploadid, fileid, filename, success, detail) {
	$.post(sAJAXProxyURL, {
			method:				"logswfuploadstatus"
			, uploadid:			uploadid
			, fileid:			fileid
			, filename:			filename
			, success:			success
			, detail:			detail
			, _ct:				new Date().getTime()
		}, function(response) {
			// we don't care about the response
		}
	);
}


function randomFileId() {
	// this allows us to generate a random string of characters to try to help us uniquely
	// identify an upload so we can combine a preupload (storing of intent to upload) with an actual upload
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = "";
	for (var i=0; i<12; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum, rnum+1);
	}
	return randomstring;
}


function size_format(filesize) {
	if (filesize >= 1073741824) {
		filesize = addCommas((filesize/1073741824).toFixed(2)) + ' GB';
	} else {
		if (filesize >= 1048576) {
			filesize = addCommas((filesize/1048576).toFixed(2)) + ' MB';
		} else {
			if (filesize >= 1024) {
				filesize = addCommas((filesize/1024).toFixed(2)) + ' KB';
			} else {
				filesize = addCommas(filesize.toFixed(2)) + ' bytes';
			}
		}
	}
	return filesize;
};


function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


function buildUploaderHTML() {
	var html = "";
	if ($("#swfuploader").size()>0) {
		html += '<span id="spanSWFUploadButton"></span><br />';
		html += '<span id="spanSelectedUploadFile"></span><br />';
		$("#swfuploader").replaceWith(html);
	}
	
	html = "";
	if ($("#swfuploader_stats").size()>0) {
		html += '<div id="divUploadStatus" style="display:none;">';
		html += '<span id="spanUploadProgress"><span id="spanUploadProgressNumerator"></span> / <span id="spanUploadProgressDenominator"></span> (<span id="spanUploadProgressPercent"></span>%)</span><br />';
		html += '<span id="spanUploadTimeLeft"></span>';
		html += '<span id="spanUploadDescription"></span>';
		html += '<span id="spanUploadProgressMeter"></span>';
		html += '</div>';
		$("#swfuploader_stats").replaceWith(html);
	}
}


$(document).ready(function() {
	
	if ($("#swfuploader").size()>0) {
		
		buildUploaderHTML();
		
		// ready function so we know when we're ready to upload
		var fReady = function() {
			bUploadSWFLoaded = true;
			enableUpload();
		};
		
		// queued function for after the user selects a file
		var fQueued = function(file) {
			$("#spanSelectedUploadFile").html(file.name + " (" + size_format(file.size) + ")");
		};
		
		// queue error, in case they select an empty or invalid file
		var fQueueError = function(file, errorcode, message) {
			switch (errorcode) {
				case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
					alert("You may only upload one file at a time.");
					break;
				case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
					alert("The file you selected is too large (2 GB max).");
					break;
				case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
					alert("You have selected an invalid (0-byte) file.");
					break;
				case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
					alert("You may not select a file of that type.");
					break;
			}
		};
		
		var fUploadStart = function(file) {
			//alert("Started uploading " + file.name);
			$("#spanUploadProgressDenominator").html(file.size + " bytes");
			$("#spanUploadDescription").html("Uploading...");
			$("#btnAbortUpload").show().removeAttr("disabled");
			$("#divUploadStatus").show();
			resetUploadProgressIndicators();
			startUploadMeter();
			nUploadStartTime = new Date().getTime();
			nUploadBytesComplete = 0;
			nUploadBytesTotal = 0;
		};
		
		var fUploadProgress = function(file, bytescomplete, bytestotal) {
			nUploadBytesComplete = bytescomplete;
			nUploadBytesTotal = bytestotal;
			$("#spanUploadProgressNumerator").html(bytescomplete);
			$("#spanUploadProgressPercent").html(((bytescomplete/bytestotal)*100).toFixed(1));
			if (bytescomplete>=bytestotal) {
				$("#spanUploadDescription").html("Processing...");
				$("#btnAbortUpload").hide().attr("disabled", "disabled");
			}
		};
		
		var fUploadError = function(file, errorcode, message) {
			logSWFUploadStatus(this.customSettings.uploadid, this.customSettings.fileid, file.name, 0, "[" + file.name + "] (" + errorcode + ") " + message);
			if (file.filestatus != SWFUpload.FILE_STATUS.CANCELLED) {
				alert(file.name + " failed to upload, please try again.  If this problem persists, there might be an error with the file itself.");
			}
		};
		
		var fUploadSuccess = function(file, serverdata, gotresponse) {
			logSWFUploadStatus(this.customSettings.uploadid, this.customSettings.fileid, file.name, 1, (gotresponse ? serverdata : "[NO SERVER RESPONSE]"));
			if (typeof uploadSuccess == "function") {
				uploadSuccess(nMediaItemUploadId);
			}
		};
		
		var fUploadComplete = function(file) {
			// this fires after either fUploadError or fUploadSuccess fires (last event after an upload attempt)
			aUploadAssociation = [];
			$("#spanSelectedUploadFile").html("");
			enableUpload();
			$("#btnAbortUpload").hide().attr("disabled", "disabled");
			$("#divUploadStatus").hide();
			stopUploadMeter();
		};
		
		// the "scheduled_task" parameter escapes the browser verification routine in production
		var stUploadSettings = {
			upload_url						:	sMMUploadURL + "?scheduled_task=1"
			, flash_url						:	sMMIncludesURL + "swfupload.swf"
			, post_params					:	{"method":"upload", "uploadid":sUniqueUploadId}
			, requeue_on_error				:	false
			, assume_success_timeout		:	30
			, file_queue_limit				:	1
			, file_size_limit				:	(typeof sUploadSizeLimit != "undefined" ? sUploadSizeLimit : "2 GB")
			, file_types					:	(typeof sFileTypes != "undefined" ? sFileTypes : "*.*")
			, file_types_description		:	(typeof sFileTypesDescription != "undefined" ? sFileTypesDescription : "All Files")
			
			, button_placeholder_id			:	"spanSWFUploadButton"
			, button_width					:	140
			, button_height					:	33
			, button_text					:	""
			, button_text_style				:	""
			, button_cursor					:	SWFUpload.CURSOR.HAND
			, button_image_url				:	sMMIncludesURL + "images/uploadbutton.gif"
			
			, swfupload_loaded_handler		:	fReady
			, file_queued_handler			:	fQueued
			, file_queue_error_handler		:	fQueueError
			, upload_start_handler			:	fUploadStart
			, upload_progress_handler		:	fUploadProgress
			, upload_error_handler			:	fUploadError
			, upload_success_handler		:	fUploadSuccess
			, upload_complete_handler		:	fUploadComplete
		};
		
		oSWFU = new SWFUpload(stUploadSettings);
		
	}
	
});



