// Form Support v1.0
// Andrew Pettican (May 2011)
//
// Changelog:
// v1.0 - 19/05/2011 - Initial build
//////////////////////////////////////////////////////////////////

// ---------------------------------------------------------------
// Parameters
// ---------------------------------------------------------------

// Field id's with default text
var fs_default_field_text = new Array();
fs_default_field_text['frm_enter_dob_dd'] = "dd";
fs_default_field_text['frm_enter_dob_mm'] = "mm";
fs_default_field_text['frm_enter_dob_yyyy'] = "yyyy";
fs_default_field_text['frm_enter_statement'] = "";

// For resetting fields back to defaults
var fs_default_file_class = "default";

// Acceptable photo/video file extensions (taken from mimes.php)
var fs_photo_file_extensions = new Array('gif','jpeg','jpg','png');
var fs_video_file_extensions = new Array('mov','qt','3gp','avi','vob','flv','mp4','mpg','mpeg','mpe','rm','rmvb','wmv');

// For upload progressbar
var fs_progress_key = "";					// The progress key to keep track of the upload. We will expect this to be set externally.
var fs_progress_timeout = 2000;				// Update the fs_active_progress_bar_target every 2 seconds
var fs_seconds_remaining = 0;				// To keep track of the upload time remaining (s)
var fs_upload_speed = 0;					// To keep track of the upload speed (kb/s)
var fs_null_response_counter = 0;			// To keep track of null responses from the uploadprogress requests
var fs_active_progress_wrapper = "";		// The active progress wrapper object
var fs_active_progress_bar = "";			// The active progress bar object
var fs_active_progress_stats = "";			// The active progress stats object
var fs_active_progress_notice = "";			// The active progress bar notice object
var fs_active_progress_bar_position = 0;	// The position of the active progress bar
var fs_active_progress_bar_target = 0;		// The target position of the active progress bar
var fs_max_movement_to_target = 0.1;		// Maximum amount the progress bar will move in one step towards the fs_active_progress_bar_target
var fs_min_movement_of_bar = 1.0;			// Minimum amount the progress bar will move in one step when it is below the fs_active_progress_bar_target
var fs_bar_step_interval = 100;				// The progress bar will update its position at 10fps (every 100ms)
var fs_ready_to_redirect = false;			// Flag indicating if we are ready to redirect after uploading a file
var fs_pb_interval = null;					// For keeping track of the progress bar interval timer
var fs_pn_interval = null;					// For keeping track of the progress notification interval timer
var fs_up_interval = null;					// For keeping track of the upload progress timer

// ---------------------------------------------------------------
// Parameters End
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// Functions
// ---------------------------------------------------------------

/**
 * Initialises the default fields on the form
 */
function initialise_default_fields()
{
	var field_ids_to_watch = "";
	for(field in fs_default_field_text)
	{
		if(field_ids_to_watch !== "")
		{
			field_ids_to_watch += ", ";
		}
		field_ids_to_watch += "#"+field;
		
		// Set the field to its default value?
		if($("#"+field).val() == "")
		{
			$("#"+field).val(fs_default_field_text[field]);
			$("#"+field).addClass('default');
		}
		
		// Apply the default class to fields which have been set to the default value themselves
		// NB: Firefox will reload old form data if the form is refreshed, this is required to make that default text appear correctly.
		else if($("#"+field).val() == fs_default_field_text[field] && !$("#"+field).hasClass('default'))
		{
			$("#"+field).addClass('default');
		}
	}
	return field_ids_to_watch;
}


/**
 * Validates the given filename against an array of accepted file extensions (case-insensitive)
 */
function validate_upload_field(filename, accepted_extensions, required)
{
	var result = false;
	
	if(filename !== "" && typeof(filename) !== undefined)
	{
		// Find the '.'
		var extension_index = filename.lastIndexOf(".");
		if(extension_index > 0 && (filename.length+1) > extension_index)
		{
			// Find the file extension
			var file_extension = filename.substr(extension_index+1).toLowerCase();
			if(file_extension !== "")
			{
				// Check that the file extension matches one of our accepted ones (this is case-insensitive)
				for(i=0; i<accepted_extensions.length; i++)
				{
					if(file_extension == accepted_extensions[i].toLowerCase())
					{
						result = true;
					}
				}
			}
		}
	}
	else if(!required)
	{
		// the field is blank, but it is not required.
		result = true;
	}
	
	return result;
}


/**
 * Checks that the upload fields on the entry form appear to be valid.
 * Hopefully we can stop most bad files from being uploaded at this stage.
 */
