<?php if (!$is_ajax) { ?>
<?php echo $header; ?><?php echo $column_left; ?>
<div id="content">
	<div class="page-header">
		<div class="container-fluid">
			<h1><?php echo $heading_title; ?></h1>
			<ul class="breadcrumb">
				<?php foreach ($breadcrumbs as $breadcrumb) { ?>
				<li><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a></li>
				<?php } ?>
			</ul>
		</div>
	</div>
	<div class="container-fluid">

<?php } else { ?>

<div class="modal-dialog modal-filemanager">
	<div class="modal-content">

		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
			<h4 class="modal-title"><?php echo $heading_title; ?></h4>
		</div>

		<div class="modal-body">

<?php } ?>



<style>
#folders .panel,
#files .panel { margin: 0; }



#folders .list-group { display: block; margin: 0; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }
#folders .list-group-item { display: block; padding: 0; border: 0; font-size: 14px; }

#folders .list-group-item > .list-group { display: block; max-height: 0; transition: max-height 200ms ease-in-out 0ms; overflow: hidden; }
#folders .list-group-item > .folder-open + .list-group { display: block; max-height: none; transition: max-height 500ms ease-in-out 0ms; }

#folders .list-group-item .list-group-item .folder-item { padding-left: calc(10px + 15px * 1); }
#folders .list-group-item .list-group-item .list-group-item .folder-item { padding-left: calc(10px + 15px * 2); }
#folders .list-group-item .list-group-item .list-group-item .list-group-item .folder-item { padding-left: calc(10px + 15px * 3); }
#folders .list-group-item .list-group-item .list-group-item .list-group-item .list-group-item .folder-item { padding-left: calc(10px + 15px * 4); }
#folders .list-group-item .list-group-item .list-group-item .list-group-item .list-group-item .list-group-item .folder-item { padding-left: calc(10px + 15px * 5); }
#folders .list-group-item .list-group-item .list-group-item .list-group-item .list-group-item .list-group-item .list-group-item .folder-item { padding-left: calc(10px + 15px * 6); }

#folders .list-group-item .fa { display: inline-block; min-width: 12px; vertical-align: middle; }

#folders .list-group-item .folder-item { display: block; position: relative; padding: 8px 10px; border-top: 1px solid rgba(0,0,0,0.1); cursor: pointer; }
#folders .list-group-item:hover > .folder-item { background: rgba(0,0,0,0.1); color: #000; }
#folders .list-group-item .folder-item:hover { background: rgba(30,145,207,0.15); color: #1872a2; }

#folders .list-group-item .folder-item .fa:nth-child(1) { margin: 0 5px 0 0; }
#folders .list-group-item .folder-item.folder-has-child .fa:nth-child(1):before { content: '\f196'; }
#folders .list-group-item .folder-item.folder-has-child.folder-open .fa:nth-child(1):before { content: '\f147'; }

#folders .list-group-item .folder-item .fa:nth-child(2):before { content: '\f07b'; }
#folders .list-group-item .folder-item.folder-open .fa:nth-child(2):before { content: '\f07c'; }

#folders .list-group-item .folder-item.folder-selected { background: #1E91CF; color: #fff; }
#folders .list-group-item .folder-item.folder-selected:hover { background: #1872a2; }
#folders .list-group-item .folder-item.folder-selected:after { content: '\f00c'; position: absolute; top: 9px; right: 10px; font: normal normal normal 14px/1 FontAwesome; }



#files .alert .fa { margin-right: 5px; vertical-align: middle; }

#file-folder { margin: 15px 0; }
#file-folder:before { content: '\f0a0'; display: inline-block; margin: 0 7px 0 0; font: normal normal normal 14px/1 FontAwesome; vertical-align: middle; }

#file-root .file-list { display: flex; flex-flow: row wrap; justify-content: flex-start; align-content: flex-start; align-items: stretch; margin: -5px; }

#file-root .file-item { position: relative; flex: 1 1 20%; min-width: 180px; padding: 5px; }
#file-root .file-item.file-hidden { display: none; }

