// Multiple file selector by Stickman -- http://www.the-stickman.com 
// with thanks to: [for Safari fixes] Luis Torrefranca -- http://www.law.pitt.edu and Shawn Parker & John Pennypacker -- http://www.fuzzycoconut.com [for duplicate name bug] 'neal'
var brid=1;
function MultiSelector( list_target, max, sufix ){
	this.list_target = list_target;
	this.count = 0;
	this.id = 0;
	if( max ){this.max = max;} 
	else {this.max = -1;};
	this.addElement = function( element, desc ){
		if( element.tagName == 'INPUT' && element.type == 'file' ){
			if(desc)desc.name = "data[Property][desc_"+sufix+'_' + this.id+"]";desc.multi_selector = this;
			element.name = sufix+'_' + this.id++;element.multi_selector = this;
			element.onchange = function(){
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';
				new_element.style.marginTop="5px";
				new_element.style.marginLeft="15px";
				if(desc){
					var new_desc = document.createElement( 'input' );
					new_desc.type = 'text';
					new_desc.style.width="200px";
					new_desc.style.marginLeft="15px";
					var new_br = document.createElement( 'p' );
					new_br.setAttribute('id','br'+brid);
					this.parentNode.insertBefore( new_desc, this );
					this.parentNode.insertBefore( new_br, this );
					brid++;
				}
				this.parentNode.insertBefore( new_element, this );
				
				if(desc) this.multi_selector.addElement( new_element,new_desc);
				else this.multi_selector.addElement( new_element,"");
				if(desc) this.multi_selector.addListRow( this, desc);
				else this.multi_selector.addListRow( this);
				this.style.position = 'absolute';
				this.style.left = '-1000px';
				
				if(desc){
					desc.style.position = 'absolute';
					desc.style.left = '-1000px';
					if((brid-2)>=0){
						var old_br=document.getElementById('br'+(brid-2));
						old_br.style.position = 'absolute';
						old_br.style.left = '-1000px';
					}
				}
				};
			if( this.max != -1 && this.count >= this.max ){
				element.disabled = true;
				};
			this.count++;
			this.current_element = element;
			}
		else {
			alert( 'Error: not a file input element' );
			};
		};
	this.addListRow = function( element, desc ){
		var new_row = document.createElement( 'div' );
		var new_row_button = document.createElement( 'input' );
		new_row_button.type = 'button';new_row_button.value = 'Delete';
		new_row_button.style.marginLeft="10px";
		new_row.element = element;
		new_row_button.onclick= function(){
			this.parentNode.element.parentNode.removeChild( this.parentNode.element );
			this.parentNode.parentNode.removeChild( this.parentNode );
			this.parentNode.element.multi_selector.count--;
			this.parentNode.element.multi_selector.current_element.disabled = false;
			return false;
		};
		if(desc){
			new_row.innerHTML = desc.value+"  -  "+element.value;
			
		}
		else
			new_row.innerHTML = element.value;		
		new_row.appendChild( new_row_button );
		this.list_target.appendChild( new_row );
	};
};
