function callToFlash(id, val)
{
	if ($(id).length > 0)
	{
		$(id).get(0).sendToFlash(val);
	}

	else
	{
		console.log('Uploader Not Found');
	}
}

function callFromFlash(val)
{
	console.log('Flash Says: ' + val);
}

function initMultiCheckboxes()
{
	// Remove any preexisting click functions.
	$('div.iu_multi input.iu_multi_checkbox').unbind('click');

	// Setup the click function to set the delete flag
	$('div.iu_multi input.iu_multi_checkbox').click(function(e)
	{
		e.stopPropagation();

		var tempBox = $(this);

		if (tempBox.attr('checked'))
		{
			tempBox.parents('.iu_info').find('.iu_multi_delete').val(1);
		}

		else
		{
			tempBox.parents('.iu_info').find('.iu_multi_delete').val(0);
		}

		return true;
	});
}

// Progress response from Flash
function imageProgress(mode, field_id, progress)
{
	console.log('Progress: ' + field + ': ' + progress + '%');

	var field = $('#' + field_id);

	// Hide the upload button
	if (mode == 'single')
	{
		field.find('.iu_button_container').addClass('iu_button_hidden');
	}

	else
	{
		disableMultiSort(field.parents('.iu_multi').attr('id'));
		field.parents('.iu_multi').find('.iu_button_container').addClass('iu_button_hidden');
	}

	// Show the status window
	var status = field.find('.iu_status');
	status.removeClass('hidden');

	// If the progress is finished then show the formatting message
	if (progress >= 100)
	{
		status.html('Upload Complete: Now Formatting Image');
	}

	// Otherwise show the progress percentage
	else
	{
		status.html('Uploading Image: ' + progress + '%');
	}

	// Add the loading class and update the progress bar width
	field.addClass('iu_loading');
	field.find('.iu_progress .iu_bar').width(progress + '%');
}

// Image completion response from Flash
function imageFinished(mode, field_id, json_data, filesLeft)
{
	// Convert the data to JSON format.
	var data = eval('(' + json_data + ')');
	var error = '';
	var field = $('#' + field_id);
	var status = (mode == 'single' ? field.find('.iu_status') : field.parents('.iu_container').find('.iu_button_container .iu_status'));

	console.log(field_id + ' Finished: ' + data);

	// Remove the loading status class and show the image upload button
	field.removeClass('iu_loading');

	if (mode == 'single')
	{
		field.find('.iu_button_container').removeClass('iu_button_hidden');
	}

	else if (filesLeft <= 0)
	{
		initMultiSort(field.parents('.iu_multi').attr('id'));
		field.parents('.iu_multi').find('.iu_button_container').removeClass('iu_button_hidden');
	}

	// If there was an error with the upload
	if (typeof(data.errors) != 'undefined' && data.errors.length > 0)
	{
		error = '<div class="iu_error_item">' + data.errors.join('</div><div class="iu_error_item">') + '</div>';
	}

	// If the image was uploaded successfully
	else if (typeof(data.filename) != 'undefined' && data.filename != '')
	{
		// If the new preview image already exists then update it's URL
		if (field.find('.iu_new_preview').length > 0)
		{
			field.find('.iu_new_preview').attr('src', '/assets/img/tmp/preview/' + data.filename + '.jpg?' + Math.floor(Math.random() * 100000000));
		}

		// Otherwise add the new image to the image to the page
		else
		{
			var img = $('<img class="iu_new_preview" title="New Image Preview" src="/assets/img/tmp/preview/' + data.filename + '.jpg?' + Math.floor(Math.random() * 100000000) + '" />');
			field.find('.iu_preview').prepend(img);
		}

		// If there is a current image then hide it.
		if (field.find('.iu_cur_preview').length > 0)
		{
			field.find('.iu_cur_preview').addClass('hidden');
		}

		// Update the forms field value
		if (mode == 'single')
		{
			field.find('.iu_new_file input').val(data.filename);
			field.find('div.error-message').remove();
		}

		else
		{
			field.find('input.iu_multi_new').val(data.filename);
		}
	}

	// Otherwise there was an error with the data
	else
	{
		error = '<div class="iu_error_item">Error processing image file.  Try again.</div>';
	}

	// If there is no image selected yet show the status message
	if (field.find('.iu_new_preview, .iu_cur_preview').length <= 0)
	{
		if (mode == 'single')
		{
			status.html('No Image Selected').removeClass('hidden');
			field.find('.iu_delete').addClass('hidden');
		}

		else
		{
			field.remove();
		}
	}

	// Otherwise hide the status message
	else
	{
		field.find('.iu_delete').removeClass('hidden');
		field.find('.iu_status').html('').addClass('hidden');
		status.html('').addClass('hidden');
	}

	// If there was an error then show the user
	if (error != '')
	{
		status.append(error).removeClass('hidden');

		status.find('.iu_error_item').unbind('click').click(function(e)
		{
			e.stopPropagation();

			$(this).remove();

			return false;
		});
	}
}

