var DashboardActionApprove = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (!this.isSingleDocument(collection))
			return false;
		var doc = collection.at(0);
		if (!doc.has('permissions') || !doc.get('permissions').edit)
			return false;
		if (!doc.has('is_draft') || doc.get('is_draft') == 0)
			return false;
		var metadata = doc.get('metadata');
		if (parseInt(metadata.checked_out_to) > 0)
			return false;

		return true;
	},
	render : function(collection) {
		var doc_id;
		doc_id = collection.at(0).get('doc_id');
		return '<a href="#" class="btn btn-secondary btn-sm mr-1 mb-1" rel="tooltip" data-original-title="'+'Approve'+'"><ion-icon name="checkmark-circle-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		var doc = collection.at(0);
		if (confirm(lmsg('documents.misc.doc_approve_confirm'))){
			var url = '/intranet/rest/documents/approve/' + doc.get('doc_id') + '/' + doc.get('version_num') + '/?parent_id=' + doc.get('parent_id');
			$.ajax({
				type: 'post',
				url: url,
				success: function(data){
					cla.showMessage(lmsg('documents.misc.doc_approve_success'), '', 'info');
					list_view.load(docs_list_state.get('folder_id'), 0, list_view.pagesize);
				},
				error: function(jqXHR, message, thrown){
					cla.showMessage(message, '', true);
				}
			});
		}
		return false;
	}
});

var DashboardActionCheckout = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		// Only show the checkout button if exactly one valid document is selected

		if (views_manager.curViewName == 'checkedout')
			return false;
		if (!this.isSingleDocument(collection))
			return false;
		var doc = collection.at(0);
		if (doc.get('doc_type') != 'standard')
			return false;
		if (!doc.has('permissions') || (!doc.get('permissions').edit && !doc.get('permissions').draft)){
			return false;
		}
		if (doc.has('has_later_draft') && doc.get('has_later_draft') == true)
		{
			// a later draft version exists, document cannot be checked out
			return false;
		}

		var metadata = doc.get('metadata');
		if (metadata.checked_out_to > 0)
			return false;
		return true;
	},
	render : function(collection) {
		return '<a href="#" class="btn btn-secondary btn-sm mr-1 mb-1" rel="tooltip" data-original-title="'+lmsg('documents.dashboard_actions.checkout')+'"><ion-icon name="log-out-outline"></ion-icon></a>';
	},
	click : function(collection) {
		var doc_id;
		var parent_id;
		var app_checkout_button = $('#btnDocumentCheckoutApp');

		// Get the document details from the only item in the collection (
		var doc = collection.at(0);
		doc_id = doc.get('doc_id');
		parent_id = doc.get('parent_id');

		hideTooltips();
		$('#documentCheckoutDialog').modal('toggle');
		$('#btnDocumentCheckout').off('click').on('click', jQuery.proxy(function() {
			this.doDocumentCheckout(doc_id, parent_id);
			$('#documentCheckoutDialog').modal('toggle');
			$('#btnDocumentCheckout').off('click');
            app_checkout_button.off('click');
		}, this));
		return false;
	},
	doDocumentCheckout: function(document_id, parent_id) {
		var include_file = !$('#no_download').prop('checked');
		var url = '/intranet/rest/documents/checkout/' + document_id + '/?parent_id=' + parent_id;
		$.ajax({
			type : 'post',
			url : url,
			success : function(data) {
				docsShowMessage(lmsg('documents.dashboard_actions.doc_checked_out'), 'info');
				if (views_manager.curViewName == 'list')
					list_view.load(docs_list_state.get('folder_id'), 0, list_view.pagesize);
				checkedout_view.collection.load();

				if (include_file === true)
				{
					url = '/intranet/documents/view.php?action=download&doc_id=' + document_id + '&parent_id=' + parent_id;
					$("body").append("<iframe src='" + url+ "' style='display: none;' ></iframe>");
				}
			},
			error : function(jqXHR, message, thrown) {
				docsShowMessage(jqXHR.responseText, 'error');
				return false;
			}
		});
		return true;
	}

});

