(function($) 
{
	// ajaxUpload plugin
	$.fn.ajaxUpload = function(options) 
	{
		/**
		 * 
		 */
		var defaultOptions = {

			start: function() {},
			complete: function(response, status, xhr, form) {},
			error: function(xhr, status, errorThrown) {}
				
		};	
		
		/**
		 * 
		 */
		var options = $.extend( {}, defaultOptions, options);

		/**
		 * 
		 */
		var element = this;
		
		/**
		 * 
		 */
		var self = this.ajaxUpload;

		/**
		 * 
		 */
		this.ajaxUpload.initialize = function() 
		{
			if ($.meta) 
			{
				options = $.extend({}, options, this.data());
			}
			
			options.start();
			
			// create and append iframe
			var iframe = appendIFrame();	
						
			// submit form
			var form = element.closest('form');
			form.attr('target', iframe.attr('id'));
			form.ajaxSubmit(
				{
					success: options.complete,
					error: options.error
				}
			);
		};
		
		/**
		 * 
		 */
		var appendIFrame = function()
		{
			var id = 'ajax-upload-target';
			
			var iframe = $('iframe#' + id);
			if (iframe.length == 0)
			{
				iframe = $('<iframe />');
				
				iframe.attr('src', options.target);
				iframe.attr('id', id);
				iframe.attr('name', id);
				iframe.hide();
			
				element.after(iframe);
			}
			return iframe;
		}

		// initialize!
		this.ajaxUpload.initialize();
		
		return this;
	}
	
})(jQuery);
