/* Convert a single file-input element into a 'multiple' input list
 *
 * Usage:
 *   1. Create a file input element (no name)
 *      eg. <input type="file" id="first_file_element">
 *   2. Create a DIV for the output to be written to
 *      eg. <table id="files_list"></table>
 *   3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
 *      eg. var multi_selector = new MultiSelector(document.getElementById('files_list'),3);
 *   4. Add the first element
 *      eg. multi_selector.addElement(document.getElementById('first_file_element','first_file_name'));
 *
 * Credit:
 *   Aaron Kilbey 2007 - Changes for table handling and count vars
 *   Original 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'
 */
 
function MultiSelector(input_name,file_list,max){
  this.file_list = file_list;                                    // Where to write the list
  this.count = 0;                                                // How many elements?
  this.id = 0;                                                   // How many elements?
  this.max = max ? max : -1;                                     // Is there a maximum?
  
  this.addElement = function(element){                           // Add a new file input element
	if(element.tagName == 'INPUT' && element.type == 'file'){    // Make sure it's a file input element
      element.name = input_name + '_' + this.id++;               // Element name -- what number am I?
      element.multi_selector = this;                             // Add reference to this object      
	  element.title = 'Click "Browse..." button to select a file';
	  element.onchange = function(e){                            // What to do when a file is selected
		// var fileRE = /^((\/[^\/]+)+|((?:[a-zA-Z]:)|(?:\\{2}\w[-\w.]*)\$?)\\(?!\.)((?:(?![\/:*?<>"|])(?![.\x20](?:\\|$))[\x20-\x7E])+\\(?!\.))*((?:(?:(?![\\/:*?<>"|])(?![ .]$)[\x20-\x7E])+)\.((?:(?![\\/:*?<>"|])(?![ .]$)[\x20-\x7E]){2,15}))?)$/;
		// if(!fileRE.test(element.value)) return false;         // File path invalid => abort
		                                                         // Removed because FF3 doesn't have full file path here anymore
		var new_element = document.createElement('input');       // New file input
        new_element.type = 'file';
		new_element.title = 'Click "Browse..." button to select a file';
		new_element = this.parentNode.insertBefore(new_element,element);  // Add new file input to form
		new_element.style.width = element.style.width;           
		this.multi_selector.addElement(new_element);
        this.multi_selector.addListRow(this);                    // Update list
		this.style.position = 'absolute';                        // Hide this: we can't use display:none because Safari doesn't like it
		this.style.left = '-10000px';
      };			
	  element.onkeypress = function(e){                          // Prevent all keypresses in field, force hitting Browse button
        return false;
  	  };	  
      if(this.max != -1 && this.count >= this.max)               // If we've reached maximum number, disable input element
        element.disabled = true;
      this.count++;                                              // Increment counter
      this.current_element = element;                            // Most recent element
      
      if(element.form){
	    if(!element.form[input_name+'_count']){                  // New count input
          var new_count = document.createElement('input');
          new_count.type = 'hidden';
          new_count.name = input_name + '_count';
          new_count.id = input_name + '_count';
		  new_count.value = 0;
		  element.form.appendChild(new_count);
        }
        else
          element.form[input_name+'_count'].value++;		
	  }
	} 
	else 
	  alert('Error: not a file input element');                  // This can only be applied to file input elements
  };
  
  this.addListRow = function(element){                           // Add a new row to the list of files
	var new_row = file_list.insertRow(file_list.rows.length);  
	var new_lbl = new_row.insertCell(0);		
	new_lbl.style.width = '100%';
	var new_dlt = new_row.insertCell(1);
	var new_row_button = document.createElement('input');        // Delete button
    new_row_button.type = 'button';
    new_row_button.value = 'X';
    new_row_button.title = 'Remove this file'
    new_row_button.onclick = function(){                         // Delete function
      this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);  // Remove list row
	  element.parentNode.removeChild(element);                   // Remove form element
	  element.multi_selector.current_element.disabled = false;   // Re-enable input element (if it's disabled)
	  element.multi_selector.count--;                            // Decrement counter
      return false;                                              // Appease Safari - without it Safari wants to reload the browser window which nixes your already queued uploads
    };
	new_row_button.style.width = '20px';
    new_lbl.innerHTML = element.value + '&nbsp;&nbsp;';          // Set row label
	new_dlt.appendChild(new_row_button);                         // Add delete button
  };
}