var DashboardActionCheckin = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		// Only show the checkin button if exactly one valid, checked out document is selected
		if (!this.isSingleDocument(collection))
			return false;
		var doc = collection.at(0);
		if (!doc.has('permissions') || !doc.get('permissions').edit)
			return false;
		var metadata = doc.get('metadata');
		if (parseInt(metadata.checked_out_to) !== parseInt(docs_list_preload_data.uid))
			return false;
		return true;
	},
	render : function(collection) {
		var doc_id;
		doc_id = collection.at(0).get('doc_id');
		return '<a href="#" class="btn btn-secondary btn-sm mr-1 mb-1" rel="tooltip" data-original-title="'+lmsg('documents.dashboard_actions.checkin')+'"><ion-icon name="log-in-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		var doc = collection.at(0);
		xajax_show_checkin_dialog(doc.get('doc_id'), doc.get('parent_id'));
		return false;
	}
});

var DashboardActionDownloadZip = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		return this.isDocumentsOnly(collection) && collection.length > 1;
	},
	render : function(collection) {
		return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.download_as_zip')+'"><ion-icon name="cube-outline"></ion-icon></a>';
	},
	click: function(collection) {
		hideTooltips();
		var data = {};
		data.files = [];
		collection.each(function(item, index) {
			var file = {
				'doc_id' : item.get('doc_id'),
				'parent_id' : item.get('parent_id'),
				'version' : item.get('version_num')
			};
			data.files[index] = file;
		});
		var query_str = $.param(data);

        var s2b_obj = {
            href: '/intranet/documents/download.php?' + query_str,
            target: '_self'
        }
        SendByPost(s2b_obj);

		return false;
	}
});

var DashboardActionDownload = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (!this.isSingleDocument(collection))
			return false;
		var doc = collection.at(0);
		if (doc.get('doc_type') != 'standard')
			return false;
		return true;
	},
	render : function(collection) {
		var doc = collection.at(0);
		return '<a href="/intranet/documents/view.php?action=download&doc_id=' + doc.get('doc_id') + '&parent_id=' + doc.get('parent_id') + '" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.download')+'"><ion-icon name="download-outline"></ion-icon></a>';
	}
});

var DashboardActionView = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (!this.isSingleDocument(collection))
			return false;
		var doc = collection.at(0);
		if (doc.get('doc_type') != 'standard')
			return false;
		return true;
	},
	render : function(collection) {
		var doc = collection.at(0);
		return '<a href="/intranet/documents/' + doc.get('parent_id') + '/' + doc.get('doc_id') + '/' + encodeURIComponent(doc.get('pc_title')) + '" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.view_primary_comp')+'"><ion-icon name="eye-outline"></ion-icon></a>';
	}
});

var DashboardActionViewProperties = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		return this.isSingleDocument(collection) || this.isSingleFolder(collection);
	},
	render : function(collection) {
		var doc = collection.at(0);

        if (!doc.get('is_error')) {
            if (this.isSingleDocument(collection))
                return '<a href="/intranet/documents/' + doc.get('parent_id') + '/' + doc.get('doc_id') + '" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="' + lmsg('documents.dashboard_actions.view_properties') + '"><ion-icon name="information-circle-outline"></ion-icon></a>';
            else
                return '<a href="/intranet/documents/folder.php?id=' + doc.get('id') + '" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="' + lmsg('documents.dashboard_actions.view_properties') + '"><ion-icon name="information-circle-outline"></ion-icon></a>';
        }
	}
});

