// 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:  root           - root folder to display; default = /
//           script         - location of the serverside AJAX file to use; default = jqueryFileTree.php
//           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. 
//

function ManageDropDroite(eltSrc,eltDest)
				{
						var newparent = escape(eltSrc.find('a:first').attr('rel').match( /.*\// ));
						var currentDir = $(eltDest).find('a:first').attr('rel');
						if(newparent != currentDir)
						{
							$.ajax({
											type: "POST",
											url: $('[name=Siteaddress]').val()+'/mod/UDA_Files/actions/jqueryFileTreeDeplacer.php',
											data: 'newparent='+newparent + '&dir='+currentDir,
											success: function(msg){
												
												//alert(eltDest.find('a').attr("id"));
												$eltID = eltDest.find('a:first').attr("id");
												var reg = new RegExp("M","g");
												var reg2 = new RegExp("_","g");
												if($eltID.match(reg))
												{
													var tab = $eltID.split(reg);
													var eltSrcId = tab[0]+tab[1];
													$('#'+eltSrcId).remove();
												}
												else
												{
													var tab = $eltID.split(reg2);
													var eltSrcId = tab[0]+'_M'+tab[1];
													$('#'+eltSrcId).remove();
												}
												$(eltDest).remove();
											}
											});
						}
				}


if(jQuery) (function($){
	
	$.extend($.fn, {
		fileTree: function(o, h) {
			// Defaults
			if( !o ) var o = {};
			if( o.root == undefined ) o.root = '/';
			if( o.script == undefined ) o.script = 'jqueryFileTree.php';
			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 = true;
			if( o.loadMessage == undefined ) o.loadMessage = 'Loading...';
			if( o.allowDragDrop == undefined ) o.allowDragDrop = true;
			if( o.owner_guid == undefined ) o.owner_guid = '0';
			
			$(this).each( function() {
				
				function InitTree(c, t) {
					$(c).addClass('wait');
					$(".jqueryFileTree.start").remove();
					$.post(o.script, { dir: t, ref : 'O', owner_guid: o.owner_guid }, function(data) {
						$(c).find('.start').html('');
						$(c).removeClass('wait').append(data);
						if( o.root == t ) $(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
						if(o.allowDragDrop)
						{
							$(c).find('a:first').droppable({hoverClass : 'jqueryFileTreedropHover', drop: function(event,ui){
																																	var eltSrc = $(this).parent() ;
																																	ManageDrop(eltSrc,ui.draggable.parent());
																															  }
																					});
						}
						bindTree(c);
						
						// UDA : PRA : Afficher par défaut la racine
						if ($("#UDA_file_content .UDA_file_toolbar").size() != 0)
						{
							$('#DIR_ROOT').trigger('click');
						}
					});
				}
				
				function showTree(c, t) {
					$(c).addClass('wait');
					$(".jqueryFileTree.start").remove();
					$.post(o.script, { dir: t, ref : 'N', owner_guid: o.owner_guid }, function(data) {
						$(c).find('.start').html('');
						$(c).removeClass('wait').append(data);
						
						if( o.root == t ) $(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
						bindTree(c);
						if(o.allowDragDrop)
						{
							$(c).find('LI').find('a:first').draggable({helper: 'clone'});
							$(c).find('LI').find('a:first').droppable({hoverClass : 'jqueryFileTreedropHover', drop: function(event,ui){
																																			var eltSrc = $(this).parent() ;
																																			ManageDrop(eltSrc,ui.draggable.parent());
																																	  }
																					});	
						}
					});
				}
				
				function ManageDrop(eltSrc,eltDest)
				{
						var newparent = escape(eltSrc.find('a:first').attr('rel').match( /.*\// ));
						var currentDir = $(eltDest).find('a:first').attr('rel');
						if(newparent != currentDir)
						{
							$.ajax({
											type: "POST",
											url: $('[name=Siteaddress]').val()+'/mod/UDA_Files/actions/jqueryFileTreeDeplacer.php',
											data: 'newparent='+newparent + '&dir='+currentDir,
											success: function(msg){
											$(eltDest).remove();
											eltSrc.parent().find('UL').remove(); // cleanup
											
											showTree( eltSrc, escape(eltSrc.find('a:first').attr('rel').match( /.*\// )) );
											
											$eltID = eltDest.find('a:first').attr("id");
											selectNode(eltSrc.find('a:first'));
											eltSrc.parent().removeClass('collapsed').addClass('expanded');
											
											
											}
											});
						}
				}
				
				function selectNode(elt)
				{
					$("#fileExplorer .li_selected").removeClass('li_selected');
					elt.addClass('li_selected');
					
					$.ajax({
								   type: "POST",
								   url: $('[name=Siteaddress]').val()+'/mod/UDA_Files/actions/jqueryFileTreeSelect.php',
								   data: "dir="+escape(elt.attr('rel').match( /.*\// )),
								   success: function(msg){
								   			$("#UDA_file_content").text('');
												$("#UDA_file_content").append(msg);
												 UDA_File_Update_action_links();
								   	}
								   });
					
				}
				
				function bindTree(t) {
					$(t).find('LI A').bind(o.folderEvent, function() {
						selectNode($(this));
						if( $(this).parent().hasClass('directory') ) {
							//if( $(this).parent().hasClass('collapsed') ) {
								// Expand
								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(), escape($(this).attr('rel').match( /.*\// )) );
								$(this).parent().removeClass('collapsed').addClass('expanded');
							//} else {
								// Collapse
								
								//	$(this).parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
								//	$(this).parent().removeClass('expanded').addClass('collapsed');
						//	}
						} else {
							h($(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() { return false; });
				}
				// Loading message
				$(this).html('<ul class="jqueryFileTree start"><li class="wait">' + o.loadMessage + '<li></ul>');
				// Get the initial file list
				InitTree( $(this), escape(o.root) );
			});
		}
	});
	
})(jQuery);
