/**
 * Provides javascript side of the SWFUpload 
 * that we do on our upload pages
 *
 * Geoffrey Thubron 
 */

//////////////////////////////////////////////////////////////
// Event Handlers                                           //
//////////////////////////////////////////////////////////////
function fileQueueError( file, errorCode, message ) 
{
	log("fileQueueError: ID=" + file.id + ", C=" + errorCode + ", M=" + message);
	try {
		var errorName = "";
		if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
			errorName = "You have attempted to queue too many files.";
		} else if ( errorCode === SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE) {
			errorName = "You have attempted to queue an empty file.";
		} else if ( errorCode === SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
			errorName = "You have attempted to queue a file that is above the size limit.";
		}

		if (errorName !== "") {
			alert(errorName);
			return;
		}
		
		alert(message);

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

function fileDialogComplete( numFilesSelected, numFilesQueued ) 
{
	log("fileDialogComplete: S=" + numFilesSelected + ", Q=" + numFilesQueued);
	try {
		if (numFilesQueued > 0) {
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}
}


function fileQueued( file )
{
	log("fileQueued: ID=" + file.id);
	var counter = this.customSettings.counter;
	
	var container = $("#upload-container-" + counter);
	
	var toClone = container.find(".example-progress");
	var uploadState = toClone.clone(true).removeClass("example-progress");
	uploadState.attr("id", "upload-id-" + counter + "-" + file.id);
	uploadState.find(".filename").text("\"" + file.name + "\"");
	uploadState.find(".remove").hide();
	container.find(".queue").append( uploadState );
	
	
	
	uploadState.show();
	
}

function uploadStart( file ) 
{
	log("uploadStart: ID=" + file.id);
	
	var counter = this.customSettings.counter;
	var uploadState = $("#upload-id-" + counter + "-" + file.id);
	uploadState.find(".progress").show().progressbar({ value: 0 });
	uploadState.find(".status").hide();
}

function uploadProgress( file, bytesLoaded ) 
{
	log("uploadProgress: ID=" + file.id + ", B=" + bytesLoaded);
	try {
		var counter = this.customSettings.counter;
		var percent = Math.ceil((bytesLoaded / file.size) * 100);

		
		var uploadState = $("#upload-id-" + counter + "-" + file.id);
		var status = uploadState.find(".status");
		if( status.text() == "Cancelled" )
		{
			return;
		}
		
		uploadState.find(".progress").progressbar('value', percent);
		if( percent === 100.0 )
		{
			uploadState.find(".status").text("Verifying...").show();
			uploadState.find(".progress").remove();
		} else {
			status.text("").hide();
			uploadState.find(".cancel").show();
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	var serverDataToShow = serverData;
	if( serverData.length > 100 ) 
	{
		serverDataToShow = "&lt;notshown&gt;";
	}
	log("uploadSuccess: ID=" + file.id + ", D=" + serverDataToShow);
	try {
		var counter = this.customSettings.counter;
		var maxSuccessful = this.customSettings.maxUploads;
		var uploadState = $("#upload-id-" + counter + "-" + file.id);
		if( serverData.substring(0, 8) == "success:" )
		{
			var fileId = serverData.substring(8);
			var pipe = fileId.indexOf('|');
			var size = fileId.substring( pipe + 1 );
			fileId = fileId.substring( 0, pipe );
			
			if( fileId == "" )
			{
				uploadState.find(".remove").remove();
			}
			
			var swfCon = $("#upload-container-" + counter);
			var complete = swfCon.find(".upload-complete");
			
			if( complete.length == maxSuccessful )
			{
				//knock off the first one
				complete.eq(0).remove();
			}
		
			uploadState.find(".status").text("(" + size + ")").show();
			uploadState.find(".progress").remove();
			uploadState.find(".fileId").text(fileId);
			uploadState.find(".cancel").remove();
			uploadState.find(".remove").show();
			uploadState.addClass("upload-complete");
			
			if( this.customSettings.preview !== false )
			{
				
				var previewCon = $(this.customSettings.preview);
				
				previewCon.attr("src", ctxp 
						+ "/mycontent/pendingfiledownload.action?width=75&height=75&fileId=" + fileId );
				previewCon.attr("class", fileId);
			}
			
		} else {
			uploadState.find(".status").text(serverData.substring(6)).show();
			uploadState.find(".progress").remove();
			uploadState.find(".cancel").remove();
		}
		
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	log("uploadComplete: ID=" + file.id);
	try {
		/*  We want the next upload to continue automatically so call startUpload here */
		if (this.getStats().files_queued > 0) {
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError( file, errorCode, message ) {
	log("uploadError: ID=" + file.id + ", C=" + errorCode + ", M=" + message);
	
	alert(message);
}



function swfUploadPreLoad() 
{
	log("swfUploadPreLoad");
	var swfUploadVar = this;
	var counter = swfUploadVar.customSettings.counter;
	var uploadContainer = $("#upload-container-" + counter);
	function longLoad()
	{
		uploadContainer.find(".loading-message").hide();
		uploadContainer.find(".long-loading").show();
		delete swfUploadVar.customSettings.longLoadTimer;
	}

	uploadContainer.find(".loading-message").show();
	
	swfUploadVar.customSettings.longLoadTimer = setTimeout( longLoad, 10000 ); 

}

function swfUploadLoaded() {
	log("swfUploadLoaded");
	if( this.customSettings.longLoadTimer )
	{
		var id = this.customSettings.longLoadTimer;
		delete this.customSettings.longLoadTimer;
		try {
			clearTimeout(id);
		} catch (ex) {}
	}
	
	var container = $("#upload-container-" + this.customSettings.counter);
	container.find(".loading-message").hide();
	container.find(".long-loading").hide();
	container.find(".loading-failed").hide();
}


function swfUploadLoadFailed()
{
	log("swfUploadLoadFailed");
	if( this.customSettings.longLoadTimer )
	{
		var id = this.customSettings.longLoadTimer;
		delete this.customSettings.longLoadTimer;
		//presumably if the timeout fires between us reading 
		//the value and us clearing it then this will still work
		//Better try catch to be sure
		try {
			clearTimeout( id );
		} catch (ex) {}
		
	}
	var container = $("#upload-container-" + this.customSettings.counter);
	container.find(".loading-message").hide();
	container.find(".long-loading").hide();
	container.find(".loading-failed").show();
}

//////////////////////////////////////////////////////////////
// SWFUpload Object Creation                                //
//////////////////////////////////////////////////////////////

var current_swf_counter = 1;

function swfUploadInit(con) 
{
	log("swfUploadInit");
	var swfCons = con.find(".swfUploadContainer");
	swfCons.each( function( index, element ) 
	{
		var swfCon = $(element);
		var button = swfCon.find(".upload-holder");
		if( button.length != 1 )
		{
			return;
		}
		
		var ourSettings = {
					sessionId:     '',
					purpose:       '',
					maxUploads:    '',
					buttonText:    '<span class="button">Select File (8MB Max)</span>',
					maxUploadSize: '8MB',
					preview:       false,
					action:        'uploadfileajax.action',
					removeAction:  'removefileajax.action?decorator=ajax&fileId=',
					quick:         ''
		};
		
		var instanceSettings = eval("(" + swfCon.find(".metadata").text() + ")");
		
		var compoundSettings = $.extend( {}, ourSettings, instanceSettings );
		
		compoundSettings.counter = current_swf_counter++;
		var button_id = "upload-holder-" + compoundSettings.counter;
		var container_id = "upload-container-" + compoundSettings.counter;
		button.attr("id", button_id);
		swfCon.attr("id", container_id);
		
		
		var settings = 
		{ 
			upload_url : ctxp + "/mycontent/" + compoundSettings.action + ";jsessionid=" + compoundSettings.sessionId,
			flash_url : ctxp + "/resource/yenka/3rdparty/SWFUpload/swfupload.swf", 
			file_size_limit : compoundSettings.maxUploadSize,
			
			file_types : "*.*",
			file_types_description : "All Files",
			file_upload_limit : 0,
			
			button_placeholder_id : button_id,
			button_width: 80,
			button_height: 20,
			button_text : compoundSettings.buttonText,
			button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; color: #8DA260; }',
			button_text_top_padding: 3,
			button_text_left_padding: 0,
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_cursor: SWFUpload.CURSOR.HAND,
			button_action : SWFUpload.BUTTON_ACTION.SELECT_FILE,
			
			post_params:
			{
				"decorator": "ajax",
				"purpose": compoundSettings.purpose,
				"quick": compoundSettings.quick
			},
			
			debug: debug,
			
			// Event Handlers
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,
			file_queued_handler: fileQueued,
			upload_start_handler : uploadStart,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,
			
			//swfobject
			swfupload_loaded_handler : swfUploadLoaded,
			swfupload_pre_load_handler : swfUploadPreLoad,
			swfupload_load_failed_handler : swfUploadLoadFailed,
			
			custom_settings: compoundSettings
		}
		
		var swfu = new SWFUpload(settings);
		
		swfUploadQueueLinks(swfCon, swfu);
		
	});
	
	
}


//////////////////////////////////////////////////////////////
// File Management                                          //
//////////////////////////////////////////////////////////////

function swfUploadQueueLinks(swfCon, swfUpload) {
	$(".remove a", swfCon).click
	(
		function( event )
		{
			event.preventDefault();
			var element = $(this);
			//this replicates uploadState = element.closest(".upload-progress");
			//in jquery < 1.3
			var uploadState = element;
			while ( !uploadState.is(".upload-progress") )
			{
				uploadState = uploadState.parent();
			}
			var fileId = uploadState.find(".fileId").text();
			
			var baseRemoveAction = swfUpload.customSettings.removeAction;
			var action = baseRemoveAction + fileId;
			
			log("Removing file " + fileId + " from upload session");
			$.ajax({
				dataType: "text",
				
				error : function (XMLHttpRequest, textStatus, errorThrown) 
				{
  					// typically only one of textStatus or errorThrown 
  					// will have info
  					uploadState.find(".status").text("Not Deleted. S:" + textStatus + " E:" + errorThrown);
				},
				
				success: function (data, textStatus) 
				{
					if( data.substring( 0, 7 ) == "success" )
					{
						var preview = $( "#upload-preview" );
						if( preview.hasClass(fileId))
						{
							preview.attr("src", ctxp + "/resource/yenka/graphics/uploadicons/unknowncontent.gif");
							preview.attr("class", "");
						}
  						uploadState.remove();
  					} 
  					else 
  					{
  						var error = data;
  						if( data.substring( 0, 5) == "error" )
  						{
  							error = data.substring(5);
  						}
  						uploadState.find(".status").html("Not Deleted. E:" + error).show(); 
  					}
				},
				
				url: action
				
			}); 
							
			
		}
	);
	
	$(".cancel a", swfCon).click
	(
		function(event)
		{
			event.preventDefault();
			var element = $(this);
			//this replicates uploadState = element.closest(".upload-progress");
			//in jquery < 1.3
			var uploadState = element;
			while ( !uploadState.is(".upload-progress") )
			{
				uploadState = uploadState.parent();
			}
			var fileId = uploadState.attr("id").substring(("upload-id-" + swfUpload.customSettings.counter + "-").length);
			log("Cancelling file " + fileId);
			
			swfUpload.cancelUpload(fileId, false);
			uploadState.find(".status").text("Cancelled").show();
			uploadState.find(".cancel").remove();
			uploadState.find(".progress").remove();
			
		}
	);
}