var DashboardActionEditProperties = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (!this.isSingleDocument(collection)/* && !this.isSingleFolder(collection)*/)
			return false;
		var doc = collection.at(0);
		if (!doc.get('permissions').edit_meta)
			return false;
        if (doc.get('doc_type') === 'link')
            return false;
		return true;
	},
	render : function(collection) {
		var doc = collection.at(0);
		if (this.isSingleDocument(collection))
			return '<a href="/intranet/documents/' + doc.get('parent_id') + '/' + doc.get('doc_id') + '#!/properties" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('common.tree_view.edit_properties')+'"><ion-icon name="create-outline"></ion-icon></a>';
		else
			return '<a href="/intranet/documents/folder.php?id=' + doc.get('id') + '" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('common.tree_view.edit_properties')+'"><ion-icon name="create-outline"></ion-icon></a>';
	}
});

var DashboardUtils = {
    decodeHtml: function(html) {
        var txt = document.createElement("textarea");
        txt.innerHTML = html;
        return txt.value;
    }
}

var DashboardActionDelete = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (collection.length == 0)
			return false;
		// if at least one of selected objects can be deleted - allow this action
		if (collection.find(function(item) {
				return item.has('permissions') && item.get('permissions')['delete'];
			}))
			return true;
		return false;
	},
	render : function(collection) {
		return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.delete')+'" ><ion-icon name="trash-outline"></ion-icon></a>';
	},
	showItem : function(item, success, message) {
		var data = {};
		data.type = item.has('type') ? item.get('type') : item.get('obj_type');
		data.id = 'del_' + data.type + '_' + item.getObjId();
		data.mode = 'list';
		data.title = item.get('title');

		data.success = success;
		if (message) {
			data.message = message;
			data.response = true;
		} else
			data.response = false;
		if (data.type === 'document' || data.type === 'document_version') {
			data.icon = item.get('doc_type') === 'link' ? 'icon-new_window' : claIcon(item.get('title'));
		}
		return _.template($('#deleteTemplate').html())(data);
	},
	click : function(collection) {
		hideTooltips();
		$('#delete-files').find('li').remove();
		collection.each(function(item, index) {
			$('#delete-files').append(DashboardActionDelete.prototype.showItem.call(this, item));
		});

		$('#about_to_delete_items').html(lmsg('documents.delete_doc.action_description', collection.length));
		$('#deleteDocumentLabel').html(lmsg('documents.delete_doc.confirm'));

		$('#deleteCancel').show();
		$('#deleteClose').hide();
		$('#deleteDocument').modal('show');
		$('#deleteDocument').on('hidden.bs.modal', function() {
			$('#deleteConfirm').off('click');
			$('#deleteDocument').off('hide');
		});

		$('#deleteConfirm').on('click', jQuery.proxy(function() {
			this.doDelete(collection);
		}, this));
		$('#deleteConfirm').show();
		$('#deleteClose').hide();
		return false;
	},
	doDelete : function(collection) {
		// Keep track of how many files are actively deleting so the close button can be enabled once they are all finished
		var deleteCount = 0;
		var total_deleted = collection.length;

		collection.each(function(item, index) {
			item.set('id', item.getObjId(), {
				silent : true
			});
			deleteCount++;
			// otherwise backbone doesn't call 'delete' method for documents as it thinks object is local
			item.destroy({
				wait : true,
				success : function(model) {
					var item_id = 'del_' + (item.has('type') ? item.get('type') : item.get('obj_type')) + '_' + item.getObjId();
					$('#' + item_id).replaceWith(DashboardActionDelete.prototype.showItem.call(this, model, 'success', lmsg('documents.dashboard_actions.deleted')));
                    trashcan_view.collection.load();
					checkedout_view.collection.load();
					deleteCount--;
					if (deleteCount === 0)
					{
						$('#deleteClose').prop('disabled', false);
						$('#about_to_delete_items').html(lmsg('documents.deleted_doc.action_description', total_deleted));
						$('#deleteDocumentLabel').html(lmsg('documents.delete_doc.deleted'));
					}
					bookmarks.load();
				},
				error : function(model, response) {
                    var responseText = DashboardUtils.decodeHtml(response.responseText)
					var item_id = 'del_' + (item.has('type') ? item.get('type') : item.get('obj_type')) + '_' + item.getObjId();
					$('#' + item_id).replaceWith(DashboardActionDelete.prototype.showItem.call(this, model, 'important', responseText));

					// Catches the situation where the user tries to delete, from the trash can, a version of
					// a document after the parent document has been deleted.
					if (response.status == 404 &&  model.attributes.obj_type == 'document_version') {
						trashcan_view.collection.remove(model); // would be removed after refreshing the page as well.
					}

					if (response.status == 500) {
						cla.showMessage(responseText, '', true);
					}

					deleteCount--;
					total_deleted--;
					if (deleteCount === 0)
					{
						$('#deleteClose').prop('disabled', false);
						$('#about_to_delete_items').html(lmsg('documents.deleted_doc.action_description', total_deleted));
						$('#deleteDocumentLabel').html(lmsg('documents.delete_doc.deleted'));
					}
					bookmarks.load();
				}
			});
		});
		$('#deleteConfirm').hide();
		$('#deleteCancel').hide();
		$('#deleteClose').show();
		$('#deleteClose').prop('disabled', true);
		this.afterDelete();
	},
	afterDelete : function() {
		trashcan_view.collection.load();
	}
});