function upload_fields_validated()
{
	// Clear any old messages and error classes on the upload field, dummy upload field, and related label
	$("#validation_errors").html("").css("display", "none");
	$(".frm_enter_photo label, .frm_enter_photo .uploader, .frm_enter_photo input#frm_enter_photo_original").removeClass("error");
	$(".frm_enter_video label, .frm_enter_video .uploader, .frm_enter_video input#frm_enter_video_original").removeClass("error");
	
	// Determine the filenames selected for upload (if any)
	var photo_filename = $("#frm_enter_photo_original").val();
	var video_filename = $("#frm_enter_video_original").val();
	
	// Determine the file extensions of these files
	var photo_valid = validate_upload_field(photo_filename, fs_photo_file_extensions, false);
	var video_valid = validate_upload_field(video_filename, fs_video_file_extensions, false);
	
	// Display error messages if needed
	var error_message = "";
	if(!photo_valid && !video_valid)
	{
		error_message = jslang['barclays.enter.invalid_photo_video'];
	}
	else if(!photo_valid)
	{
		error_message = jslang['barclays.enter.invalid_photo'];
	}
	else if(!video_valid)
	{
		error_message = jslang['barclays.enter.invalid_video'];
	}
	
	if(error_message !== "")
	{
		// Create validation_errors div if needed
		if($("#validation_errors").length <= 0)
		{
			$('<div class="validation_errors" id="validation_errors"></div>').insertBefore('form#frm_enter');
		}
		
		// Dump the message onto the page
		$("#validation_errors").html("<p>"+error_message+"</p>").css("display", "block");
	}
	
	return (video_valid && photo_valid);
}


/**
 * Initialises the progress bar returning true/false to indicate if this was successful.
 */
function initialise_progress_bar(id)
{
	//$('#debug').html('initialise_progress_bar('+id+')<br />'+$('#debug').html());
	// Check that the id represents a valid progress bar wrapper
	if(document.getElementById(id) !== null && $("#"+id).hasClass("progress_wrapper"))
	{
		// Find the progress bar and progress stats objects within the wrapper
		fs_active_progress_wrapper = id;
		fs_active_progress_bar = "progress_bar";
		fs_active_progress_stats = "progress_stats";
		fs_active_progress_notice = "progress_notice";
		if($("#"+id+" #"+fs_active_progress_bar).length <= 0)
		{
			fs_active_progress_bar = "";
		}
		if($("#"+id+" #"+fs_active_progress_stats).length <= 0)
		{
			fs_active_progress_stats = "";
		}
		if($("#"+id+" #"+fs_active_progress_notice).length <= 0)
		{
			fs_active_progress_notice = "";
		}
		
		// Do we have the required ids?
		if(fs_active_progress_bar !== "")
		{
			// Initialise the progress bar to its fs_active_progress_bar_target state
			$("#"+fs_active_progress_bar).progressbar({ value: fs_active_progress_bar_target });
			
			// Fade the progress bar wrapper in
			$("#"+fs_active_progress_wrapper).fadeIn();
			
			return true;
		}
	}
	return false;
}


/**
 * Updates the status of the fs_active_progress_bar for the given upload status information
 * 
 * upload_status should have the following properties:
 * 	"time_start":"1214384364",
 * 	"time_last":"1214384366",
 * 	"speed_average":"25889",
 * 	"speed_last":"40952",
 * 	"bytes_uploaded" :"51778",
 * 	"bytes_total":"8125518",
 * 	"files_uploaded":"0",
 * 	"est_sec":"311"
 */