// Add an image to a multi image area
function addMultiItem(id)
{
	var par = $('#' + id + ' .iu_button_container input.parent');

	if (par.length > 0)
	{
		par = par.val();

		var node = $('<div id="" class="iu_multi_item"><div class="iu_sort_handle"></div><div class="iu_preview"><div class="iu_status"></div><div class="iu_progress"><div class="iu_bar"></div></div></div><div class="iu_info"><input type="hidden" name="data[' + par + '][id][]" value="" class="iu_multi_id" /><input type="hidden" name="data[' + par + '][new][]" value="" class="iu_multi_new" /><input type="hidden" name="data[' + par + '][delete][]" value="0" class="iu_multi_delete" /><div class="input checkbox iu_delete hidden"><input type="checkbox" name="" value="1" class="iu_multi_checkbox" /><label for="">Delete This Image</label></div><hr class="clear" /></div></div>');

		node.insertBefore('#' + id + ' .iu_button_container');

		$('#' + id + ' .iu_multi_item').identify('iu_multi_' + par);

		var lastNode = $('#' + id + ' .iu_multi_item:last');

		var checkbox = lastNode.find('.iu_multi_checkbox');
		checkbox.identify('MultiDelete' + par);

		lastNode.find('.iu_delete label').attr('for', checkbox.attr('id'));

		initMultiCheckboxes()

		initMultiSort(id);

		return lastNode.attr('id');
	}

	return false;
}

// Initialize the drag and drop photo sorting
var initMultiSort = function (id)
{
	disableMultiSort(id);

	if (!$('#' + id).hasClass('iu_no_sort'))
	{
		$('#' + id).addClass('iu_sortable');

		$('#' + id).sortable(
		{
			revert: 		false,
			placeholder: 	'iu_multi_placeholder',
			handle:			'div.iu_preview',
			items:			'div.iu_multi_item',
			containment:	$('#' + id).parent().parent()
		});
	}

	else
	{
		initProjectContent();
	}
}

// Removes a sortable
var disableMultiSort = function (id)
{
	$('#' + id).removeClass('iu_sortable');
	$('#' + id).sortable('destroy');
}

// Initialize the image uploaders
function initImageUploader()
{
	initMultiCheckboxes();

	// If the user has Flash installed
	if (swfobject.hasFlashPlayerVersion('9.0'))
	{
		// Add the image upload button for each single image
		$( ".iu_single .iu_button").each
		(
			function(index)
			{
				var parent = $(this).parents('.iu_single');
				var field_id = parent.attr('id');
				var btn_id = $(this).attr('id');
				var url = $(this).parents('.iu_button_container').find('input.url').val();

				// Hide the status message if there is no message
				if (parent.find('.iu_status').html() == '')
				{
					parent.find('.iu_status').addClass('hidden');
				}

				if (parent.find('.iu_new_preview, .iu_cur_preview').length <= 0)
				{
					parent.find('.iu_delete').addClass('hidden');
				}

				// Setup the Flash button parameters
				var vars = {id:field_id, url:url, mode:'single'};
				var params = {scale:'noScale', salign:'lt', menu:'false', allowScriptAccess:'always', wmode:'transparent'};
				var attributes = {id:btn_id, name:btn_id, bgcolor:'#FFFFFF'};

				swfobject.embedSWF('/assets/swf/image_uploader_front.swf', btn_id, '200', '30', '9.0', '', vars, params, attributes);
			}
		);

		// Add the image upload button for each multi image upload area
		$( ".iu_multi .iu_button").each
		(
			function(index)
			{
				var parent = $(this).parents('.iu_multi');
				var field_id = parent.attr('id');
				var btn_id = $(this).attr('id');
				var url = $(this).parents('.iu_button_container').find('input.url').val();

				initMultiSort(field_id);

				// Setup the Flash button parameters
				var vars = {id:field_id, url:url, mode:'multi', label:'SELECT IMAGE(S)'};
				var params = {scale:'noScale', salign:'lt', menu:'false', allowScriptAccess:'always', wmode:'transparent'};
				var attributes = {id:btn_id, name:btn_id, bgcolor:'#FFFFFF'};

				swfobject.embedSWF('/assets/swf/image_uploader_front.swf', btn_id, '200', '30', '9.0', '', vars, params, attributes);
			}
		);
	}

	// Otherwise show an error message
	else
	{
		// Hide the image upload fields and show message
		$(".iu_single .iu_button").replaceWith("Flash is needed to upload images.");
	}
}