var DashboardActionAddBookmark = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (collection.length == 0)
			return false;
		// if at least one not bookmarked object exists
		if (collection.find(function(obj) {
				return !obj.get('is_bookmarked');
			}))
			return true;
		return false;
	},
	render : function(collection) {
		return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.details.add_bookmark')+'"><ion-icon name="star-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		collection.each(function(el) {
			bookmarks.addBookmark(el.get('type'), el.getObjId());
		});
		docsShowMessage(lmsg('documents.dashboard_actions.bookmarks_added'), 'success')
		return false;
	}
});

var DashboardActionRemoveBookmark = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (collection.length == 0)
			return false;
		// if at least one bookmarked object exists
		if (collection.find(function(obj) {
				return !obj.get('is_bookmarked');
			}))
			return false;
		return true;
	},
	render : function(collection) {
		return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.remove_from_bookmark')+'"><ion-icon name="star"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		collection.each(function(el) {
			bookmarks.removeBookmark(el.get('type'), el.getObjId());
		});
		docsShowMessage(lmsg('documents.dashboard_actions.bookmars_removed'), 'success')
		return false;
	}
});

var DashboardActionRenew = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (!dms_options['cfg_docs_allow_renew'])
			return false;
		if (collection.length == 1)
		{
			var doc = collection.at(0);
			if (doc.get('obj_type') == 'document' && doc.get('doc_type') != 'standard')
				return false;
			var metadata = doc.get('metadata');
			if (!metadata || metadata.checked_out_to > 0)
				return false;
			return doc.has('permissions') && doc.get('permissions')['edit'];
		} else if (collection.length > 1 && this.isDocumentsOnly(collection))
		{
			if (collection.find(function(doc) {
					return !(doc.has('permissions') && doc.get('permissions')['edit']) || doc.get('doc_type') != 'standard';
				}))
				return false;
			return true;
		}
		return false;
	},
	render : function(collection) {
		if (collection.length == 1)
		{
			var doc = collection.at(0);

			if (doc.get('obj_type') == 'document')
				return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.renew')+'"><ion-icon name="refresh-outline"></ion-icon></a>';
			else
				return '<a href="/intranet/documents/renew_mass.php?fid=' + doc.get('id') + '" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.renew_folder')+'"><ion-icon name="refresh-outline"></ion-icon></a>';
		} else
		{
			return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.renew')+'"><ion-icon name="refresh-outline"></ion-icon></a>';
		}
	},
	click : function(collection) {
		hideTooltips();
		if (collection.length == 1)
		{
			var doc = collection.at(0);
			if (doc.get('obj_type') == 'document')
				xajax_show_checkin_dialog(doc.get('doc_id'), doc.get('parent_id'), 1);
			else
				return true;
			return false;
		} else
		{
			var form = $('<form id="renew_form" action="/intranet/documents/renew_mass.php" method="post"></form>');
			collection.each(function(item, index) {
				var item_id_str = item.get('doc_id') + '_' + item.get('parent_id');
				form.append($('<input type="hidden" name="item_update[]" value="'+item_id_str+'" />'));
			});
			jQuery(document.body).append(form);
			form.submit();
			return false;
		}
	}

});

