( function( $ ) {
	$.fn.upload = function ( options )
	{
		var settings = $.extend({
			okLabel: "Ok",
			cancelLabel: "Cancel",
			okCallback: false,
			closeCallback: false,
			multiSelect: false,
			singleSelect: false,
			fieldId: false
		}, options);

		var selectionChanged = false;

		var objPointer = null;

		/*
		var start = function(fileObjName) {
			// Create an unique iframe
			var uploadedFile = $('[name='+fileObjName+']');

			$('[name='+fileObjName+']').val('');

			var iframe = $("<iframe width='100' height='100'><body>FUNKYDUNKY <form method='POST' action='cgi-bin/upload.cgi'></form></body></iframe>");

			$(iframe).children('form').append(uploadedFile);

			$(iframe).appendTo('body');

			// $(iframe).child('form').trigger('submit');
		}
		*/

		this.each (function () {
			// Create unique ID of the field
			var uniqueId = Math.floor(Math.random()*1000000);
			$(this).data('uid', uniqueId);

			$(this).after("<div id='current_image_"+uniqueId+"'></div><br><div style='position: relative;'><input type='file' name='upload_file_"+uniqueId+"' id='upload_file_"+uniqueId+"' style='position: absolute; z-index: 20000; opacity: 0; filter: alpha(opacity=0); width: 1px; height: 22px;' onChange='uploader.goUpload(\""+uniqueId+"\");'><div style='position: absolute; top: 0px; left: 0px; z-index: 1; width: 350px;'><img src='/skin1/images/btn_upload.gif' id='btn_upload_"+uniqueId+"'><span id='progress_bar_"+uniqueId+"' style='display: none;'></span></div></div><br>");

			// Set the data of the upload_file to id of the master input hidden field
			$('#upload_file_'+uniqueId).data('master_id', $(this).attr('id'));

			// Show the current image
			uploader.showImage(uniqueId, $(this).val());
		});
		
		return this;
	};
})( jQuery );

var uploader = {
	showImage		: function (uniqueId, imageId) {
		$.get(
			'/uploader.php',
			{
				action		: 'show_image',
				image_id	: imageId
			},
			function (data) {
				$('#current_image_'+uniqueId).html(data);
			},
			'html'
		);
	},
	checkProgress	: function (uniqueId) {
		$.get (
			'/uploader.php',
			{
				sid	: uniqueId
			},
			function (data) {
				// file_id
				// error
				// percentage
				var fileId = data.file_id;
				var error = data.error;
				var percentage = data.percentage;

				if (fileId > 0) {
					// Copy the received fileId into the input hidden text
					var masterId = $('#upload_file_'+uniqueId).data('master_id');
					$('#'+masterId).val(fileId);

					// Stop timer
					window.clearInterval ($('#progress_bar_'+uniqueId).data('interval_id'));

					// File has finished uploading, hide the progress bar
					$('#progress_bar_'+uniqueId).hide();

					// Show the upload button again
					$('#btn_upload_'+uniqueId).show();

					// Update the file display
					uploader.showImage (uniqueId, fileId);
				} else {
					$('#progress_bar_'+uniqueId).progressBar(percentage);
				}
			},
			'json'
		)
	},
	goUpload	: function (uniqueId) {
		// Hide the upload button
		$('#btn_upload_'+uniqueId).hide();

		// Show the progress bar
		$('#progress_bar_'+uniqueId).progressBar(
			0,
			{
				boxImage	: '/skin1/images/progressbar.gif',
				barImage	: '/skin1/images/progressbg_green.gif'
			}
		);
		$('#progress_bar_'+uniqueId).show();

		// Now create a copy of the userfile object and submit it to iframe
		var real = $('#upload_file_'+uniqueId).attr('id', 'real_file');
		var cloned = real.clone(true);

		// real.hide();

		cloned.attr('id', 'upload_file_'+uniqueId);
		cloned.insertAfter(real);

		var form = "<div style='display: none;'><form method='POST' enctype='multipart/form-data' target='iframe_"+uniqueId+"' action='/cgi-bin/upload.cgi?sid="+uniqueId+"' id='form_"+uniqueId+"'></form><iframe id='' name='iframe_"+uniqueId+"'></iframe></div>";

		$('body').append(form);

		// Add the file object
		real.appendTo('form#form_'+uniqueId);

		// Submit this form
		document.getElementById("form_"+uniqueId).submit();

		// Delete this temporary form
		real.remove();
		$('#form_'+uniqueId).remove();

		// Start polling
		var intervalId = window.setInterval(
			function () {
				uploader.checkProgress(uniqueId);
			},
			3000
		);

		// Save this interval# into the progress_bar data field
		$('#progress_bar_'+uniqueId).data('interval_id', intervalId);
	}
}