function update_progress_bar(upload_status)
{
	//$('#debug').html('update_progress_bar('+upload_status+')<br />'+$('#debug').html());
	// Should we update the stats message?
	var update_stats_msg = false;
	
	// Ensure we actually have an active progress bar and the required upload_status properties
	if(upload_status != null && fs_active_progress_bar !== "" && upload_status.hasOwnProperty("speed_last") && upload_status.hasOwnProperty("bytes_uploaded") && upload_status.hasOwnProperty("bytes_total") && upload_status.hasOwnProperty("est_sec"))
	{
		// What is the percentage complete?
		var percentage = Math.floor(100 * parseInt(upload_status.bytes_uploaded) / parseInt(upload_status.bytes_total));
		
		// What is the current upload speed?
		fs_upload_speed = (Math.round(upload_status.speed_last / 102.4) / 10); // To convert bytes/s into kb/s
		
		// Estimate how much time is remaining
		fs_seconds_remaining = parseInt(upload_status.est_sec, 10);
		update_stats_msg = true;
		
		// Set a new target for the progress bar to reach
		fs_active_progress_bar_target = percentage;
	}
	
	// Otherwise, just reduce the remaining time by 1 second (providing we haven't reached 0)
	else if(fs_seconds_remaining > 1)
	{
		fs_seconds_remaining--;
		update_stats_msg = true;
	}
	
	// Update the stats message?
	if(update_stats_msg = true && fs_active_progress_stats !== "")
	{
		var temp_time = fs_seconds_remaining;
		var upload_time_hh = Math.floor(temp_time / (60*60));
		temp_time -= upload_time_hh*60*60;
		var upload_time_mm = Math.floor(temp_time / 60);
		temp_time -= upload_time_mm*60;
		var upload_time_ss = Math.floor(temp_time);
		var remaining_time = format_time(upload_time_hh, upload_time_mm, upload_time_ss);
		
		var stats_message = "";
		if(remaining_time !== "")
		{
			stats_message += remaining_time+" "+jslang['barclays.enter.remaining']+" ("+fs_upload_speed+"KB/s)";
		}
		else
		{
			stats_message += "&nbsp;";
		}
		$("#"+fs_active_progress_stats).html(stats_message);
	}
}


/**
 * Formats the timecode (hh, mm, ss) into a human readable string
 * e.g. format_time(0, 4, 32) returns "4 minutes 32 seconds"
 * NB: we will only show 2 parts of the time. This means if there is over 1 hour, seconds will not be shown, if there is under 1 hour, seconds will be shown.
 * e.g. 1 hour 4 minutes ... 59 minutes 34 seconds
 */
function format_time(hh, mm, ss)
{
	var upload_time_readable = "";
	var parts_shown = 0;
	if(hh > 0 && parts_shown < 2)
	{
		upload_time_readable += (upload_time_readable !== "" ? " " : "")+hh+(hh > 1 ? jslang['barclays.enter.hours'] : jslang['barclays.enter.hour']);
		parts_shown += 1;
	}
	if(mm > 0 && parts_shown < 2)
	{
		upload_time_readable += (upload_time_readable !== "" ? " " : "")+mm+(mm > 1 ? jslang['barclays.enter.minutes'] : jslang['barclays.enter.minute']);
		parts_shown += 1;
	}
	if(ss > 0 && parts_shown < 2)
	{
		upload_time_readable += (upload_time_readable !== "" ? " " : "")+ss+(ss > 1 ? jslang['barclays.enter.seconds'] : jslang['barclays.enter.second']);
		parts_shown += 1;
	}
	return upload_time_readable;
}


/**
 * Keeps the user informed of the status of the upload until it is complete
 */
function begin_upload(progress_key)
{
	// Ensure that the progress_key is set properly
	if(typeof(progress_key) == "string" && progress_key != "")
	{
		//$('#debug').html('begin_upload('+progress_key+')<br />'+$('#debug').html());
		
		// Set this now so we can redirect as soon as we're ready
		// If we set this after the upload completes, the iframe event which triggers the redirect will ahave passed already
		fs_ready_to_redirect = true;
		
		// Start polling the server for the status of the upload
		get_upload_progress(progress_key);
		
		// Locally poll the progress bar to animate it up to the fs_active_progress_bar_target
		fs_pb_interval = setInterval(function()
		{
			// Have we reached the target position yet?
			if(fs_active_progress_bar_position < fs_active_progress_bar_target)
			{
				// Determine how far we will move in this interval
				// A max of fs_max_movement_to_target towards the fs_active_progress_bar_target
				// A min a fs_max_movement_to_target step along the progress bar
				var movement = Math.max(fs_min_movement_of_bar, Math.round((fs_active_progress_bar_target-fs_active_progress_bar_position)*fs_max_movement_to_target));
				
				// Ensure that the movement we've selected won't take us over the fs_active_progress_bar_target
				var max_movement_of_bar = fs_active_progress_bar_target-fs_active_progress_bar_position;
				movement = Math.min(max_movement_of_bar, movement);
				
				// Increment by the calculated movement every fs_bar_step_interval
				fs_active_progress_bar_position += movement;
				$("#"+fs_active_progress_bar).progressbar('option', 'value', fs_active_progress_bar_position);
			}
			
			// We've reached the target, but we should only stop polling if the target is at a full 100%
			else if(fs_active_progress_bar_target >= 100)
			{
				// Clean up
				clearInterval(fs_pb_interval);
				fs_pb_interval = null;
			}
		}, fs_bar_step_interval);
		
		
		// Update the '...' message and reduce the time remaining every second
		if(fs_active_progress_notice !== "")
		{
			fs_pn_interval = setInterval(function()
			{
				if($("#"+fs_active_progress_notice+" #dots").length > 0)
				{
					var dots_txt = $("#"+fs_active_progress_notice+" #dots").html();
					if(dots_txt == ".&nbsp;&nbsp;")
					{
						dots_txt = "..&nbsp;";
					}
					else if(dots_txt == "..&nbsp;")
					{
						dots_txt = "...";
					}
					else if(dots_txt == "...")
					{
						dots_txt = ".&nbsp;&nbsp;";
					}
					$("#"+fs_active_progress_notice+" #dots").html(dots_txt);
				}
				else
				{
					// Our dots have gone, presume the upload is complete
					clearInterval(fs_pn_interval);
					fs_pn_interval = null;
				}
				update_progress_bar(null);
			}, 1000);
		}
	}
	return true;
}