var DashboardActionPermissions = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
        var model = collection.at(0);

        if (model.get('doc_type') === 'link') {
            return false;
        }
		if(dms_options.cfg_docs_viewers_see_perms == false) {
			if (collection.length > 0) {
				var perms = model.get('permissions');
				if (perms['edit'] || perms['delete'] || perms['edit_meta'] || perms['edit_perms'])
					return true;
				else
					return false;
			}
		}
		if (collection.length == 1)
			return true;
		return false;
	},
	render : function(collection) {
		return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.view_edit_perms')+'"><ion-icon name="key-outline"></ion-icon></a>';
	},
	click : function(collection) {
		console.log('Show folder permissions');
		hideTooltips();
		var doc = collection.at(0);
		perms_dialog_show(doc.getObjId(), doc.get('obj_type'), doc.get('parent_id'), null, function(message) {
			perms_dialog_hide();
			docsShowMessage(message, 'success');
		});
		return false
	}
});

var DashboardActionAddToClipboard = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (collection.length > 0)
			return true;
		return false;
	},
	render : function(collection) {
		return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.copy_to_clipboard')+'"><ion-icon name="reader-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		for(var i = 0; i < collection.length; i++) {
			var doc = collection.at(i);
			if (!clipboard_docs.isSelected(doc))
				clipboard_docs.add(doc);
		}
		// If select all was checked, uncheck
		$('.js-select-all').prop('checked', false);
		collection.reset();
		return false;
	}
});

var ClipboardActionRemove = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (collection.length > 0)
			return true;
		return false;
	},
	render : function(collection) {
		return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.remove_from_clipboard')+'"><ion-icon name="close-circle-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		for(var i = 0; i < collection.length; i++) {
			var doc = collection.at(i);
			if (clipboard_docs.isSelected(doc))
				clipboard_docs.remove(doc, {
					silent : true
				});
		}

		clipboard_docs.trigger('reset');

		return false;
	}
});

var ClipboardActionSelectAll = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (collection.length < clipboard_docs.length)
			return true;
		return false;
	},
	render : function(collection) {
		return '<a href="#" rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" data-original-title="'+lmsg('documents.dashboard_actions.select_all')+'"><ion-icon name="checkmark-circle-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		clipboard_docs.trigger('reset');
		return false;
	}
});