#file-root .file-item .file-box { position: relative; display: block; margin: 0; padding: 15px; border: 1px solid #ddd; font-weight: normal; text-align: center; overflow: hidden; }
#file-root .file-item:hover .file-box { background: rgba(0,0,0,0.03); border: 1px solid #aaa; }

#file-root .file-item .file-checkbox { position: absolute; top: 20px; left: 20px; cursor: pointer; z-index: 1; }
#file-root .file-item .file-checkbox:checked + .file-box { background: rgba(30,145,207,0.15); border: 1px solid #1E91CF; }

#file-root .file-item .file-buttons { position: absolute; width: 100%; top: 50%; left: 50%; transform: translate3d(-50%, -100px, 0); opacity: 0; transition: all 200ms ease-in-out 0ms; }
#file-root .file-item:hover .file-buttons,
#file-root .file-item .file-checkbox:checked + .file-box .file-buttons { transform: translate3d(-50%, -50%, 0); opacity: 1; }

#file-root .file-item:hover .file-image,
#file-root .file-item .file-checkbox:checked + .file-box .file-image { opacity: 0.5; }

#file-root .file-name,
#file-root .file-size { display: block; }

#file-root .file-name { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #000; }
#file-root .file-size { color: #999; }

#file-root .file-select,
#file-root .file-download,
#file-root .file-copy-url { font: normal normal normal 14px/1 FontAwesome; }

#file-root .file-select:before { content: '\f00c'; }
#file-root .file-download:before { content: '\f019'; }
#file-root .file-copy-url:before { content: '\f0c1'; }
</style>

<script src="//cdnjs.cloudflare.com/ajax/libs/speakingurl/9.0.0/speakingurl.min.js" type="text/javascript"></script>
<script src="view/javascript/jquery/jquery.stringtoslug.min.js" type="text/javascript"></script>
<script src="view/javascript/jquery/jquery.cookie.min.js" type="text/javascript"></script>
<script src="view/javascript/clipboard.min.js" type="text/javascript"></script>

<div class="row">
	<div id="folders" class="col-sm-4 col-lg-3">
		<div class="panel panel-default">
			<div class="panel-heading">
				<h3 class="panel-title">
					<i class="fa fa-folder-open-o"></i>
					Pastas
				</h3>
			</div>

			<div class="panel-body">
				<button type="button" data-toggle="tooltip" title="<?php echo $button_folder_refresh; ?>" id="folder-refresh" class="btn btn-default"><i class="fa fa-refresh"></i></button>
				<button type="button" data-toggle="tooltip" title="<?php echo $button_folder; ?>" id="folder-new" class="btn btn-primary"><i class="fa fa-folder"></i></button>
				<button type="button" data-toggle="tooltip" title="<?php echo $button_folder_delete; ?>" id="folder-delete" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>
			</div>

			<ul id="folder-root" class="list-group"></ul>
		</div>
	</div>

	<div id="files" class="col-sm-8 col-lg-9">
		<div class="panel panel-default">
			<div class="panel-heading">
				<h3 class="panel-title">
					<i class="fa fa-files-o"></i>
					Arquivos
				</h3>
			</div>

			<div class="panel-body">
				<div class="row">
					<div class="col-xs-7 col-sm-6 col-md-7 col-lg-8">
						<button type="button" data-toggle="tooltip" title="<?php echo $button_file_refresh; ?>" id="file-refresh" class="btn btn-default"><i class="fa fa-refresh"></i></button>
						<button type="button" data-toggle="tooltip" title="<?php echo $button_file_upload; ?>" id="file-upload" class="btn btn-primary"><i class="fa fa-upload"></i></button>
						<button type="button" data-toggle="tooltip" title="<?php echo $button_file_delete; ?>" id="file-delete" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>
					</div>
					<div class="col-xs-5 col-sm-6 col-md-5 col-lg-4">
						<input type="text" id="file-search" name="search" value="" placeholder="<?php echo $entry_search; ?>" class="form-control">
					</div>
				</div>

				<div id="file-folder" class="well well-sm"></div>

				<div id="file-root"></div>
			</div>
		</div>
	</div>
</div>



