// Create a folder
$.fn.folderCreate = function() {

		var makeRootFolder = '';
		
		var newNode = 	'<li><div folderNameGlobal="" id="" >' + 
						'<form id="folderFormNew" method="post" target="_blank">' + 
						'<input name="folderNameNew" value="New Folder">' + 
						'</form>' + 
						'</div></li>';

		//first check if fisrt subfolder then add new ul, else append to existing subfolders ul
		if( $('.current', '#Files #nav_secondary').parent().children('ul').length == 0 )
		{

			$('.current', '#Files #nav_secondary').parent().append('<ul class="subfolder"></ul>');
			$('.current', '#Files #nav_secondary').parent().children('ul').append( newNode );

		}   
		else
		{

			folderTreeView.expand( $('.current', '#Files #nav_secondary').parent().children('ul') );
			$('.current', '#Files #nav_secondary').parent().children('ul').append( newNode );

		}

		$("#Files #secondary").scrollTo( $('form#folderFormNew', '#Files #nav_secondary').parent() );

		$('#folderFormNew input', '#Files').bind('blur', function() {
			$(this).parent().submit()
		}).select()

		$('#folderFormNew', '#Files').submit( function() {

			div = $(this).parent()
			//clean RFC reserved chars out and encode
			var folderNameNew = $(this).children('input').attr('value');
			if( folderNameNew.charAt(0) == '#' )
				folderNameNew = folderNameNew.substr(1, (folderNameNew.length-1) )
			folderNameNew = folderNameNew.replace(/\//g,'_')

			// TODO: Remove language string
			if( folderNameNew == 'New Folder' || folderNameNew == '' ) 
			{

				div.parent().remove()                                          
				return false

			}

			var parent = $(this).getActiveFolder()
			
			folderNameNewUrlencodedDouble = urlencode( parent + '/' + folderNameNew );

			if(parent == '/')
				dirTitle = htmlentities(folderNameNew);
			else
				dirTitle = htmlentities(parent + '/' + folderNameNew);
				
			//CONSIDER: use clone instead to transparently cope with html changes to the list
			div.html('<a class="webdavFolder" href="#" title="' + dirTitle + '"><span class="label">' + htmlentities(folderNameNew) + '</span><span class="unread" style="display:none;"><strong>0</strong></span></a>')
			$.php(moduleBaseUrl + '/webdav/foldercreate?folderNameNew=' + folderNameNewUrlencodedDouble + (makeRootFolder?'/makeRootFolder/1':''));

			$("A.webdavFolder", div).folderDndInit();

			// Bind to click the new folder
			$("A.webdavFolder", div).bind('click', function() {
				$(this).folderClickFiles();
			});
			
			
			//setMessageDroppableFolder( div.children('a:first') );
			//only set up treeView on the node if it is the first

			if( $('.current', '#Files #nav_secondary').parent().children('ul').children('li').length == 1)
			{

				folderTreeView.addNode( $('.current', '#Files #nav_secondary').parent() );

			}

			return false;

	   	});
	
		return false;

};

// Delete a specified folder
$.fn.folderDelete = function() {
	
	if(confirm("Are you sure you want to delete the folder " + $(this).getActiveFolder() + "?"))	{
		
		$.getJSON( siteBaseUrl + 'index.php/api/webdav/deletefile/?FolderDelete=1&Directory=' + urlencode($(this).getActiveFolder()), '', function(json) {
		
			if(json) {
				
				if(json.status == 'OK') {
					// Remove the selected folder
					$("DIV.current", "#Files").fadeOut('fast', function() {
						
						$(this).removeTreeNode();
						$("A.webdavFolder:first").parent().addClass('current');
						$("#webdav_files").loadFiles( "/" );
						//$(this).remove();
						
					});
				} else {
					alert('Folder cannot be deleted	');
				}
				
			}
		});
}

}

// Delete the specified file
$.fn.deleteFile = function()
{
	var files = $("FORM[name=listfiles]", "#Files").serializeArray();
	if(files.length == 0) {
		alert('No file selected.');
		return;
	}

	if(confirm("Are you sure you want to delete the selected files?"))	{
		$.getJSON(siteBaseUrl + 'index.php/api/webdav/deletefile/?Directory=' + urlencode($(this).getActiveFolder()), files, function(json) { $(this).fileChange(json) });

	}
}

$.fn.fileChange = function(json)
{

	if(json) {

		// Remove selected files from the view
		if(json.status == 'OK') {
			
			$("INPUT.fileSelect:checked").parent().parent().fadeOut('fast', function() {
				$(this).remove();

				// If no files left, show message
				if($("DIV.activeFile").size() == 0)
					$(this).showNoFiles(jsTranslate('No files in folder'));
				else {
					$("DIV.activeFile:first").viewFile();					
					$("DIV#noMessageDisplay", "DIV#webdav_files").remove();
				}

			});
			
						
		} else {
			alert('Delete failed - Please reload');
		}
		
	}

};

// Search for files in the DOM, matching by the filename
$.fn.searchFiles = function()
{
	var search = $(this).find('INPUT#listfilesSearch').val();

	// Unhighlight any previous selections, please!
	$("DIV.name", "DIV.activeFile").each(function() {
		$(this).html( $(this).text() );			
	});
	
	// Require less then 3 characters to perform the search
	if(search.length < 3) {
		$("DIV.activeFile").show();
		$("DIV#noMessageDisplay", "DIV#webdav_files").remove();
		return false;		
	}
		
	// Hide all other rows
	$("DIV.activeFile").hide();

	var searchMatch = 0;
	// Loop thro each file and see if it matches
	$("DIV.activeFile").each(function() {
		var row = $(this);
		var file = $(this).find("DIV.name").text();
	
		//alert(file + ":" + search);
		var reg = new RegExp( search, 'i' );
	
		if(reg.test(file)) {
			row.show();
			row.highlight(search);
		
			if(searchMatch == 0) {
				row.viewFile();
				$("INPUT[name=id]", row).attr('checked', true);					
			}
			
			searchMatch++;
		
		}
							
	});
	
	// Display the no files DIV if search results null
	if(searchMatch == 0) {
		$(this).showNoFiles(jsTranslate('No search results. Try again.'));
	} else {
		$("DIV#noMessageDisplay", "DIV#webdav_files").remove();
	}
		
	return false;
}

var params = '';	
var files;

// Function called when dragging a file element
$.fn.fileOnDrag = function() {

	var size = $('INPUT.fileSelect:checked', '#Files').size();

	$('INPUT.fileSelect:checked', '#Files').each(function() {

		$(this).parent().parent().css('opacity', 0.6);

	});

	if(!size)
		size = 1;
		
    return $('<div class="files_icon_drag"><div class="files_drag_no"><span class="drag"><strong>' + size + '</strong></span></div></div>');	
};

// Function called on DND mouse end
$.fn.fileDndStop = function() {
	
	$('INPUT.fileSelect:checked', '#Files').each(function() {

		$(this).parent().parent().css('opacity', 1);

	});
	
	
};

// Setup the folder drop
$.fn.folderDndInit = function() {
		
	$(this).droppable({
		accept: ".ui-draggable",
		activeClass: 'droppable-active',
		hoverClass: 'droppable-hover',
		
		over: function() {
			
		},
		
		drop: function(ev, ui) {
			var folderName = $(this).attr('title');
			
			// Can't drop to current folder
			if( $(this).parent().hasClass('current') )
				return
				
			// Move the selected files
			ui.draggable.moveFiles( folderName )
		
		} 
	})
	
}

// Setup the file upload DND support
$.fn.dropzone.uploadStarted = function(fileIndex, file){
	$("DIV#primary_header H1", "#Files").html("Uploading " + file.name + " <span class='progress'>0%</span> <span class='speed'></span>");
	
	var infoDiv = $("<div></div>");
	infoDiv.attr("id", "dropzone-info" + fileIndex);
	infoDiv.html("upload started: " + file.name);
	
	var progressDiv = $("<div></div>");
	progressDiv.css({
		'background-color': 'orange',
		'height': '20px',
		'width': '0%'
	});
	progressDiv.attr("id", "dropzone-speed" + fileIndex);

	var fileDiv = $("<div></div>");
	fileDiv.addClass("dropzone-info");
	fileDiv.css({
		'border' : 'thin solid black',
		'margin' : '5px'
	});
	fileDiv.append(infoDiv);				
	fileDiv.append(progressDiv);				
	
	$("#dropzone-info").after(fileDiv);
};

$.fn.dropzone.uploadFinished = function(fileIndex, file, duration){
	var currentQueue = $("#webdav_files").data('files');
		$("#webdav_files").data('files', currentQueue - 1);
	if( fileIndex == 1 || fileIndex == 0 )
		$("#webdav_files").loadFiles( $("#action_files_upload").getActiveFolder(), file.name );
};

$.fn.dropzone.fileUploadProgressUpdated = function(fileIndex, file, newProgress){
	$("DIV#primary_header H1 SPAN.progress").html(newProgress + "%");
	
};

$.fn.dropzone.fileUploadSpeedUpdated = function(fileIndex, file, KBperSecond){
	$("DIV#primary_header H1 SPAN.speed").html( getReadableSpeedString(KBperSecond) );
};

$.fn.dropzone.newFilesDropped = function(files){
	var fileNum = $("#webdav_files").data('files') + 1;
	$("#webdav_files").data('files', fileNum);
	$(".dropzone-info").remove();
};

// Move the selected files
$.fn.moveFiles = function(destination) {
	
	$.getJSON(siteBaseUrl + 'index.php/api/webdav/rename/?Directory=' + urlencode($(this).getActiveFolder()) + "&NewDirectory=" + urlencode(destination) + "/", $("FORM[name=listfiles]").serializeArray(), function(json) { $(this).fileChange(json) });
	
};

// Rename a specified file
$.fn.renameFile = function(oldFile, newFile) {

	$.getJSON(siteBaseUrl + 'index.php/api/webdav/rename/?Directory=' + urlencode($(this).getActiveFolder()) + "&NewDirectory=" + urlencode($(this).getActiveFolder()) + "&OldFileName=" + urlencode(oldFile) + "&NewFileName=" + urlencode(newFile), '', function(json) { 
	
	});
	
};

// Load the files from a specified folder
$.fn.loadFiles = function(folder, filename) //TODO refactor this into propper scope, currently uverides base jQuery methods here
{

	// Launch the JSON to load selected files
	$.getJSON(siteBaseUrl + 'index.php/api/webdav/list?folder=' + urlencode(folder), params, function(json) 
	{

		if( json ) 
		{

			// First, hide all others
			$("DIV.activeFile").remove();
			files = json;
			var timeDelay = 1000;
			var uniqueFileNodeCounter = 0;
			$.each(files, function(i, n) 
			{
				uniqueFileNodeCounter++
				var item = files[i];

				var file = $("DIV.template", "#webdav_files").clone();
			
				$(file).data('Filename', item.fileName);
				$(file).removeClass('template');
				$(file).addClass('activeFile');
				$(file).addClass('file' + uniqueFileNodeCounter)
			
				$(file).show();

				$("INPUT.fileSelect", file).bind('click', function(e) 
				{
				
					if($("INPUT.fileSelect", file).attr('checked') == true)
						file.addClass('selected');
					else
						file.removeClass('selected');
	
				
					e.stopPropagation();
					return true;
				
				})
			
				$(file).bind('click', function() { $(file).viewFile(); });
			
				$("INPUT[name=id]", file).val(item.fileName);
				$("DIV.name", file).text(item.fileName);
				// Add the name to the checkbox for delete action
				$("INPUT.fileSelect", file).val(item.fileName);
				$("P.size", file).text(jQuery.bytesToHuman(item.size));
				$("DIV.date", file).text(jQuery.timeago(new Date(item.modified*1000)));
				
					iconUrl = siteBaseUrl + "images/icons/file-type-" + item.iconName + "-large.png";
					$("IMG.photoSmall", file).attr('src', iconUrl)
					if(/^image\//.test(item.contentType) && gd_enabled == 1) 
					{
					
						$("IMG.photoSmall", file).addClass(item.iconName);
						//stagger the setting of src (and therefore the browser request load to the server) if image size > 1MB
						thumbUrl = siteBaseUrl + "index.php/mail/webdav/open?Filename=" + urlencode(item.fileName) + "&Thumbnail=1" + "&Directory=" + item.path.slice(0, item.path.lastIndexOf('/'))
						if( item.size > 3000000 )
							timeDelay = timeDelay + 1000
						else if( item.size > 500000 )
							timeDelay = timeDelay + 500
						else
							timeDelay = timeDelay + 100
						setTimeout( '$("IMG.photoSmall", ".file' + uniqueFileNodeCounter + '" ).attr("src", "' + thumbUrl + '");' , timeDelay )
						
					}
					else if (item.iconName != '' ) 
					{
					
						$("IMG.photoSmall", file).addClass(item.iconName);
						//$("IMG.photoSmall", file).attr('src', iconUrl);
						// Center the fileimage more in alignment
						$("IMG.photoSmall", file).css('padding-left', '6px');
						$("IMG.photoSmall", file).css('padding-right', '10px');
					
						//$("IMG.photoSmall", file).attr('height', '25');
						$("IMG.photoSmall", file).removeClass('photoSmall');					
					
					}
					else
					{
						//$("IMG.photoSmall", file).attr('src', "");  //disabled because was causing hits to /
					}
			
				$("DIV#webdav_files").append(file);
		
				// Make the elements draggable
				$(file).draggable(
				{
                    scroll:false,
					containment: 'body',
                    helper: function() { return $(this).fileOnDrag(); },
					stop: function() { $(this).fileDndStop() },
					appendTo:'#draggableFilesContainer',
					cursor:'move',
					distance:10,
					cursorAt:{top:15, left:48},
					revert: "invalid",
					revertDuration: 300
				});
			
				// Open the first file by default
				if(filename == item.fileName) 
				{
						$(file).viewFile();
						$("INPUT.fileSelect", file).attr('checked', true);
				}

				//prevent highlighting on drag
				$(".activeFile", "DIV#webdav_files").each(function() { 
 	  				this.onselectstart = function() { return false; };

 	  			}); 

			});
			
			if(!files[0])	
			{
			
				$(this).showNoFiles(jsTranslate("No files in folder. Upload or Drag and Drop files from the desktop."));
				
			}
			else
			{
				$("DIV#noMessageDisplay", "DIV#webdav_files").remove();
				$("DIV#back_button", "#Files").show();
				
				if(!filename)
					$("DIV.activeFile:first").viewFile();
				
			}

		}

		// Select the input field
		$("INPUT#listfilesSearch").focus();
		
		// Setup the search on the list of files
		$("FORM[name=listfiles]").unbind('submit');
		$("FORM[name=listfiles]").bind('submit', function() { return false; });

		$("FORM[name=listfiles]").unbind('keyup');
		$("FORM[name=listfiles]").bind('keyup', function() { return $(this).searchFiles(); });
					
		
	});
			
};

// View a specified file
$.fn.viewFile = function() {		

	if($(this).data('Filename') == undefined)
		return;
		
	$("DIV.activeFile").removeClass('selected');
	$(this).addClass('selected');
	$("INPUT.fileSelect").attr('checked', false);
	$("INPUT.fileSelect", this).attr('checked', true);

	$("DIV#primary_header H1", "#Files").html( $(this).data('Filename') );
	
	$.php(moduleBaseUrl + '/webdav/view/?Filename=' + urlencode( $(this).data('Filename') ) + '&Directory=' + urlencode( $("#Files").getActiveFolder() ) );

};

// Show a warning if no files or search results
$.fn.showNoFiles = function(message) {
	
	$("DIV#noMessageDisplay", "DIV#webdav_files").remove();
	$("DIV#webdav_files").append('<div style="margin:50px;" id="noMessageDisplay">&nbsp;' + message + '</div>');
	$("DIV#primary_header H1", "#Files").html( $("#Files").getActiveFolder() );
	$("DIV#file_info", "#Files").html("");
	$("DIV#back_button", "#Files").hide();
};

// Find the current highlighted folder
$.fn.getActiveFolder = function() {
	
	return $("DIV.current A", "#Files").attr('title');
	
};

// Return the parent/root directory of the selected folder
$.fn.getParentFolder = function() {
	
	var folder = $('UL#nav_secondary DIV.current', '#Files').parent().attr('title');
	
};

$.fn.folderClickFiles = function()
{

	//hide the delete folder option if Home folder selected
	if( $(this).hasClass('webdavRoot') )
		$('.folder-remove', '#Files').hide()
	else
		$('.folder-remove', '#Files').show()
	$("UL#nav_secondary DIV.current", "#Files").removeClass('current');
	
	$(this).parent().addClass('current');
	$("#webdav_files").loadFiles( $(this).attr('title') );
	$(this).parent().addClass('current');
	
};


$.fn.pushCommentRow = function(Message, photoUrl)
{
	var $comment = $("LI.commentTemplate:first", "#Files").clone();

	$comment.hide();
	$('.message-bubble', $comment).attr('commentid', 'xxxx')
	$("div.white-bg-sms span", $comment ).html( Message );
	$("OL#conversation", "#Files").append($comment);
	$comment.fadeIn('slow');
	
	// Post to the server
	$.php(moduleBaseUrl + '/webdav/comment/', $('FORM#fileComments', '#Files').serializeArray() );
	
	// Reset the field after submitting
	$("TEXTAREA[name=Comment]", "#Files").val('');

	setTimeout(function(){
		$('.cssSummaryRow.selected', '#webdav_files').click()
	}, 2000)
	
};


function editStorageFolderDblClick(clickedObject) 
{

	var a = $(clickedObject)
	var oldName = $('span', a).text();

	if($.inArray(oldName, ['Attachments','Documents','Music','Pictures']) >= 0) {
		return;
	}
	
	// Create a form to specify the new name
	$('<form id="updateGroupForm" method="post" target="_blank"><input name="newGroupName" oldGroupName="' + oldName + '" value="' + oldName + '"></form>').insertAfter(a); 

	// Hide the label text
	a.hide();

	var form = a.parent().children('form');
	var input = form.children('input');

	setTimeout(function(){
		input.focus();
		input.select();		
	},500)


	input.bind('blur', function() 
	{
		$(this).parent().submit()
	})
	
	form.submit( function() 
	{ 
		form = $(this)
		newGroupName = $(this).children('input').attr('value')
		oldGroupName = $(this).children('input').attr('oldGroupName')
		
		// Change the text to the new groupname
		$('span', a).text(newGroupName);
		a.attr('title', newGroupName);
		
		// Show the original div
		a.show();
		// Remove from the DOM the html form for editing
		form.remove();

		if( newGroupName != oldGroupName )
		{
			$.getJSON(siteBaseUrl + 'index.php/api/webdav/rename/?Directory=' + urlencode(oldGroupName) + "&NewDirectory=" + urlencode(newGroupName), '', function(json) { 

			});
		}

		return false
	
	})
	  
}