var ClipboardActionCopy = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (docs_list_state.get('folder_id') === 0 && !this.isFoldersOnly(collection))
			return false;
		return (collection.length > 0);
	},
	render : function(collection) {
		return '<a rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" title="'+lmsg('documents.dashboard_actions.copy')+'"><ion-icon name="copy-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		// Set labels on template
		$('#copymoveConfirm').show().text(lmsg('documents.dashboard_actions.confirm'));
		$('#actionTitle').text(lmsg('documents.dashboard_actions.copy_items_title')); // Copy the following items
		$('#copymoveChangeLocation').show();

		// If clear modal window of previous content
		$('#modal-files').find('li').remove();

		$('#modalMove .modal-footer button').show();
		$('#copymoveClose').hide();

		// Get the current folder in docs list and populate a folder picker
		if(docs_list_state.get('folder_id') > 0) {
			$.get('/intranet/rest/documents/folder/' + docs_list_state.get('folder_id') + '/info/', function(response) {
				$('#folderSelect').find('option').prop('value', response.id).text(response.title);
			});
		} else if (docs_list_state.get('folder_id') == 0) {
            $('#folderSelect').find('option').prop('value', 0).text(lmsg('documents.home.title'));
		}
		// List the files to be copied
		collection.each(function(item, index) {
			var data = {};
			data.id = item.get('type') + '_' + item.getObjId();
			data.type = item.get('type');
			data.title = item.get('title');
			data.response = false;
			if (data.type === 'document') {
				data.icon = item.get('doc_type') == 'link' ? 'icon-new_window' : claIcon(data.title);
			}
			var fileListTemplate = _.template($('#fileListTemplate').html())(data);
			$('#modal-files').append(fileListTemplate);
		});

		$('#modalMove').modal('show');
		$('#modalMove').on('hidden.bs.modal', function() {
			$('#copymoveConfirm').off('click');
			$('#modalMove').off('hide');
		});

		// If confirmation is pressed start copying files
		$('#copymoveConfirm').on('click', function() {
			var folderId = parseInt(jQuery('#folderSelect').val());
			collection.each(function(item, index) {
				var data = {};
				data.destination = folderId;
				if (item.get('type') === 'document') {
					data.objects = ['/intranet/rest/documents/document/' + item.getObjId() + '?parent_id=' + item.get('parent_id')]
				}
				if (item.get('type') === 'folder') {
					data.objects = ['/intranet/rest/documents/folder/' + item.getObjId() + '/']
				}
				var jsonData = JSON.stringify(data);
				$.post('/intranet/rest/documents/copy/', jsonData, function(response) {
					response = response[0];
					data.response = true;
					data.message = response.message;
					data.id = item.get('type') + '_' + item.getObjId();
					data.title = item.get('title');
					data.type = item.get('type');
                    if (response.success === true) {
                        data.success = 'success';
                        // Remove the item from the clipboard after successfully copying it.
                        clipboard_docs.remove(item);
                    }
                    else {
                        data.success = 'warning';
                    }
					if (data.type === 'document')
						data.icon = claIcon(data.title);
					var fileListTemplate = _.template($('#fileListTemplate').html())(data);
					$('#' + data.id).replaceWith(fileListTemplate);
				});
			});

			$('#modalMove .modal-footer button').hide();
			$('#copymoveClose').show();
			// Load the current view to see changes to dir
			list_view.load(docs_list_state.get('folder_id'), 0, list_view.pagesize);
		});
	}
});

var ClipboardActionMove = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (docs_list_state.get('folder_id') === 0 && !this.isFoldersOnly(collection))
			return false;
		return (collection.length > 0);
	},
	render : function(collection) {
		return '<a rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" title="'+lmsg('documents.dashboard_actions.move')+'"><ion-icon name="move-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		// Set labels on template
		$('#copymoveConfirm').show().text(lmsg('documents.dashboard_actions.confirm')); // 'Confirm'
		$('#actionTitle').text(lmsg('documents.dashboard_actions.move_items_title')); // 'Move the following items'
		$('#copymoveChangeLocation').show();

		// If clear modal window of previous content
		$('#modal-files').find('li').remove();

		$('#modalMove .modal-footer button').show();
		$('#copymoveClose').hide();

		// Get the current folder in docs list and populate a folder picker
        if(docs_list_state.get('folder_id') > 0) {
            $.get('/intranet/rest/documents/folder/' + docs_list_state.get('folder_id') + '/info/', function(response) {
                $('#folderSelect').find('option').prop('value', response.id).text(response.title);
            });
        } else if (docs_list_state.get('folder_id') == 0) {
            $('#folderSelect').find('option').prop('value', 0).text(lmsg('documents.home.title'));
        }

		// List the files to be moved
		collection.each(function(item, index) {
			var data = {};
			data.id = item.get('type') + '_' + item.getObjId();
			data.type = item.get('type');
			data.title = item.get('title');
			data.response = false;
			if (data.type === 'document') {
				data.icon = item.get('doc_type') == 'link' ? 'icon-new_window' : claIcon(data.title);
			}
			var fileListTemplate = _.template($('#fileListTemplate').html())(data);
			$('#modal-files').append(fileListTemplate);
		});

		$('#modalMove').modal('show');
		$('#modalMove').on('hidden.bs.modal', function() {
			$('#copymoveConfirm').off('click');
			$('#modalMove').off('hide');
		});

		// If confirmation is pressed start moving files
		$('#copymoveConfirm').on('click', function() {
			var folderId = parseInt(jQuery('#folderSelect').val());
			collection.each(function(item, index) {
				var data = {};
				data.destination = folderId;
				if (item.get('type') === 'document') {
					data.objects = ['/intranet/rest/documents/document/' + item.getObjId() + '?parent_id=' + item.get('parent_id')];
				}
				if (item.get('type') === 'folder') {
					data.objects = ['/intranet/rest/documents/folder/' + item.getObjId() + '/'];
				}
				var jsonData = JSON.stringify(data);
				$.post('/intranet/rest/documents/move/', jsonData, function(response) {
					response = response[0];
					data.response = true;
					data.success = response.success === true ? 'success' : 'warning';
					data.message = response.message;
					data.type = item.get('type');
					data.id = item.get('type') + '_' + item.getObjId();
					data.title = item.get('title');
					if (data.type === 'document')
						data.icon = claIcon(data.title);
					var fileListTemplate = _.template($('#fileListTemplate').html())(data);
					$('#' + data.id).replaceWith(fileListTemplate);

                    if (response.success === true) {
                        // Removes the recently moved item from the clipboard.
                        clipboard_docs.remove(item);
                    }
				});
			});
            clipboard_docs.trigger('reset');

			$('#modalMove .modal-footer button').hide();
			$('#copymoveClose').show();
			// Load the current view to see changes to dir
			list_view.load(docs_list_state.get('folder_id'), 0, list_view.pagesize);
		});
	}
});

