//pass in an anchor tag with an href pointing to a photo you want to preview
//$(".multifile").multifile();

(function($) {
		  
$.fn.multifile = function() {
	
	//loop through the items
	this.each(function() {  
		var $this = $(this);

		//create the initial unordered list
		$this.after("<ul class='file_list'></ul>");
		
		var $input = $this.prev("input"); //hidden input field
		var $list = $this.next("ul.file_list");
	
		//add a file when dropdown list item changes
		$this.change(function() {
			var file = $(this).children("option:selected").val(); //selected dropdown file
			//add a file
			if (file) {
				if ($input.val() != "") {
					var arr = $input.val().split("|"); //array made from hidden field value
					$.merge(arr, [file]); //merge the selected file into the array
					$input.val(arr.join("|")); //join the array into a string and insert it into the input value
					update_list(arr);
				} else {
					$input.val(file);
					update_list(file);
				}
			}
		});
	
		var update_list = function(arr) {	
			//empty the ul list
			$list.empty();
			
			//create a string of list items "li"
			var li = "";
			//var btn_delete = "<a href='#' class='file_delete' title='delete'>delete</a>";
			if ($.isArray(arr)) {
				$.each(arr, function(key, val) {
					li += "<li><a href='#' class='file_delete' title='delete'>" + val + "</a></li>";
				});
			} else {
				li = "<li><a href='#' class='file_delete' title='delete'>"+ arr + "</a></li>";
			}
			
			//append the "li" items to the "ul"
			$list.append(li);
			//bind delete function
			file_delete(); 
		};
	
		//delete item from list
		var file_delete = function() {
			$(".file_delete").click(function() {
				var arr = $input.val().split("|"); //array made from hidden field value
				var li = $(this).parent();
				var index = $list.children("li").index(li);
				
				//remove that index from the array
				arr.splice(index, 1);
	
				$input.val(arr.join("|")); //join the array into a string and insert it into the input value
				update_list(arr); //update the list of files
				return false;
			});
		};
		
		//populate the initial list
		var files = $input.val(); //hidden input field value
		if (files) {
			var arr = files.split("|"); //array made from hidden field value
			update_list(arr);
		}
	
	//end $.each loop
	});
	
	// returns the jQuery object to allow for chainability.  
	return this;
}

})(jQuery);