/**
 * Repeatedly polls the server for the latest status info of the upload.
 * The frequency between polls will reduce as the time to completion nears.
 * This is to prevent hammering the server when an upload still has a long time to complete.
 */
function get_upload_progress(progress_key)
{
	//$('#debug').html('get_upload_progress('+base_url+'upload_progress.php?id='+progress_key+')<br />'+$('#debug').html());
	$.getJSON(base_url+"upload_progress.php?id=" + progress_key, function(data)
	{
		// Has the upload completed?
		if (data == null)
		{
			// Presume that the server may accidently return null responses under high load
			// Only allow this routine to stop polling if we receive 10 nulls in a row
			fs_null_response_counter++;
			if(fs_null_response_counter >= 10)
			{
				// Force the progress bar to 100%
				fs_active_progress_bar_target = 100;
				if(fs_active_progress_stats !== "")
				{
					$("#"+fs_active_progress_stats).html("&nbsp;");
				}
				if(fs_active_progress_notice !== "")
				{
					$("#"+fs_active_progress_notice).html(jslang['barclays.enter.upload_complete']).css('text-align', 'center');
				}
				
				// Done
				fs_progress_timeout = -1;
			}
			else
			{
				// Null response, ask the server again in 1 second
				fs_progress_timeout = 1000;
			}
		}
		
		// Otherwise update the progress bar
		else
		{
			fs_null_response_counter = 0;
			update_progress_bar(data);
			
			// Determine how long we should wait before asking for updated progress info
			if(fs_seconds_remaining > 60*60)
			{
				// Over 1 hr remaining, check progress every 20 seconds
				fs_progress_timeout = 20000;
			}
			else if(fs_seconds_remaining > 30*60)
			{
				// Over 30 mins remaining, check progress every 15 seconds
				fs_progress_timeout = 15000;
			}
			else if(fs_seconds_remaining > 10*60)
			{
				// Over 10 mins remaining, check progress every 10 seconds
				fs_progress_timeout = 10000;
			}
			else if(fs_seconds_remaining > 5*60)
			{
				// Over 5 mins remaining, check progress every 5 seconds
				fs_progress_timeout = 5000;
			}
			else if(fs_seconds_remaining > 2*60)
			{
				// Over 2 mins remaining, check progress every 3 seconds
				fs_progress_timeout = 3000;
			}
			else
			{
				// Under 2 mins remaining, check progress every 2 seconds
				fs_progress_timeout = 2000;
			}
		}
	});
	
	// Ensure that we never ask the server at less than 1 second intervals
	if(fs_progress_timeout >= 1000)
	{
		fs_up_interval = setTimeout(function(){get_upload_progress(progress_key)}, fs_progress_timeout);
	}
	else
	{
		fs_up_interval = null;
	}
}

// ---------------------------------------------------------------
// Functions End
// ---------------------------------------------------------------



