//
// Much of this script is taken from:  http://www.quirksmode.org/dom/inputfile.html
// Modifications and comments by Robert Ray - Systek CT | http://www.systekct.com/
//

var W3CDOM = (document.createElement && document.getElementsByTagName);  // Does the browser support the DOM?

setFiles = function () 
{
	if (!W3CDOM) return; // Check DOM support
	
	// Set up the wrapping element with the background button image
	// All styling is in the stylesheet
	var wrapElement = document.createElement('span');
	wrapElement.className = 'fileWrapper';
	wrapElement.appendChild(document.createElement('span'));
	
	var inputs = document.getElementsByTagName('input'); // Find all inputs on the page
	
	for ( var i=0; i < inputs.length; i++ ) // Iterate through all inputs
	{
		if ( inputs[i].type != 'file' ) // Skip all non-file-type inputs
		{
			continue;
		}
		
		inputs[i].className = 'file hidden'; // Change the input's class for transparent styles
		
		var wrapperClone = wrapElement.cloneNode(true); // Make an exact copy of the wrapping element
		var inputClone = inputs[i].cloneNode(true);  // Make an exact copy of the input 
		var label = inputs[i].parentNode;  // Store the label element surrounding the input
		var labelChildren = label.childNodes; // Store all children of the label
		
		// Cycle through all children of the label
		// Must be done in reverse because an element will be removed
		for ( j = labelChildren.length; j >= 0; j-- ) 
		{
			if ( labelChildren[j] ) // Check if the child has any properties
			{
				if ( labelChildren[j].type == 'file' ) // Check if the child is an input of type "file"
				{
					label.removeChild(labelChildren[j]); // Remove the input
				}
			}
		}
		
		wrapperClone.appendChild(inputClone); // Add the input inside the wrapper element
		label.appendChild(wrapperClone); // Add the wrapper element into the label
		
		var innerSpan = wrapperClone.getElementsByTagName('span')[0]; // Store the span created earlier
		var inputValue = inputs[i].value;
		
		innerSpan.innerHTML = inputValue.replace( /\s/g, "&nbsp;" ); // Add the value of the file input to the span after replacing spaces with non-breaking spaces
		
		inputs[i].onchange = inputs[i].onmouseout = function() // When the input value changes, change the innerHTML of the span
		{
			inputValue = this.value 
			innerSpan.innerHTML = inputValue.replace( /\s/g, "&nbsp;" ); // Add the value of the file input to the span after replacing spaces with non-breaking spaces
		}
	}
}