var ClipboardActionLink = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		if (docs_list_state.get('folder_id') === 0 || !this.isDocumentsOnly(collection))
			return false;
		return (collection.length > 0);
	},
	render : function(collection) {
		return '<a rel="tooltip" class="btn btn-secondary btn-sm mr-1 mb-1" title="'+lmsg('documents.dashboard_actions.create_link')+'"><ion-icon name="link-outline"></ion-icon></a>';
	},
	click : function(collection) {
		hideTooltips();
		// Set labels on template
		$('#copymoveConfirm').show().text(lmsg('documents.dashboard_actions.confirm'));
		$('#actionTitle').text(lmsg('documents.dashboard_actions.create_link_title')); // 'Create a Link'
		$('#copymoveChangeLocation').show();

		// If clear modal window of previous content
		$('#modal-files').find('li').remove();

		$('#modalMove .modal-footer button').show();
		$('#copymoveClose').hide();

		// Get the current folder in docs list and populate a folder picker
        if(docs_list_state.get('folder_id') > 0) {
            $.get('/intranet/rest/documents/folder/' + docs_list_state.get('folder_id') + '/info/', function(response) {
                $('#folderSelect').find('option').prop('value', response.id).text(response.title);
            });
        } else if (docs_list_state.get('folder_id') == 0) {
            $('#folderSelect').find('option').prop('value', 0).text(lmsg('documents.home.title'));
        }
		// List the files to be linked
		collection.each(function(item, index) {
			var data = {};
			data.id = item.get('type') + '_' + item.getObjId();
			data.type = item.get('type');
			data.title = item.get('title');
			data.response = false;
			if (data.type === 'document') {
				data.icon = item.get('is_doc_type_link') ? 'icon-new_window' : claIcon(data.title);
			}
			var fileListTemplate = _.template($('#fileListTemplate').html())(data);
			$('#modal-files').append(fileListTemplate);
		});

		$('#modalMove').modal('show');
		$('#modalMove').on('hidden.bs.modal', function() {
			$('#copymoveConfirm').off('click');
			$('#modalMove').off('hide');
		});

		// If confirmation is pressed start linking files
		$('#copymoveConfirm').on('click', function() {
			var folderId = parseInt(jQuery('#folderSelect').val());
			collection.each(function(item, index) {
				var data = {};
				data.destination = folderId;
				if (item.get('type') === 'document') {
					data.objects = ['/intranet/rest/documents/document/' + item.getObjId() + '?parent_id=' + item.get('parent_id')]
				}
				if (item.get('type') === 'folder') {
					data.objects = ['/intranet/rest/documents/folder/' + item.getObjId() + '/']
				}
				var jsonData = JSON.stringify(data);
				$.post('/intranet/rest/documents/link/', jsonData, function(response) {
					response = response[0];
					data.response = true;
					data.success = response.success === true ? 'success' : 'warning';
					data.message = response.message;
					data.type = item.get('type');
					data.title = item.get('title');
					data.id = item.get('type') + '_' + item.getObjId();
					if (data.type === 'document')
						data.icon = item.get('is_doc_type_link') ? 'icon-new_window' : claIcon(data.title);
					var fileListTemplate = _.template($('#fileListTemplate').html())(data);
					$('#' + data.id).replaceWith(fileListTemplate);
				});
			});
			$('#modalMove .modal-footer button').hide();
			$('#copymoveClose').show();
			// Load the current view to see changes to dir
			list_view.load(docs_list_state.get('folder_id'), 0, list_view.pagesize);
		});
		//clipboard_docs.trigger('reset');
		// return false;
	}
});