<script type="text/javascript"><!--
$(function(){

	var root_folder_name = 'catalog';

	var files_loading = '<div class="alert alert-info" role="alert"><i class="fa fa-2x fa-refresh fa-spin"></i> <strong>Carregando arquivos, por favor aguarde...</strong></div>';
	var folder_error = '<div class="alert alert-danger" role="alert"><i class="fa fa-2x fa-exclamation-triangle"></i> <strong>Ops... houve um erro no carregamento dos arquivos. Por favor, selecione novamente a pasta desejada.</strong></div>';
	var folder_empty = '<div class="alert alert-warning" role="alert"><i class="fa fa-2x fa-exclamation-circle"></i> <strong>Esta pasta está vazia.</strong></div>';
	var search_empty = '<div class="alert alert-warning" role="alert"><i class="fa fa-2x fa-exclamation-circle"></i> <strong>Nenhum arquivo corresponde a sua busca.</strong></div>';

	var folders_data = <?php echo $folders; ?>;
	var files_data = [];

	var $folders             = $('#folders');
	var $folder_root         = $('#folder-root');
	var $folder_refresh      = $('#folder-refresh');
	var $folder_refresh_icon = $folder_refresh.find('.fa');
	var $folder_new          = $('#folder-new');
	var $folder_delete       = $('#folder-delete');
	var $folder_delete_icon  = $folder_delete.find('.fa');
	var $folder_items        = null;
	var $folder_selected     = null;

	var $files              = $('#files');
	var $file_root          = $('#file-root');
	var $file_refresh       = $('#file-refresh');
	var $file_refresh_icon  = $file_refresh.find('.fa');
	var $file_upload        = $('#file-upload');
	var $file_upload_icon   = $file_upload.find('.fa');
	var $file_delete        = $('#file-delete');
	var $file_delete_icon   = $file_delete.find('.fa');
	var $file_search        = $('#file-search');
	var $file_folder        = $('#file-folder');
	var $file_items         = null;

	// FOLDERS REFRESH
	$folder_refresh.on('click', function(){
		folders_get();
	});

	var folder_block_refresh = false;
	var folder_timeout = null;
	var folder_jqxhr = null;

	function folders_get() {
		// bloqueia consecutivas requisições enquanto houver um requisição em aberto
		if (folder_block_refresh) { return; }

		// ativa bloqueio
		folder_block_refresh = true;

		// show loading
		$folder_refresh_icon.addClass('fa-spin');

		// disable button
		$folder_refresh.prop('disabled', true);

		clearTimeout(folder_timeout);
		if (folder_jqxhr) { folder_jqxhr.abort(); }

		folder_timeout = setTimeout(function(){
			// ajax
			folder_jqxhr = $.ajax({
				url: 'index.php?route=common/filemanager/folders&token=<?php echo $token; ?>',
				method: 'POST',
				dataType: 'json'
			})
			.done(function(data){
				folders_data = data;
				folders_init();
			})
			.always(function(){
				// remove loading
				$folder_refresh_icon.removeClass('fa-spin');

				setTimeout(function(){
					// enable button
					$folder_refresh.prop('disabled', false);

					// desbloqueia novas requisições
					folder_block_refresh = false;
				}, 5000);
			});
		}, 1000);
	}

	// FOLDER CREATE
	$folder_new.on('click', function(e) {
		var path = $folder_selected.data('folder-path');
		path = ('/' + path).replace(/\\/gi, '/');

		// confirmação 1
		var modal_title = '<i class="fa fa-folder-o"></i> Nova pasta!';
		var modal_content = 'Criar nova pasta em: <strong>'+ path +'</strong><br><br><div class="form-group required"><label class="control-label" for="input-folder"><?php echo $entry_folder; ?></label><div><input type="text" name="name" value="" placeholder="<?php echo $entry_folder; ?>" id="input-folder" class="form-control" /></div></div>';
		var modal_buttons = [
			'<button type="button" class="btn btn-danger btn-no" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>',
			'<button type="button" class="btn btn-primary btn-yes"><i class="fa fa-check"></i> Criar pasta</button>'
		];

		var modal = showModal(modal_title, modal_content, modal_buttons);

		var $input_folder = modal.find('#input-folder');

		$input_folder.stringToSlug({
			setEvents: 'blur change',
			getPut: '#input-folder',
			space: '-'
		});

		setTimeout(function(){ $input_folder.focus(); }, 500);

		modal.find('.btn-yes').on('click', function(){
			var name = $input_folder.val();

			$.ajax({
				url: 'index.php?route=common/filemanager/new_folder&token=<?php echo $token; ?>',
				type: 'post',
				dataType: 'json',
				data: 'directory='+ path +'&folder='+ name,
				beforeSend: function() {
					$folder_delete_icon.removeClass('fa-trash-o').addClass('fa-circle-o-notch fa-spin');
					$folder_delete.prop('disabled', true);
				},
				complete: function() {
					$folder_delete_icon.removeClass('fa-circle-o-notch fa-spin').addClass('fa-trash-o');
					$folder_delete.prop('disabled', false);
				},
				success: function(json) {
					if (json['error']) {
						var modal_title = '<i class="fa fa-exclamation-triangle"></i> Erro!';
						var modal_content = json['error'];
						var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
						showModal(modal_title, modal_content, modal_buttons);
					}

					if (json['success']) {
						modal.modal('hide');

						var modal_title = '<i class="fa fa-check"></i> Sucesso!';
						var modal_content = json['success'];
						var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
						showModal(modal_title, modal_content, modal_buttons);

						$folder_refresh.trigger('click');
					}
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
				}
			});
		});
	});

	// FOLDER DELETE
	$folder_delete.on('click', function(e) {
		var path = $folder_selected.data('folder-path');
		path = ('/' + path).replace(/\\/gi, '/');

		// confirmação 1
		var modal_title = '<i class="fa fa-exclamation-triangle"></i> ATENÇÃO!';
		var modal_content = '<div class="text-danger lead" style="text-align:center;"><strong>Você está tentando excluir uma PASTA!</strong></div>';
		var modal_buttons = [
			'<button type="button" class="btn btn-primary btn-no" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>',
			'<button type="button" class="btn btn-danger btn-yes" data-dismiss="modal"><i class="fa fa-check"></i> Ok, continuar!</button>'
		];

		var modal = showModal(modal_title, modal_content, modal_buttons);

		modal.find('.btn-yes').on('click', function(){
			// confirmação 2
			var modal_title = '<i class="fa fa-exclamation-triangle"></i> ATENÇÃO!';
			var modal_content = '<div class="text-danger lead" style="text-align:center;"><strong>TODOS os arquivos e subpastas contidos nesta pasta também serão PERMANENTEMENTE EXCLUÍDOS!<br><br>Este procedimento NÃO PODERÁ SER DESFEITO!</strong></div>';
			var modal_buttons = [
				'<button type="button" class="btn btn-danger btn-yes" data-dismiss="modal"><i class="fa fa-check"></i> Ok, estou ciente!</button>',
				'<button type="button" class="btn btn-primary btn-no" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>'
			];

			var modal = showModal(modal_title, modal_content, modal_buttons);

			modal.find('.btn-yes').on('click', function(){
				// confirmação 3
				var modal_title = '<i class="fa fa-exclamation-triangle"></i> Excluir pasta?';
				var modal_content = '<strong class="text-danger">Aviso:</strong> Você está tentando excluir a pasta <strong>"'+ path +'"</strong>.<br><br><strong class="text-danger">Todos os arquivos e subpastas contidos nela também serão PERMANENTEMENTE excluídos!<br><br>Este procedimento NÃO poderá ser desfeito!</strong><br><br><strong>Tem certeza que deseja continuar?</strong>';
				var modal_buttons = [
					'<button type="button" class="btn btn-primary btn-no" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>',
					'<button type="button" class="btn btn-danger btn-yes" data-dismiss="modal"><i class="fa fa-check"></i> Sim, excluir pasta!</button>'
				];

				var modal = showModal(modal_title, modal_content, modal_buttons);

				modal.find('.btn-yes').on('click', function(){
					$.ajax({
						url: 'index.php?route=common/filemanager/delete_folder&token=<?php echo $token; ?>',
						type: 'post',
						dataType: 'json',
						data: 'directory='+ path,
						beforeSend: function() {
							$folder_delete_icon.removeClass('fa-trash-o').addClass('fa-circle-o-notch fa-spin');
							$folder_delete.prop('disabled', true);
						},
						complete: function() {
							$folder_delete_icon.removeClass('fa-circle-o-notch fa-spin').addClass('fa-trash-o');
							$folder_delete.prop('disabled', false);
						},
						success: function(json) {
							if (json['error']) {
								var modal_title = '<i class="fa fa-exclamation-triangle"></i> Erro!';
								var modal_content = json['error'];
								var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
								showModal(modal_title, modal_content, modal_buttons);
							}

							if (json['success']) {
								var modal_title = '<i class="fa fa-check"></i> Sucesso!';
								var modal_content = json['success'];
								var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
								showModal(modal_title, modal_content, modal_buttons);

								$folder_refresh.trigger('click');
							}
						},
						error: function(xhr, ajaxOptions, thrownError) {
							alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
						}
					});
				});
				// confirmação 3 - fim
			});
			// confirmação 2 - fim
		});
		// confirmação 1 - fim
	});

	// FOLDER SELECT
	$folders.on('click', '.folder-item', function(){
		folders_select( $(this) );
	});

	function folders_select($folder, prevent_open) {
		if (!$folder.hasClass('folder-selected')) {
			// remove classe selected de todas as pastas
			$folder_items.removeClass('folder-selected');

			// adiciona classe selected na pasta atual
			$folder.addClass('folder-selected');
		}

		// grava cookie com id da pasta atual para recarregar pre-selecionada
		$.cookie('folder-selected', $folder.data('folder-id'));

		$folder_selected = $folder;

		// busca os arquivos da pasta
		files_get();

		if (!prevent_open) {
			folders_open_close($folder);
		}
	}

	// FOLDER OPEN/CLOSE
	function folders_open_close($folder) {
		$folder.filter('.folder-has-child').toggleClass('folder-open');
		folders_save_open();
	}

	function folders_open($folder) {
		$folder.filter('.folder-has-child').addClass('folder-open');
		folders_save_open();
	}

	function folders_close($folder) {
		$folder.filter('.folder-has-child').removeClass('folder-open');
		folders_save_open();
	}

	function folders_save_open() {
		// grava cookie com os ids das pastas abertas para recarregar abertas
		var open = [];

		$folder_items.filter('.folder-open').each(function(){
			open.push( this.getAttribute('data-folder-id') );
		});

		$.cookie('folder-open', open.join(','));
	}

	// FOLDERS BUILD
	// função recursiva para gerar a estrutura das pastas
	function folders_build(folder) {
		var html = '';

		// valida array de pastas
		if (folder && folder.length) {
			// percorre array de pastas
			for (var i = 0, len = folder.length; i < len; i++) {
				var f = folder[i];
				var classes = '';
				var children = '';

				if (f['nodes'] && f['nodes'].length > 0) {
					// recursivamente busca as subpastas
					children = folders_build(f['nodes']);
					if (children != '') {
						children = '<ul class="list-group">'+ children +'</ul>';
						classes += ' folder-has-child';
					}
				}

				// a pasta raiz deve vir aberta e pré-selecionada
				if (f['path'] == root_folder_name) {
					classes += ' folder-open folder-selected';
				}

				html += '<li class="list-group-item"><span class="folder-item'+ classes +'" data-folder-id="'+ f['id'] +'" data-folder-path="'+ f['path'] +'"><i class="fa"></i><i class="fa"></i> '+ f['text'] +'</span>'+ children +'</li>';
			}
		}

		return html;
	}

	// recupera as pastas abertas na última sessão e salvas em cookie
	function folders_restore_open() {
		// pega informações do cookie
		var open = $.cookie('folder-open');

		// valida informações do cookie
		if (!open) {
			open = '';
		}

		if (open != '') {
			open = open.split(',');

			$folder_items.removeClass('folder-open');
			$folder_items.filter('[data-folder-path="'+ root_folder_name +'"]').addClass('folder-open');

			$.each(open, function(index, value){
				$folder_items.filter('[data-folder-id="'+ value +'"]').addClass('folder-open');
			});
		}
	}

	// recupera a última pasta selecionada e salva em cookie
	function folders_restore_selected() {
		var selected = $.cookie('folder-selected');

		if (!selected) {
			selected = root_folder_name;
		}

		if (selected != '') {
			selected = $folder_items.filter('[data-folder-id="'+ selected +'"]');

			if (!selected || selected.length == 0) {
				selected = $folder_items.filter('[data-folder-path="'+ root_folder_name +'"]');
			}

			folders_select(selected, true);
		}
	}

	// monta estrutura de pastas
	function folders_init() {
		var html = folders_build(folders_data);
		$folder_root.html(html);

		$folder_items = $folders.find('.folder-item');

		folders_restore_open();
		folders_restore_selected();
	}

	folders_init();

	// FILES REFRESH
	$file_refresh.on('click', function(){
		files_get();
	});

	var files_block_refresh = false;
	var files_last_path = '';
	var files_timeout = null;
	var files_jqxhr = null;

	function files_get() {
		var path = $folder_selected.data('folder-path');

		// bloqueia consecutivas requisições enquanto houver um requisição em aberto
		if (files_last_path == path && files_block_refresh) { return; }

		// atualiza path no painel de arquivos
		$file_folder.html(('/' + path).replace(/\\/gi, '/'));

		// ativa bloqueio
		files_block_refresh = true;
		files_last_path = path;

		// show loading
		$file_root.html(files_loading);
		$file_refresh_icon.addClass('fa-spin');

		// disable button
		$file_refresh.prop('disabled', true);

		clearTimeout(files_timeout);
		if (files_jqxhr) { files_jqxhr.abort(); }

		files_timeout = setTimeout(function(){
			// ajax
			files_jqxhr = $.ajax({
				url: 'index.php?route=common/filemanager/files&token=<?php echo $token; ?>',
				method: 'POST',
				dataType: 'json',
				data: 'directory=' + path
			})
			.fail(function(){
				$file_root.html(folder_error);
			})
			.done(function(data){
				if (data['error']) {
					$file_root.html(folder_error);
				} else if (data['empty']) {
					$file_root.html(folder_empty);
				} else {
					if (!data.length) {
						$file_root.html(folder_empty);
					} else {
						files_data = data;
						files_init();
					}
				}
			})
			.always(function(){
				// remove loading
				$file_refresh_icon.removeClass('fa-spin');

				setTimeout(function(){
					// enable button
					$file_refresh.prop('disabled', false);

					// desbloqueia novas requisições
					files_block_refresh = false;
				}, 5000);
			});
		}, 1000);
	}

	// FILES BUILD
	// monta estrutura dos arquivos
	function files_init() {
		var html = '<div class="file-list">';

		var files_total = files_data.length;

		for (var i = 0; i < files_total; i++) {
			var file = files_data[i];

			html += '<div class="file-item" data-file-path="' + file['file'] + '" title="' + file['name'] + '\n[' + file['size'] + ']">';
			html += '	<input id="file-checkbox-'+ i +'" type="checkbox" name="path[]" value="' + file['file'] + '" class="file-checkbox">';
			html += '	<label for="file-checkbox-'+ i +'" class="file-box">';
			html += '		<img class="file-image" src="' + file['thumb'] + '" alt="' + file['name'] + ' [' + file['size'] + '">';
			html += '		<span class="file-name">'+ file['name'] +'</span>';
			html += '		<span class="file-size">['+ file['size'] +']</span>';
			html += '		<span class="file-buttons">';
			<?php if ($type != '') { ?>
			html += '			<a class="btn btn-primary file-select" data-toggle="tooltip" title="<?php echo $button_file_select; ?>" href="'+ file['href'] +'"></a>';
			<?php } ?>
			html += '			<a class="btn btn-default file-download" data-toggle="tooltip" title="<?php echo $button_file_download; ?>" href="index.php?route=common/filemanager/download&token=<?php echo $token; ?>&file='+ file['file'] +'" target="_blank"></a>';
			html += '			<a class="btn btn-default file-copy-url" data-toggle="tooltip" title="<?php echo $button_file_copy_url; ?>" href="'+ file['href'] +'" data-clipboard-text="'+ file['href'] +'"></a>';
			html += '		</span>';
			html += '	</label>';
			html += '</div>';
		}

		html += '<div class="file-item filler"></div>';
		html += '<div class="file-item filler"></div>';
		html += '<div class="file-item filler"></div>';
		html += '<div class="file-item filler"></div>';
		html += '<div class="file-item filler"></div>';
		html += '</div>';

		$file_root.html(html);

		$file_items = $files.find('.file-item');
	}

	// FILES SEARCH
	var search_last = '';
	var search_timeout = null;

	$file_search.on('keyup', function(){
		// aplica um delay para não disparar a busca
		// caso várias teclas sejam digitadas em sequência
		clearTimeout(search_timeout);
		search_timeout = setTimeout(file_search, 250);
	});

	// faz a busca entre os arquivos da pasta
	function file_search() {
		var search = $.trim( $file_search.val() );
		var search_rg = new RegExp(search, 'i');

		// somente permite a busca caso seja um termo diferente do anterior
		if (search_last == search) {
			return;
		}

		search_last = search;

		// remove qualquer possível aviso inserido anteriormente
		$file_root.find('.alert').remove();

		// busca os itens e filtra um por um
		$file_root.find('.file-item').not('.filler').each(function(){
			var $this = $(this);
			var filename = $.trim( $this.find('.file-name').html() );

			if (filename.search(search_rg) == -1) {
				$this.addClass('file-hidden');
			} else {
				$this.removeClass('file-hidden');
			}
		});

		// caso não sobre nenhum arquivo depois de aplicado o filtro
		// exibe aviso que a busca não retornou resultados
		if ($file_root.find('.file-item').not('.filler').not('.file-hidden').length == 0) {
			$file_root.append(search_empty);
		}
	}

	// FILE SELECT
	<?php if ($type == 'editor') { ?>
		// grava range e seleção logo que carregar o gerenciador
		// para não perder a seleção original no editor
		var range, sel = document.getSelection();

		if (sel.rangeCount) {
			range = sel.getRangeAt(0);
		}
	<?php } ?>

	// seleciona o arquivo
	$files.on('click', '.file-select', function(e){
		e.preventDefault();

		var $this = $(this);
		var $parent = $this.parents('.file-item');

		<?php if ($thumb) { ?>
			$('#<?php echo $thumb; ?>').find('img').attr('src', $parent.find('.file-image').attr('src'));
		<?php } ?>

		<?php if ($target) { ?>
			$('#<?php echo $target; ?>').attr('value', $parent.data('file-path'));
		<?php } ?>

		<?php if ($type == 'editor') { ?>
			if (range) {
				var img = document.createElement('img');
				img.src = $(this).attr('href');

				range.insertNode(img);
			}
		<?php } ?>

		$('#modal-image').modal('hide');
	});

	// FILE COPY URL
	var clipboard = new Clipboard('.file-copy-url');

	clipboard.on('success', function(e) {
		var modal_title = '<i class="fa fa-check"></i> Sucesso!';
		var modal_content = 'URL copiada com sucesso!<br><br>'+ e.text;
		var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
		showModal(modal_title, modal_content, modal_buttons);
	});

	$files.on('click', '.file-copy-url', function(e){
		e.preventDefault();
	});

	// FILES UPLOAD
	var upload_timer = null;

	$file_upload.on('click', function() {
		$('#form-upload').remove();
		$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" id="form-upload-input" name="files[]" multiple="multiple" value="" /></form>');
		$('#form-upload-input').trigger('click');

		var directory = $folders.find('.folder-selected').data('folder-path');

		clearInterval(upload_timer);
		upload_timer = setInterval(function() {
			if ($('#form-upload-input').val() != '') {
				clearInterval(upload_timer);

				$.ajax({
					url: 'index.php?route=common/filemanager/upload&token=<?php echo $token; ?>&directory=' + directory,
					type: 'post',
					dataType: 'json',
					data: new FormData($('#form-upload')[0]),
					cache: false,
					contentType: false,
					processData: false,
					beforeSend: function() {
						$file_upload_icon.removeClass('fa-upload').addClass('fa-circle-o-notch fa-spin');
						$file_upload.prop('disabled', true);
					},
					complete: function() {
						$file_upload_icon.removeClass('fa-circle-o-notch fa-spin').addClass('fa-upload');
						$file_upload.prop('disabled', false);
					},
					success: function(json) {
						if (json['error']) {
							var modal_title = '<i class="fa fa-exclamation-triangle"></i> Erro!';
							var modal_content = json['error'];
							var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
							showModal(modal_title, modal_content, modal_buttons);
						}

						if (json['success']) {
							var modal_title = '<i class="fa fa-check"></i> Sucesso!';
							var modal_content = json['success'];
							var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
							showModal(modal_title, modal_content, modal_buttons);

							$file_refresh.trigger('click');
						}
					},
					error: function(xhr, ajaxOptions, thrownError) {
						alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
					}
				});
			}
		}, 500);
	});

	// FILES DELETE
	$file_delete.on('click', function(e) {
		var files_checked = $files.find('.file-checkbox:checked');
		var total_files = files_checked.length;

		if (total_files == 0) {
			// aviso
			var modal_title = '<i class="fa fa-exclamation-triangle"></i> Atenção!';
			var modal_content = 'Por favor, selecione pelo menos um arquivo para exclusão.';
			var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
			showModal(modal_title, modal_content, modal_buttons);

			return false;
		}

		// confirmação
		var modal_title = '<i class="fa fa-exclamation-triangle"></i> Excluir '+ (total_files > 1 ? 'arquivos' : 'arquivo') +'?';

		var modal_content = '<strong class="text-danger">Aviso:</strong> Você está tentando excluir '+ (total_files > 1 ? 'os seguintes arquivos' : 'o seguinte arquivo') +':<br>';
		files_checked.each(function(){
			modal_content += '- <strong>'+ $(this).parent().find('.file-name').html() +'</strong><br>';
		});
		modal_content += '<br><strong class="text-danger">Este é um procedimento PERMANENTE e NÃO PODERÁ SER DESFEITO!</strong><br><br><strong>Tem certeza que deseja continuar?</strong>';

		var modal_buttons = [
			'<button type="button" class="btn btn-primary btn-no" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>',
			'<button type="button" class="btn btn-danger btn-yes" data-dismiss="modal"><i class="fa fa-check"></i> Sim, excluir '+ (total_files > 1 ? 'arquivos' : 'arquivo') +'!</button>'
		];

		var modal = showModal(modal_title, modal_content, modal_buttons);

		modal.find('.btn-yes').on('click', function(){
			$.ajax({
				url: 'index.php?route=common/filemanager/delete&token=<?php echo $token; ?>',
				type: 'post',
				dataType: 'json',
				data: files_checked,
				beforeSend: function() {
					$file_delete_icon.removeClass('fa-trash-o').addClass('fa-circle-o-notch fa-spin');
					$file_delete.prop('disabled', true);
				},
				complete: function() {
					$file_delete_icon.removeClass('fa-circle-o-notch fa-spin').addClass('fa-trash-o');
					$file_delete.prop('disabled', false);
				},
				success: function(json) {
					if (json['error']) {
						var modal_title = '<i class="fa fa-exclamation-triangle"></i> Erro!';
						var modal_content = json['error'];
						var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
						showModal(modal_title, modal_content, modal_buttons);
					}

					if (json['success']) {
						var modal_title = '<i class="fa fa-check"></i> Sucesso!';
						var modal_content = json['success'];
						var modal_buttons = ['<button type="button" class="btn btn-primary btn-close" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>'];
						showModal(modal_title, modal_content, modal_buttons);

						$file_refresh.trigger('click');
					}
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
				}
			});
		});
	});

	// HELPER MODAL
	function showModal(title, content, buttons) {
		var modal = $('<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="Aviso"><div class="modal-dialog xmodal-sm"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">'+ title +'</h4></div><div class="modal-body">'+ content +'</div><div class="modal-footer">'+ buttons.join('') +'</div></div></div></div>');

		modal.on('hidden.bs.modal', function(){
			modal.remove();
		});

		return modal.modal('show');
	}

});
//--></script>



<?php if (!$is_ajax) { ?>

	</div>
</div>
<?php echo $footer; ?>

<?php } else { ?>

		</div>
	</div>
</div>

<?php } ?>