// jQuery File Tree Plugin
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 24 March 2008
//
// Visit http://abeautifulsite.net/notebook.php?article=58 for more information
//
// Usage: $('.fileTreeDemo').fileTree( options, callback )
//
// Options:  libraryId      - library ID to display; default = null
//           script         - location of the serverside AJAX file to use; default = /Library/FileTreeData
//           folderEvent    - event to trigger expand/collapse; default = click
//           expandSpeed    - default = 500 (ms); use -1 for no animation
//           collapseSpeed  - default = 500 (ms); use -1 for no animation
//           expandEasing   - easing function to use on expand (optional)
//           collapseEasing - easing function to use on collapse (optional)
//           multiFolder    - whether or not to limit the browser to one subfolder at a time
//           loadMessage    - Message to display while initial tree loads (can be HTML)
//
// History:
//
// 1.01 - updated to work with foreign characters in directory/file names (12 April 2008)
// 1.00 - released (24 March 2008)
//
// TERMS OF USE
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
if (jQuery) (function ($) {

	$.extend($.fn, {
		fileTree: function (o, fileSelected, folderExpanded, folderCollapsed, folderDeleted, fileDeleted, folderRenamed, fileRenamed) {
			// Defaults
			if (!o) var o = {};
			if (o.libraryId == undefined) o.libraryId = null;
			if (o.script == undefined) o.script = '/Library/FileTreeData';
			if (o.folderEvent == undefined) o.folderEvent = 'click';
			if (o.expandSpeed == undefined) o.expandSpeed = 500;
			if (o.collapseSpeed == undefined) o.collapseSpeed = 500;
			if (o.expandEasing == undefined) o.expandEasing = null;
			if (o.collapseEasing == undefined) o.collapseEasing = null;
			if (o.multiFolder == undefined) o.multiFolder = false;
			if (o.loadMessage == undefined) o.loadMessage = 'Loading...';
			if (o.isAdmin == undefined) o.isAdmin = false;
			if (o.isReversed == undefined) o.isReversed = false;

			function loadHtmlForFolders(data) {
				var dataHtml = '';
				for (i = 0; i < data.Data.Folders.length; i++) {
					var thisFolder = data.Data.Folders[i];
					dataHtml += '<li class="directory collapsed">';
					if (o.isAdmin) {
						dataHtml += '<img class="delete-folder" rel="' + thisFolder.RelativePathEscapedForJs + '" src="../../Scripts/filetree/images/cross.png" width="10" height="10" alt="Delete" title="Delete"/>';
						dataHtml += '<img class="rename-folder" rel="' + thisFolder.RelativePathEscapedForJs + '" src="../../Scripts/filetree/images/textfield_rename.png" alt="Rename" title="Rename"/>';
					}
					dataHtml += '<a href="#" libraryId="' + o.libraryId + '" rel="' + thisFolder.RelativePathEscapedForJs + '">' + thisFolder.FolderName + '</a></li>';
				}
				return dataHtml;
			}

			function loadHtmlForFiles(data) {
				var dataHtml = '';
				for (i = 0; i < data.Data.Files.length; i++) {
					var thisFile = data.Data.Files[i];
					var mp3DownloadLink = '';
					if (thisFile.ExtensionImage == 'mp3') {
						mp3DownloadLink = '<a class="download downloadMp3 dontSupressA" href="/Handlers/Mp3DownloadHandler.ashx?mp3=' + thisFile.RelativePath + '"><img src="/Content/images/16x16/download.png" alt="Download" title="Download"/></a>';
					}
					dataHtml += '<li class="file ext ext_' + thisFile.ExtensionImage + '">';
					if (o.isAdmin) {
						dataHtml += '<img class="delete-file" rel="' + thisFile.RelativePathFromLibraryEscapedForJs + '" src="../../Scripts/filetree/images/cross.png" alt="Delete" title="Delete"/>';
						dataHtml += '<img class="rename-file" rel="' + thisFile.RelativePathFromLibraryEscapedForJs + '" src="../../Scripts/filetree/images/textfield_rename.png" alt="Rename" title="Rename"/>';
					}
					dataHtml += '<a href="#" rel="' + thisFile.RelativePathEscapedForJs + '">' + thisFile.FileName + '</a>' + mp3DownloadLink + '</li>';
				}
				return dataHtml;
			}

			$(this).each(function () {

				function showTree(c, t, p) {
					$(c).addClass('wait');
					$(".jqueryFileTree.start").remove();
					$.ajax({
						type: 'POST',
						url: o.script,
						data: { libraryId: t, relativePath: p },
						success: function (data) {
							$(c).find('.start').html('');
							var dataHtml = '<ul class="jqueryFileTree" style="display:none;">';
							if (o.isReversed) {
								// load files before folders...everything is backwards
								dataHtml += loadHtmlForFiles(data);
								dataHtml += loadHtmlForFolders(data);
							} else {
								dataHtml += loadHtmlForFolders(data);
								dataHtml += loadHtmlForFiles(data);
							}
							//dataHtml += '<li class="directory-add collapsed"><input type="text" /></a></li>';
							dataHtml += '</ul>';
							$(c).removeClass('wait').append(dataHtml);
							if (o.libraryId == null) $(c).find('ul:hidden').show(); else $(c).find('ul:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
							bindTree(c);
						},
						dataType: "json"
					});
				}

				function bindTree(t) {
					$(t).find('li img.delete-folder')
						.mouseover(function () { $(this).addClass('over'); })
						.mouseout(function () { $(this).removeClass('over'); })
						.bind('click', function () { var folderPath = $(this).attr('rel'); if (confirm('Are you sure you want to delete this folder?\n' + folderPath)) folderDeleted(folderPath); });
					$(t).find('li img.rename-folder')
						.mouseover(function () { $(this).addClass('over'); })
						.mouseout(function () { $(this).removeClass('over'); })
						.bind('click', function () { var folderPath = $(this).attr('rel'); folderRenamed(folderPath); });
					$(t).find('li img.delete-file')
						.mouseover(function () { $(this).addClass('over'); })
						.mouseout(function () { $(this).removeClass('over'); })
						.bind('click', function () { var filePath = $(this).attr('rel'); if (confirm('Are you sure you want to delete this file?\n' + filePath)) fileDeleted(filePath); });
					$(t).find('li img.rename-file')
						.mouseover(function () { $(this).addClass('over'); })
						.mouseout(function () { $(this).removeClass('over'); })
						.bind('click', function () { var filePath = $(this).attr('rel'); fileRenamed(filePath); });
					$(t).find('li a').bind(o.folderEvent, function () {
						if ($(this).parent().hasClass('directory')) {
							if ($(this).parent().hasClass('collapsed')) {
								// Expand
								folderExpanded($(this).attr('rel'));
								if (!o.multiFolder) {
									$(this).parent().parent().find('ul').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
									$(this).parent().parent().find('li.directory').removeClass('expanded').addClass('collapsed');
								}
								$(this).parent().find('ul').remove(); // cleanup
								//showTree($(this).parent(), $(this).attr('libraryId'), escape($(this).attr('rel').match(/.*\//)));
								showTree($(this).parent(), $(this).attr('libraryId'), $(this).attr('rel'));
								$(this).parent().removeClass('collapsed').addClass('expanded');
							} else {
								// Collapse
								folderCollapsed($(this).attr('rel'));
								$(this).parent().find('ul').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
								$(this).parent().removeClass('expanded').addClass('collapsed');
							}
						} else if ($(this).hasClass('dontSupressA')) {
							return true;
						} else {
							fileSelected($(this).attr('rel'));
						}
						return false;
					});
					// Prevent A from triggering the # on non-click events
					if (o.folderEvent.toLowerCase != 'click') $(t).find('li a').bind('click', function () {
						if ($(this).hasClass('dontSupressA')) {
							return true;
						} else {
							return false;
						} 
					});
				}
				// Loading message
				$(this).html('<ul class="jqueryFileTree start"><li class="wait">' + o.loadMessage + '</li></ul>');
				// Get the initial file list
				showTree($(this), escape(o.libraryId), '');
			});
		}
	});

})(jQuery);
