/*
	Class for uploading multiple files from a single input field
   
	Concept From the-stickman.com
 */

var upload_object;

/*
	Init requires:
		name (String): Name used for INPUT elements
		list (div element): DIV where new files are appended
		input (file input element): the initial INPUT element
 */
function FileUpload_Init (name,list,input)
{
	upload_object = new FileUpload(name,list);
	upload_object.addInputField(input);
}

function FileUpload (name,list)
{
	//Name for input fields
	this.name = name;
	//List of files to be uploaded
	this.list = list;
	this.count = 0;
	this.id = 0;
	
	var preload_image = new Image();
        preload_image.src = '/securitylabs/images/file_upload_remove.gif'
	
	this.addInputField = function(input)
	{
		if (input.tagName == 'INPUT' && input.type == 'file' )
		{
			input.name = this.name + '[' + this.id++ + ']';
			input.upload_object = this;
			//When the user selects a file, create a new input field and hide this one
			input.onchange = function()
			{
				var new_input = document.createElement( 'input' );
				new_input.type = 'file';
				new_input.size = this.size;
				this.parentNode.insertBefore(new_input,this);
				//Add functions to new file input field
				this.upload_object.addInputField(new_input);
				this.upload_object.addListRow(this);
				// Hide the input element
				this.style.position = 'absolute';
				this.style.left = '-1000px';
			};
			if (this.count >= 5 )
			{
				input.disabled = true;
			};
			this.count++;
			this.current_input = input;
		};
	};

	this.addListRow = function(input)
	{
		var new_row = document.createElement('div');
		new_row.style.margin = '2px';
		var filename = document.createElement('span');
		filename.style.paddingLeft = '5px';
		filename.innerHTML = input.value;
		var delete_button = document.createElement('input');
		delete_button.style.verticalAlign = 'bottom';
		//delete_button.src = '/securitylabs/images/file_upload_remove.gif';
		//delete_button.title = 'Remove';
		delete_button.type = 'button';
		delete_button.value = 'X';
		//Store reference to file upload field
		new_row.input = input;
		// Remove this file from the list, decrement count
		delete_button.onclick= function()
		{
			this.parentNode.input.parentNode.removeChild(this.parentNode.input);
			this.parentNode.parentNode.removeChild(this.parentNode);
			this.parentNode.input.upload_object.count--;
			this.parentNode.input.upload_object.current_input.disabled = false;
			return false;
		};
		new_row.appendChild(delete_button);
		new_row.appendChild(filename);
		this.list.appendChild(new_row);
	};
};