var TrashCanActionDelete = new Class({
	Extends : DashboardActionDelete,

	isAllowed : function(collection)// not using parent class as it may start
	// checking permissions
	{
		return (collection.length > 0);
	},
	render : function(collection) {
		return '<a href="#" class="btn btn-secondary btn-sm mr-1 mb-1" rel="tooltip" data-original-title="'+lmsg('documents.dashboard_actions.delete_completely')+'" ><ion-icon name="trash-outline"></ion-icon></a>';
	},
	afterDelete : function() {
		return;
	}
});

var TrashCanActionRestore = new Class({
	Extends : DashboardActionBase,

	isAllowed : function(collection) {
		return collection.length > 0 ? true : false;
	},
	render : function(collection) {
		return '<a href="#" class="btn btn-secondary btn-sm mr-1 mb-1" rel="tooltip" data-original-title="'+lmsg('documents.dashboard_actions.restore')+'" ><ion-icon name="arrow-undo-outline"></ion-icon></a>';
	},
	showItem : function(item, success, message) {
		var data = {};
		data = item.toJSON();
		data.success = success;
		if (message) {
			data.message = message;
			data.response = true;
		} else
			data.response = false;
		if (data.obj_type === 'document') {
			data.icon = claIcon(item.get('title'));
		} else {
			data.icon = 'folder-outline';
		}
		return _.template($('#restoreItemTemplate').html())(data);
	},
	click : function(collection) {
		hideTooltips();
		var $el = $('#modalTrashCanRestore');
		$('ul.inputs-list', $el).find('li').remove();
		collection.each(function(item, index) {
			$('ul.inputs-list', $el).append(TrashCanActionRestore.prototype.showItem.call(this, item));
		});

		$el.modal('show');
		$el.on('hidden.bs.modal', function() {
			$('#restoreConfirm').show();
			$('#restoreClose').hide();
			$('#restoreConfirm').off('click');
			$('#modalTrashCanRestore').off('hide');
		});

		$('#restoreConfirm').on('click', function() {
			collection.each(function(item, index) {
				$.post(item.get('URI') + '/restore').complete(function(response) {
					var success = (response.status >= 200 && response.status < 300);
					var message = success ? lmsg('documents.dashboard_actions.restored') : response.responseText;
					$('#trash_' + item.get('id')).replaceWith(TrashCanActionRestore.prototype.showItem.call(this, item, success, message));
					$('#restoreConfirm').hide();
					$('#restoreClose').show();
                    trashcan_view.collection.load();
				});
			});
			// Reload the trash can content
			trashcan_view.collection.fetch({reset: 1});
			list_view.collection.folder_id = null;
			// to force reloading documents list when shown
		});
		return false;
	}
});