// ---------------------------------------------------------------
// JS Events
// ---------------------------------------------------------------
jQuery(document).ready(function()
{
	// Uniform (All browsers except for IE6 and below)
	//////////////////////////////////////////////////////////////
	if(ie == -1 || ie > 6)
	{
		$("select, input[type=checkbox], input[type=radio], input[type=text], input[type=email], input[type=password], input[type=file], input[type=submit], input[type=reset], textarea, button").not(".nojs").uniform(
		{
			fileDefaultText: jslang['barclays.enter.no_file'],
			fileBtnText: jslang['barclays.enter.browse']
		});
		$("form").removeClass("naked").addClass("uniformed");
	}
	
	
	// Some field ids will have default text.
	//////////////////////////////////////////////////////////////
	// Initialise fields
	var field_ids_to_watch = initialise_default_fields();
	
	// Any fields to watch?
	if(field_ids_to_watch !== "")
	{
		// A default field has received focus
		$(field_ids_to_watch).bind('click focus', function(event)
		{
			// Remove default settings?
			var field_id = this.id;
			if(field_id !== "" && fs_default_field_text.hasOwnProperty(field_id) && $("#"+field_id).hasClass('default'))
			{
				$("#"+field_id).val("");
				$("#"+field_id).removeClass('default');
			}
		});
		
		// A default field has lost focus
		$(field_ids_to_watch).bind('focusout', function(event)
		{
			// Apply default settings?
			var field_id = this.id;
			if(field_id !== "" && fs_default_field_text.hasOwnProperty(field_id) && $("#"+field_id).val() == "")
			{
				$("#"+field_id).addClass('default');
				$("#"+field_id).val(fs_default_field_text[field_id]);
			}
		});
	}
	
	// When a form is submitted, clear all default input/textarea fields, these should not be sent to the server
	$("form").submit(function()
	{
		$("input.default, textarea.default").val("");
	});
	
	
	// When the 'enter' key is pressed on a the entry form, prevent form submission
	// The only exception to this is using the 'enter' key within textareas (Should we allow linebreaks?)
	//////////////////////////////////////////////////////////////
	$("form#frm_enter").keypress(function(event)
	{
		//if(event.keyCode == 13 && event.target.nodeName.toLowerCase() !== "textarea")
		/*
		if(event.keyCode == 13)
		{
			// Prevent form submission on an enter keypress
			return false;
		}
		*/
	});
	
	
	// Form upload fields.
	// The real file input may need to have its size adjusted
	// NB: This applies to all file inputs
	//////////////////////////////////////////////////////////////
	$('form .uf_uploader').each(function()
	{
		var max_file_field_size = 100;
		var $uf_file = $(this).find("input[type='file']:first");
		//$uf_file.css('opacity', 0.5);
		$uf_file.width('auto'); // This wont work with fixed css widths
		if($uf_file.length === 1)
		{
			// The target width for the $uf_file is based on the div.uploader width
			var target_file_width = $(this).width();
			
			// Adjust the size attribute repeatedly until we either:
			// a. Beat the width of the div.uploader
			// b. Reach a predefined maximum 'size' (i.e. 22)
			var width_start = $uf_file.width();
			var size_before = $uf_file.attr("size");
			while($uf_file.width() < target_file_width && $uf_file.attr("size") < max_file_field_size) {
				$uf_file.attr('size', parseInt($uf_file.attr('size')) + 1);
			}
			var size_after = $uf_file.attr("size");
			
			// In order to prevent our width going over, force the width to match the div.uploader
			var width_before = $uf_file.width();
			$uf_file.width(target_file_width);
			var width_after = $uf_file.width();
			var size_final = $uf_file.attr("size");
			//alert(size_before+" > "+size_after+" > "+size_final+"\n"+width_start+" > "+width_before+" > "+width_after+">"+target_file_width);
		}
	});
	
	
	// Uploader controls
	// NB: This applies only to file inputs wrapped within a .uploader div
	//////////////////////////////////////////////////////////////
	
	// Set initial filename if we have a .file_saved
	$("form .uploader").each(function()
	{
		// Find the related parts of .uploader
		var $uploader_wrapper = $(this);
		var $uf_uploader = $uploader_wrapper.find('.uf_uploader:first');
		var $uf_filename = $uf_uploader.find('.uf_filename:first');
		
		// For saved files which are already uploaded
		var $file_saved = $uploader_wrapper.find('.file_saved:first');
		
		// Got required nodes?
		if($uploader_wrapper.length === 1 && $uf_uploader.length === 1 && $uf_filename.length === 1 && $file_saved.length === 1)
		{
			if($file_saved.html() !== "")
			{
				var filename = $file_saved.html().split(/[\/\\]+/);
				filename = filename[(filename.length-1)];
				$uf_filename.html(filename).removeClass('default');
			}
		}
	});
	
	// Clear the file and file_dummy input fields
	// NB: This will cause the form to submit
	$("form .uploader input.uf_button_cancel").click(function(event)
	{
		// Find the related parts of .uploader
		var $form = $(this).parents('form:first');
		var $file_clear_submit = $(this);
		var $uploader_wrapper = $(this).parents('.uploader:first');
		var $uf_uploader = $uploader_wrapper.find('.uf_uploader:first');
		var $uf_filename = $uf_uploader.find('.uf_filename:first');
		var $uf_file = $uf_uploader.find("input[type='file']:first");
		
		// For saved files which are already uploaded
		var $file_saved = $uploader_wrapper.find('.file_saved:first');
		
		// Got required nodes?
		if($uploader_wrapper.length === 1 && $uf_uploader.length === 1 && $uf_filename.length === 1 && $uf_file.length === 1 && $file_clear_submit.length === 1 && $file_saved.length === 1)
		{
			// We have a saved file, the form must be _POSTed to clear it
			if($file_saved.html() !== "")
			{
				// Destroy all file inputs
				$form.find("input[type='file']").each(function()
				{
					$(this).replaceWith('');
				});
				
				// Reset the form target
				$form.attr('target', '_self');
				
				// Submit the form
				$(file_clear_submit).trigger('click');
			}
			
			// We have a local file which has not yet uploaded, we may be able to clear it with JS
			else if($uf_file.val() !== "")
			{
				// Clear the file input
				$uf_file.val("");
				
				// Reset the visible filename
				$uf_filename.html(jslang['barclays.enter.no_file']).addClass(fs_default_file_class);
				
				// This will not always work, so double check that the file field is clear
				if($uf_file.val() !== "")
				{
					// Destroy all file inputs
					$form.find("input[type='file']").each(function()
					{
						$(this).replaceWith('');
					});
					
					// Reset the form target
					$form.attr('target', '_self');
					
					// Submit the form
					$(file_clear_submit).trigger('click');
				}
				else
				{
					return false;
				}
			}
			else
			{
				// There isn't a file to cancel
				return false;
			}
		}
	});
	
	
	// Reset button clicked
	//////////////////////////////////////////////////////////////
	$("form input[type='reset']").click(function(event)
	{
		// Find the related parts of the form
		var $form = $(this).parents('form:first');
		var $uf_filenames = $form.find('.uf_filename');
		$uf_filenames.each(function()
		{
			$(this).html(jslang['barclays.enter.no_file']).addClass(fs_default_file_class);
		});
		
		// Reinitialise default fields
		// NB: This must happen after a delay to allow the reset function to make all fields blank first
		setTimeout(function()
		{
			initialise_default_fields();
		}, 200);
	});
	
	
	// Upload button was clicked.
	// Set a target on this form to ensure the progressbar will work
	//////////////////////////////////////////////////////////////
	$("input#frm_enter_submit").click(function()
	{
		var $form = $(this).parents('form:first');
		
		// Validate the filename, hopefully we can prevent users from uploading bad files before they post the form.
		if($form.length === 1 && upload_fields_validated())
		{
			// Only post the form to the frame if we are uploading files
			if($("#frm_enter_photo_original").val() !== "" || $("#frm_enter_video_original").val() !== "")
			{
				// Hide the submission buttons
				$form.find('fieldset.frm_enter_submit').fadeOut();
				
				// Initialise the progress bar
				if(initialise_progress_bar("progress_wrapper"))
				{
					// Trigger the begin_upload loop to keep track of progress
					$form.attr('target', 'progress_frame');
					begin_upload(fs_progress_key);
				}
			}
		}
		else
		{
			return false;
		}
	});
	/*
	// DEBUG
	setTimeout(function()
	{
		initialise_progress_bar("progress_wrapper");
		fs_active_progress_bar_target = 60;
		begin_upload('1');
	}, 3000);
	*/
	
	
	// Redirect back to the register form with the upload page set when the progress iframe indicates that it has loaded after a file upload
	//////////////////////////////////////////////////////////////
	$("iframe#progress_frame").bind("load", function()
	{
		if(fs_ready_to_redirect)
		{
			// Set some final messages
			fs_active_progress_bar_target = 100;
			if(fs_active_progress_stats !== "")
			{
				$("#"+fs_active_progress_stats).html("&nbsp;");
			}
			if(fs_active_progress_notice !== "")
			{
				$("#"+fs_active_progress_notice).html(jslang['barclays.enter.upload_complete']).css('text-align', 'center');
			}
			
			location.assign(base_url+(current_lang == "hk" ? "hk/" : "")+"enter/upload");
		}
	});
});

// ---------------------------------------------------------------
// JS Events End
// ---------------------------------------------------------------
