Ext.define("Ext.ux.file.view.Manager", {

	extend: "Ext.panel.Panel",

	alias: "widget.filemanager",

	treeDiskFolders: undefined,

	pnlWest: undefined,
	pnlCenter: undefined,
	border: false,
	grdStore: undefined,
	i_grid_memory: undefined,

	delayedTask: undefined,

	i_dropzone: undefined,

	toolbar: undefined,

	layout: "fit",

	sharedTreeStore: undefined,

	initComponent: function() {

		var i_self = this;
		i_self.dmdName = i_self.dmd.split("/").pop().split(".").shift();
		i_self.callParent();

		i_self.pnlContent = Ext.widget("panel", {
			layout: "border"
		});

		i_self.pnlWest = Ext.widget("panel", {
			width: 200,
			minWidth: 200,
			title: ip2.i18n({
				da: "Bibiliotek",
				en: "Library"
			}),
			layout: "fit",
			region: "west",
			border: false,
			split: true,
			collapsible: true,
			items: [
				i_self.createTreeDisk()
			]
		});

		i_self.pnlCenter = Ext.widget("panel", {
			flex: 1,
			title: ip2.i18n({
				da: "Filer",
				en: "Files"
			}),
			layout: "fit",
			region: "center",
			border: false,
			split: true
		});

		i_self.pnlCenter.add(i_self.createGrid());

		i_self.pnlContent.add(i_self.pnlWest);
		i_self.pnlContent.add(i_self.pnlCenter);

		i_self.add(i_self.pnlContent);

		return i_self;
	},

	createDropZone: function(grid) {
		var i_self = this;

		i_self.i_dropzone = Ext.widget("container", {
			layout: "fit",
			renderTo: Ext.getBody(),
			style: {
				"background-color": "white",
				"position": "absolute",
				"top": "0px",
				"left": "0px",
				"right": "0px",
				"bottom": "0px",
				"display": "none",
				"opacity": "0.9"
			},
			items: [i_self.createPortlet()],
			listeners: {
				afterrender: function(item) {
					var i_dropzone = item;
					i_dropzone.dragging = 0;
					document.body.addEventListener("dragenter", function(o_event) {
						if (!i_dropzone.dragging || i_dropzone.dragging === 0) {
							var i_el = i_dropzone.getEl();
							if (i_el.dom) {
								i_el.setStyle("display", "inline");
								i_el.setStyle("z-index", "1");
								var size = item.getSize();
								i_self.portlet.setSize(size.width, size.height);

								var i_portlet = i_self.portlet;

								var f_layout = i_portlet.doLayout || i_portlet.updateLayout;

								f_layout.call(i_portlet);
							}
						}
						i_dropzone.dragging++;
					});

					document.body.addEventListener("dragleave", function(o_event) {
						i_dropzone.dragging--;
						var i_el = i_dropzone.getEl();
						if (i_el.dom && i_dropzone.dragging === 0) {
							i_el.setStyle("display", "none");
							i_el.setStyle("z-index", "0");
						}
					});

					document.body.addEventListener("drop", function(o_event) {
						var i_el = i_dropzone.getEl();
						if (i_el.dom) {
							i_el.setStyle("display", "none");
						}
						i_dropzone.dragging = 0;
					});
				}
			}
		});

		return i_self.i_dropzone;
	},

	createPortlet: function() {
		var i_self = this;
		var portlet = Ext.widget("panel", {
			border: 0,
			layout: {
				type: "vbox",
				padding: 5,
				align: "stretch"

			},
			style: {
				"position": "absolute",
				"padding": "5px",
				"top": "0px",
				"left": "0px",
				"right": "0px",
				"bottom": "0px",
				"font-size": "5px"
			},
			items: []
		});
		i_self.portlet = portlet;
		return portlet;
	},

	createColumns: function() {
		var i_self = this;
		var columns = [];

		if (i_self.itemCount % 2 === 0) {
			i_self.itemCount = Math.ceil(i_self.itemCount / 6);
		}
		else {
			i_self.itemCount = Math.ceil(i_self.itemCount / 5);
		}

		for (var i = 0; i < i_self.itemCount; i++) {
			var column = {
				xtype: "container",
				flex: 1,
				border: 0,
				layout: {
					type: "hbox",
					padding: 5,
					align: "stretch"
				},
				items: []
			};
			columns.push(column);
		}

		return columns;
	},

	addItems: function() {
		var i_self = this;
		i_self.index = 0;
		var columns = i_self.portlet.items.items;
		i_self.portlet.tmp.forEach(function(item) {
			columns[i_self.index].add(item);
			i_self.index++;
			if (i_self.index == columns.length) {
				i_self.index = 0;
			}
		});
	},

	createPortletItem: function(s_path, text) {
		var i_self = this;
		var item = {
			xtype: "container",
			border: 0,
			draggable: false,
			closable: false,
			collapsible: false,
			layout: "fit",
			flex: 1,
			items: [
				{
					xtype: "gallerydropbox",
					flex: 1,
					dropText: [
					text,
					"</br><small><small>",
						ip2.i18n({
							da: "Drop for at tilføje filer",
							en: "Drop to add files"
						}),
					"</small></small>"
					].join(""),
					path: s_path,
					extensions: Ext.ux.file.util.Handler.extensions,
					maxItems: -1,
					style: {
						"position": "absolute",
						"padding": "5px",
						"top": "0px",
						"left": "0px",
						"right": "0px",
						"bottom": "0px",
						"font-size": "25px"
					},
					listeners: {
						drop: {
							fn: function(i_dropbox, a_files, o_event) {

								var i_plugin = i_dropbox.getDDPlugin();
								var s_message = "";

								if (i_plugin.enableDrop) {

									if (a_files.length == 1) {

										s_message = ip2.i18n({
											da: "Arbejder....",
											en: "Working...."
										});

										i_self.setLoading(s_message, true);

										Ext.ux.file.util.Handler.createRecordTemporary(i_dropbox.path, a_files[0], function(o_record) {

											i_self.setLoading(false);

											var i_store = i_self.grdStore;
											var i_window = i_self.createEditWindow(i_store, o_record, "new", o_record.uploadname);

											i_window.show();
										});
									}
									else {

										s_message = ip2.i18n({
											da: "Kontrolerer filer....",
											en: "Checking files..."
										});

										i_self.setLoading(s_message, true);

										Ext.ux.file.util.Handler.checkFiles(i_dropbox.path, a_files, function(o_result) {

											i_self.setLoading(false);

											var a_update = o_result.update;
											var a_create = o_result.create;
											var b_update = false;
											var b_cancel = false;
											var b_create = false;

											if (a_update.length > 0) {

												b_update = true;

												Ext.ux.file.util.Handler.getUIConflickWindow(
													i_self.getEl(),
													i_self, i_dropbox.path, a_update,
													function(cancel, a_records) {

														b_cancel = cancel;

														if (!b_create) {

															i_self.setLoading(false);
															i_self.grdStore.load();
														}
														else {

															s_message = ip2.i18n({
																da: "Opretter filer....",
																en: "Creating files..."
															});

															i_self.setLoading(s_message, true);
														}
													});
											}
											if (a_create.length > 0) {

												b_create = true;

												if (!b_update) {

													i_self.setLoading(false);

													s_message = ip2.i18n({
														da: "Opretter filer....",
														en: "Creating files..."
													});

													i_self.setLoading(s_message, true);
												}
												Ext.ux.file.util.Handler.createRecords(i_dropbox.path, a_create, false, function(a_records) {

													b_create = false;

													if (!b_update) {
														i_self.setLoading(false);
														i_self.grdStore.load();
													}
													if (b_cancel) {
														i_self.setLoading(false);
														i_self.grdStore.load();
													}
												});
											}
										});
									}
								}
							}
						},
						dragenter: {
							fn: function(i_dropbox, o_event) {

								var i_plugin = i_dropbox.getDDPlugin();

								if (!ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".create")) {
									i_dropbox.addCls(i_plugin.failureCls);
									i_plugin.enableDrop = false;
								}
							}
						},
						dragleave: {
							fn: function(i_dropbox, o_event) {
								var i_plugin = i_dropbox.getDDPlugin();
								i_plugin.enableDrop = true;
							}
						}
					}
				}
			]
		};
		return item;
	},

	createAddButton: function() {
		var i_self = this;
		var btnAdd = Ext.widget("splitbutton", {
			text: ip2.i18n({
				da: "Tilføj",
				en: "Add"
			}),
			listeners: {
				menuhide: function(item) {
					if (item.pressed) {
						item.toggle();
					}
				}
			},
			handler: function(item) {
				item.toggle();
				if (item.pressed) {
					item.showMenu();
				}
				else {
					item.hideMenu();
				}
			},
			menu: {
				xtype: "menu",
				minWidth: 150,
				height: 350,
				width: 200,
				autoScroll: true,
				enableKeyNav: false,
				onMouseOver: function() {},
				items: [
					i_self.createTreeAdd()
				]

			}
		});
		return btnAdd;
	},

	createTreeAdd: function() {
		var i_self = this;
		var i_tree = Ext.ux.file.util.Handler.getUITree({
			path: "$root$",
			useSystem: false,
			rootVisible: false,
			flex: 1,
			store: i_self.sharedTreeStore,
			listeners: {
				select: {
					fn: function(model, node) {
						var menu = i_self.treeAdd.up("menu");
						if (menu) {
							menu.hide();
							var i_view = i_self.treeAdd.getView();
							if (node.get("allowAdd")) {
								var i_store = i_self.grdStore;

								var o_record = i_self.grdStore.model.create();
								o_record.set("FILPATH", node.get("path"));
								o_record.set("FILORIPATH", node.get("path"));
								o_record.set("FILCRTBY", ip2.navigator.user.id);
								o_record.set("FILCREATE", ip2.createIsoTimeStamp());

								var wndEdit = i_self.createEditWindow(i_store, o_record, "new");
								wndEdit.show();
							}
							else {
								var title = ip2.i18n({
									da: "Fejl",
									en: "Error"
								});
								var msg = ip2.i18n({
									da: "Det ikke tilladt at oprette en fil på denne folder",
									en: "It is not allowed to create a file in this folder"
								});
								ip2.messageBox({
									icon: Ext.MessageBox.WARNING,
									title: title,
									closable: true,
									message: msg,
									yesText: ip2.i18n({
										da: "OK",
										en: "OK"
									}),
									noText: ip2.i18n({
										da: "Annuller",
										en: "Cancel"
									})
								});
							}
							i_view.deselect(node);
						}
					}
				}
			}
		});

		var store = i_tree.getStore();
		var i_view = i_tree.getView();

		store.on({
			load: {
				fn: function(store, a_records, success, operation, node) {
					ip2.each(a_records, function(o_record) {
						o_record.set("allowDrag", false);

						if (!o_record.get("hasChild")) {
							o_record.set("loaded", true);
						}
						else {
							o_record.expand();
						}
					});
					i_view.refresh();
					i_tree.setLoading(false);
				}
			}
		});
		i_self.treeAdd = i_tree;
		return i_tree;
	},

	createTreeDisk: function() {
		var i_self = this;
		stack = [];
		stack.push(0);

		var i_tree = Ext.ux.file.util.Handler.getUITree({
			path: "$root$",
			viewConfig: {
				plugins: {
					ptype: "treeviewdragdrop",
					enableDrag: false,
					enableDrop: true,
					dropGroup: "grid2tree",
					appendOnly: true
				},
				listeners: {
					beforedrop: {
						fn: function(node, data, overModel, dropPosition, dropHandler, e) {
							if (ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".create")) {
								var a_records = data.records;

								var s_fromPath = a_records[0].get("FILPATH");
								var s_toPath = ip2.cleanPath(overModel.get("path")) + "/";

								var msg = ip2.i18n({
									da: "Kontrolerer filer..",
									en: "Checking  files.."
								});
								i_self.setLoading(msg, true);
								Ext.ux.file.util.Handler.checkRecords(s_toPath, a_records, function(a_create, a_update) {
									var b_update = false;
									var b_cancel = false;
									var b_create = false;
									if (a_update.length > 0) {
										i_self.setLoading(false);
										b_update = true;
										ip2.each(a_update, function(o_update) {
											o_update.name = o_update.get("FILNAME");
											o_update.src = o_update.get("FILPATH") + o_update.get("FILNAME");
										});;
										var wnd = i_self.createConflickWindow(s_toPath, a_update, function(a_overwrite, a_rename) {
											if (a_rename.length > 0) {
												var a_records = [];
												ip2.each(a_rename, function(o_rename) {
													var o_record = o_rename.file;
													o_record.set("FILNAME", o_rename.suggestedName);
													a_records.push(o_record);
												});
												Ext.ux.file.util.Handler.moveRecords(s_toPath, a_records, function(a_records) {
													i_self.grdStore.load();
												});
											}
											if (a_overwrite.length > 0) {
												var a_records = [];
												var msg = ip2.i18n({
													da: "Flytter filer..",
													en: "Moving  files.."
												});
												i_self.setLoading(msg, true);
												ip2.each(a_overwrite, function(o_overwrite) {
													a_records.push(o_overwrite.file);
												});
												Ext.ux.file.util.Handler.moveAndDeleteOldRecords(s_toPath, a_records, function(a_records) {
													i_self.setLoading(false);
													i_self.grdStore.load();
												});
											}
											if (a_overwrite.length == 0 && a_rename.length == 0) {
												i_self.grdStore.load();
											}
										}, function() {
											b_cancel = true;
											if (!b_create) {
												i_self.grdStore.load();
											}
											else {
												var msg = ip2.i18n({
													da: "Flytter filer....",
													en: "Moving files..."
												});
												i_self.setLoading(msg, true);
											}
										});
										wnd.show();
									}
									if (a_create.length > 0) {
										b_create = true;
										if (!b_update) {
											i_self.setLoading(false);
											var msg = ip2.i18n({
												da: "Flytter filer..",
												en: "Moving  files.."
											});
											i_self.setLoading(msg, true);
										}
										Ext.ux.file.util.Handler.moveRecords(s_toPath, a_create, function(a_records) {
											b_create = false;
											if (!b_update) {
												i_self.setLoading(false);
												i_self.grdStore.load();
											}
											if (b_cancel) {
												i_self.setLoading(false);
												i_self.grdStore.load();
											}
										});
									}
								});
								data.records = [];
							}
							else {
								return false;
							}
						}
					},
					drop: {
						fn: function(node, data, overModel) {
							i_self.treeDiskFolders.getSelectionModel().select(overModel);
						}
					}
				}
			},
			listeners: {
				select: {
					fn: function(tree, node) {
						var title = ip2.i18n({
							da: "Filer - ",
							en: "Files - "
						});
						title += node.get("text");
						var path = "";
						if (node.isRoot()) {
							path = "/";
						}
						else {
							path = node.get("path");
						}

						i_self.pnlCenter.setTitle(title);

						if (node.get("type") == "system") {
							i_self.pnlCenter.setLoading(true);
							Ext.ux.file.util.Handler.getRecordListByPath(path, function(a_records) {
								if (i_self.i_grid_memory) {
									i_self.grid.hide();
									var i_memestore = i_self.i_grid_memory.getStore();
									i_memestore.loadData(a_records);
									i_memestore.loadPage(1);
									i_self.i_grid_memory.show();
								}
								else {
									i_self.grid.hide();
									i_self.i_grid_memory = i_self.createMemoryGrid(a_records);
									i_self.pnlCenter.add(i_self.i_grid_memory);
								}

								i_self.pnlCenter.setLoading(false);
							});
						}
						else {
							if (i_self.i_grid_memory) {
								i_self.i_grid_memory.hide();
								i_self.grid.show();
							}
							i_self.grdStore.proxy.extraParams.where = "FILPATH like '" + path + "%'";
							i_self.grdStore.currentPage = 1;
							i_self.grdStore.load();
						}

						i_self.treeDiskFolders.selected = node;
					}
				},
				itemcontextmenu: {
					fn: function(tree, node, html, index, event) {
						event.preventDefault();
						var theNode = node;
						var a_items = [];
						if (ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".createfolder")) {
							a_items.push({
								text: ip2.i18n({
									da: "Tilføj mappe",
									en: "Add folder"
								}),
								parent: node,
								disabled: (node.get("type") == "system") || node.isRoot(),
								handler: function(button) {
									var msg = ip2.i18n({
										da: "Skriv navnet på den nye mappe",
										en: "Write name on the new folder"
									});
									var title = ip2.i18n({
										da: "Ny mappe",
										en: "New folder"
									});
									Ext.Msg.prompt(title, msg, function(btn, text) {
										if (btn == "ok") {
											i_self.createDir(theNode, text);
										}
									});
								}
							});
						}
						if (ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".deletefolder")) {
							a_items.push({
								text: ip2.i18n({
									da: "Slet mappe",
									en: "Delete folder"
								}),
								parent: node,
								disabled: (node.get("isHive") || node.isRoot()) ? true : false,
								handler: function(button) {
									var msg = ip2.i18n({
										da: "Vil du slette mappen..?",
										en: "DO you want to delete the folder..?"
									});
									var title = ip2.i18n({
										da: "Slet",
										en: "Delete"
									});

									ip2.messageBox({
										icon: Ext.MessageBox.WARNING,
										title: title,
										closable: true,
										message: msg,
										yesText: ip2.i18n({
											da: "OK",
											en: "OK"
										}),
										yesFn: function () {
											i_self.deleteDir(theNode);
										},
										noText: ip2.i18n({
											da: "Annuller",
											en: "Cancel"
										})
									});
								}
							});
						}
						if (ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".syncfolder")) {
							a_items.push({
								text: ip2.i18n({
									da: "Synkroniser mappe",
									en: "synchronize folder"
								}),
								disabled: !node.get("allowImport"),
								handler: function(item) {
									var msg = ip2.i18n({
										da: "Synkroniserer filer",
										en: "synchronizing files"
									});
									i_self.setLoading(msg, true);

									Ext.ux.file.util.Handler.consulidateDirectory(node.get("path"), function(a_records, a_delete) {
										i_self.setLoading(false);
										if (a_records.length > 0) {
											i_self.addTags(a_records, function(a_records) {
												var title = ip2.i18n({
													da: "Success",
													en: "Success"
												});
												var msg = ip2.i18n({
													da: a_records.length + " filer blev tilføjet..",
													en: a_records.length + " files was added"
												});
												if (a_delete.length > 0) {
													msg = msg + ip2.i18n({
														da: "<br></br>" + a_delete.length + " referencer blev slettet",
														en: "<br></br>" + a_delete.length + " references was delete"
													});
												}
												ip2.messageBox({
													icon: Ext.MessageBox.INFO,
													title: title,
													closable: false,
													message: msg,
													yesFn: function() {
														i_self.grdStore.load();
													},
													noFn: function() {
														i_self.grdStore.load();
													},
													cancelFn: function() {
														i_self.grdStore.load();
													},
													yesText: ip2.i18n({
														da: "OK",
														en: "OK"
													}),
													noText: ip2.i18n({
														da: "Annuller",
														en: "Cancel"
													})
												});
											});
										}
										else {
											var title = ip2.i18n({
												da: "Success",
												en: "Success"
											});
											var msg = ip2.i18n({
												da: "Ingen nye filer..",
												en: "No new files.."
											});
											if (a_delete.length > 0) {
												msg = msg + ip2.i18n({
													da: "<br></br>" + a_delete.length + " referencer blev slettet",
													en: "<br></br>" + a_delete.length + " references was delete"
												});
											}
											if (a_delete.length == 0) {
												ip2.messageBox({
													icon: Ext.MessageBox.INFO,
													title: title,
													closable: false,
													message: msg,
													yesText: ip2.i18n({
														da: "OK",
														en: "OK"
													}),
													noText: ip2.i18n({
														da: "Annuller",
														en: "Cancel"
													})
												});
											}
											else {
												ip2.messageBox({
													icon: Ext.MessageBox.INFO,
													title: title,
													closable: false,
													message: msg,
													yesFn: function() {
														i_self.grdStore.load();
													},
													noFn: function() {
														i_self.grdStore.load();
													},
													cancelFn: function() {
														i_self.grdStore.load();
													},
													yesText: ip2.i18n({
														da: "OK",
														en: "OK"
													}),
													noText: ip2.i18n({
														da: "Annuller",
														en: "Cancel"
													})
												});
											}
										}
									});
								}
							});
						}
						a_items.push({
							text: ip2.i18n({
								da: "Genindlæs",
								en: "Reload"
							}),
							parent: node,
							handler: function(button) {
								i_self.reloadTrees(node, false);
							}
						});
						var menu = Ext.widget("menu", {
							allowOtherMenus: false,
							items: a_items
						});
						var a_xy = event.getXY();
						menu.showAt(a_xy[0], a_xy[1]);
					}
				}
			}
		});

		var i_view = i_tree.getView();
		var i_store = i_tree.getStore();

		i_self.sharedTreeStore = i_store;
		i_store.on({
			load: {
				fn: function(store, a_records, success, operation, node) {
					var i_tree = i_self.treeDiskFolders;
					if (!i_tree.selected) {
						var i_root = i_tree.getRootNode();
						var record = i_root.getChildAt(0);
						i_tree.selected = record;
						i_tree.getSelectionModel().select(record);
					}
					ip2.each(a_records, function(o_record) {
						o_record.set("allowDrag", false);

						if (!o_record.get("hasChild")) {
							o_record.set("loaded", true);
						}
						else {
							stack.push(0);
							o_record.expand();
						}
					});
					stack.pop();
					if (stack.length === 0) {
						var root = i_tree.getRootNode();
						i_self.portlet.tmp = [];
						i_self.itemCount = 0;
						if (i_self.portlet.items) {
							i_self.portlet.removeAll(true);
						}
						root.cascadeBy(function(node) {
							if (!node.isRoot() && node.get("allowDrop")) {
								i_self.itemCount++;
								var s_path = ip2.cleanPath(node.get("path")) + "/";
								var text = "";
								if (!node.parentNode.isRoot()) {
									var parent = node.parentNode;
									while (!parent.isRoot() && parent.get("allowDrop")) {
										text = parent.get("text") + "/" + text;
										parent = parent.parentNode;
									}
									text = text + node.get("text");
								}
								else {
									text = node.get("text");
								}
								var item = i_self.createPortletItem(s_path, text);
								i_self.portlet.tmp.push(item);
							}
						});
						i_self.portlet.add(i_self.createColumns());
						i_self.addItems();
						i_view.refresh();
						i_tree.setLoading(false);
					}
				}
			}
		});
		i_self.treeDiskFolders = i_tree;

		return i_tree;
	},

	addTags: function(a_records, f_callback) {
		var i_self = this;
		var title = ip2.i18n({
			da: "Nye filer",
			en: "New files"
		});
		var msg = ip2.i18n({ da: "Der er " + a_records.length + " nye filer", en: "There is " + a_records.length + " new files" }) + "</br>";
		msg += ip2.i18n({ da: "Tilføj tags", en: "Add tags" });

		Ext.Msg.prompt(title, msg, function(btn, text) {
			var msg = ip2.i18n({
				da: "Opretter filer...",
				en: "Creating files..."
			});
			i_self.setLoading(msg, true);
			if (btn == "ok") {
				Ext.ux.file.util.Handler.createTags(a_records, text, function(a_records) {
					i_self.setLoading(false);
					f_callback(a_records);
				});
			}
			else {
				Ext.ux.file.util.Handler.upsertRecords(a_records, function(a_records) {
					i_self.setLoading(false);
					f_callback(a_records);
				});
			}
		});
	},

	createDir: function(node, dir) {
		var i_self = this;
		var path = ip2.cleanPath(node.get("path")) + "/" + dir;
		var msg = ip2.i18n({
			da: "Opretter mappe",
			en: "Creating folder"
		});
		i_self.treeDiskFolders.setLoading(msg, true);
		Ext.ux.file.util.Handler.createDirectory(path, function(success) {
			if (success) {
				i_self.reloadTrees(node, false);
			}
			else {
				i_self.treeDiskFolders.setLoading(false);
				var title = ip2.i18n({
					da: "Fejl",
					en: "Error"
				});
				var msg = ip2.i18n({
					da: "Mappen kunne ikke oprettes",
					en: "The folder could not be created"
				});
				ip2.messageBox({
					icon: Ext.MessageBox.ERROR,
					title: title,
					closable: true,
					message: msg,
					yesText: ip2.i18n({
						da: "OK",
						en: "OK"
					}),
					noText: ip2.i18n({
						da: "Annuller",
						en: "Cancel"
					})
				});
			}
		});
	},

	reloadTrees: function(node, b_parent) {

		var i_self = this;
		i_self.treeDiskFolders.setLoading(true);
		i_self.treeDiskFolders.reload(node, b_parent, true);
	},

	deleteDir: function(node) {
		var i_self = this;
		var path = ip2.cleanPath(node.get("path"));
		var msg = ip2.i18n({
			da: "Sletter mappe",
			en: "Deleting folder"
		});
		i_self.treeDiskFolders.setLoading(msg, true);
		Ext.ux.file.util.Handler.deleteDirectory(path, function(success) {
			i_self.treeDiskFolders.setLoading(false);
			if (success) {
				i_self.reloadTrees(node, true);
			}
			else {
				var title = ip2.i18n({
					da: "Fejl",
					en: "Error"
				});
				var msg = ip2.i18n({
					da: "Sleting af mappen kunne ikke fortagets<br>mappen er ikke tom",
					en: "Removal of the folder could not be done<br>folder is not empty"
				});
				ip2.messageBox({
					icon: Ext.MessageBox.ERROR,
					title: title,
					closable: true,
					message: msg,
					yesText: ip2.i18n({
						da: "OK",
						en: "OK"
					}),
					noText: ip2.i18n({
						da: "Annuller",
						en: "Cancel"
					})
				});
			}
		});
	},

	createTooltip: function(view) {
		var i_self = view.up("filemanager");

		var tpl = new Ext.XTemplate(
			'<tpl for=".">',
				'<tpl if="values.FILEXTERNAL == true">',
				'<div style="width:250px;height:auto !important;">',
					'<div style="',
						'float: left;',
						'width: 25%;',
						'height: 100px;',
						'background-image: url({[this.getURL(values.FILEXTERNAL,values.FILEXT,values.FILORIPATH)]});',
						'background-repeat: no-repeat;',
						'background-size: contain;',
						'background-position: 50% 50%;',
					'"></div>',
					'<div style="',
						'float:right;',
						'padding:0px 0px 0px 10px;',
						'width:73%;',
						'height:100%;">',
						'<p><b>' + ip2.i18n({ da: "ID", en: "ID" }) + ' </b>: {FILFILTKN}</p>',
						'<p><b>' + ip2.i18n({ da: "Navn", en: "Name" }) + ' </b>: {FILNAME}</p>',
						'<p><b>' + ip2.i18n({ da: "Overskrift", en: "Header" }) + ' </b>: {FILHEAD}</p>',
						'<p><b>' + ip2.i18n({ da: "Overskrift 2", en: "Sub header" }) + '</b>: {FILSUB}</p>',
						'<p><b>' + ip2.i18n({ da: "Tag", en: "Tag" }) + ' </b>: {FILTAG}</p>',
						'<p><b>' + ip2.i18n({ da: "Relationer", en: "Relations" }) + ' </b>: {FILREL}</p>',
						'<p><b>' + ip2.i18n({ da: "Ekstern", en: "External" }) + ' </b>: [this.converTo(values.FILEXTERNAL)]</p>',
						'</div>',
					'<div style="clear:both"></div>',
					'</div>',
				'</tpl>',
				'<tpl if="values.FILEXTERNAL == false">',
					'<div style="width:250px;height:auto !important;">',
					'<div style="',
						'float: left;',
						'width: 25%;',
						'height: 100px;',
						'background-image: url({[this.getURL(values.FILEXTERNAL, values.FILEXT, values.FILPATH, values.FILNAME)]});',
						'background-repeat: no-repeat;',
						'background-size: contain;',
						'background-position: 50% 50%;',
					'"></div>',
					'<div style="',
						'float:right;',
						'padding:0px 0px 0px 10px;',
						'width:73%;',
						'height:100%;">',
						'<p><b>' + ip2.i18n({ da: "ID", en: "ID" }) + ' </b>: {FILFILTKN}</p>',
						'<p><b>' + ip2.i18n({ da: "Navn", en: "Name" }) + ' </b>: {FILNAME}</p>',
						'<p><b>' + ip2.i18n({ da: "Overskrift", en: "Header" }) + ' </b>: {FILHEAD}</p>',
						'<p><b>' + ip2.i18n({ da: "Overskrift 2", en: "Sub header" }) + '</b>: {FILSUB}</p>',
						'<p><b>' + ip2.i18n({ da: "Tag", en: "Tag" }) + ' </b>: {FILTAG}</p>',
						'<p><b>' + ip2.i18n({ da: "Relationer", en: "Relations" }) + ' </b>: {FILREL}</p>',
						'<p><b>' + ip2.i18n({ da: "Ekstern", en: "External" }) + ' </b>: {[this.converTo(values.FILEXTERNAL)]}</p>',
					'</div>',
					'<div style="clear:both;"></div>',
				'</div>',
				'</tpl>',
			'</tpl>',
			{
				converTo: function(value) {
					return value ? ip2.i18n({ da: "Ja", en: "Yes" }) : ip2.i18n({ da: "Nej", en: "No" });
				},
				getURL: function(b_external, s_ext, s_path, s_name) {
					var s_url = "";
					var a_extension_image = ["jpg","jpeg","png","gif", "bmp"];
					if (b_external) {
						if (a_extension_image.indexOf(s_ext.toLowerCase()) == -1) {
							s_url = Ext.ux.file.util.Handler.getUrlByExtension(s_url);
						}
						else {
							s_url = s_path;
						}
					}
					else {
						if (a_extension_image.indexOf(s_ext.toLowerCase()) == -1) {
							s_url = Ext.ux.file.util.Handler.getUrlByExtension(s_url);
						}
						else {
							s_url = s_path + s_name;
						}
					}
					var dc = new Date().getMilliseconds();
					return "\"" + s_url + "?_dc=" + dc + "\"";
				}
			}
        );

		view.tip = Ext.create("Ext.tip.ToolTip", {
			// The overall target element.
			target: view.el,

			// Each grid row causes its own seperate show and hide.
			delegate: view.itemSelector,

			// Moving within the row should not hide the tip.
			trackMouse: true,

			// Render immediately so that tip.body can be referenced prior to the first show.
			renderTo: Ext.getBody(),
			showDelay: 800,
			autoHide: false,
			listeners: {
				// Change content dynamically depending on which element triggered the show.
				beforeshow: function (tip) {
					var o_record = view.getRecord(tip.triggerElement);
					var div = document.createElement("div");
					var i_tpl = tpl.compile();
					i_tpl.overwrite(div, o_record.data);
					tip.update(div.innerHTML);
					delete div;
				}
			}
		});
		Ext.QuickTips.init();
	},

	createEditWindow: function(store, o_record, type, uploadname) {

		var i_self = this;
		var o_size = Ext.ux.file.util.Handler.getWindowSize();
		var title = "";
		if (type == "new") {
			title = ip2.i18n({
				da: "Ny fil",
				en: "New file"
			});
		}
		else {
			title = ip2.i18n({
				da: "Rediger " + o_record.get("FILNAME"),
				en: "Editing " + o_record.get("FILNAME")
			});
		}
		var wndEdit = Ext.widget("fileedit", {
			title: title,
			width: o_size.width * 0.9,
			height: o_size.height * 0.9,
			layout: "fit",
			constrain: true,
			modal: true,
			record: o_record,
			store: store,
			type: type,
			hasUploaded: uploadname != null ? true : false,
			uploadname: uploadname
		});
		return wndEdit;
	},

	createConflickWindow: function(pp_path, a_files, okFn, cancelFn) {
		var i_self = this;
		var wnd = Ext.widget("fileconflict", {
			files: a_files,
			path: pp_path,
			width: 900,
			height: 600,
			okFn: okFn || Ext.emptyFn,
			cancelFn: cancelFn || Ext.emptyFn
		});
		return wnd;
	},

	createGrid: function() {
		var i_self = this;

		var i_grid = Ext.ux.file.util.Handler.getUIGrid({
			autoLoad: false,
			viewConfig: {
				listeners: {
					render: i_self.createTooltip
				},
				plugins: {
					ptype: "gridviewdragdrop",
					enableDrop: false,
					dragGroup: "grid2tree"
				}
			}
		});

		i_grid.on({
			afterrender: {
				fn: function(i_grid) {

					var i_toolbar = i_grid.getToolbar();

					i_grid.events.itemdblclick.clearListeners();

					var index = i_toolbar.removeExport();

					i_toolbar.items.removeAt(index);

					index = i_toolbar.removeAdd();

					if (index && ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".create")) {
						i_toolbar.insert(index, i_self.createAddButton());
					}

					if (ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".update") ||
						ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".read")) {

						i_grid.on({
							"itemdblclick": {
								fn: function(grid, record, html, index) {
									var i_store = i_grid.getStore();
									var i_window = i_self.createEditWindow(i_store, record, "edit");
									i_window.show();
								}
							}
						});

						var i_menu = i_grid.getRowMenu();

						if (i_menu) {
							i_menu.items.removeAt(1, true);
							i_menu.items.items[0].handler = function(i_menu, event) {
								var i_store = i_grid.getStore();
								var i_record = i_grid.getSelection()[0];
								var i_window = i_self.createEditWindow(i_store, i_record, "edit");
								i_window.show();
							};
						}
					}

					var i_dropzone = i_self.createDropZone();

					var i_element = i_grid.getView().getEl();

					i_dropzone.getEl().insertBefore(i_element);

					i_grid.on({
						"afterdelete": {
							fn: function(store, records) {
								// TODO: Pipe yourself on the ip2.App event "entityupdate"
								// instead - the 2nd argument will be type (update, delete, create)
								// so we can deprecate the afterdelete event
								// By: ISJ
								Ext.ux.file.util.Handler.unlinkRecords(records, function() {});
							}
						}
					});
				}
			}
		});

		var i_store = i_grid.getStore();

		i_self.grid = i_grid;
		i_self.grdStore = i_store;

		i_store.on({
			beforeload: {
				fn: function(i_store, o_operation) {

					var i_selectedNode = i_self.treeDiskFolders.getSelection()[0];
					if (i_selectedNode) {
						var i_proxy = i_store.getProxy();
						var o_sorters = i_store.getSorters();
						var o_extraParams = i_proxy.getExtraParams();

						var s_path = "";

						if (i_selectedNode.isRoot()) {
							s_path = "/";
						}
						else {
							s_path = i_selectedNode.get("path");
						}

						s_path = "FILPATH like '" + s_path + "%'";
						var s_where = o_extraParams.where;
						if (!ip2.isEqual(s_where, s_path)) {
							if (s_where) {
								s_where = s_where + " AND " + s_path;
							}
							else {
								s_where = s_path;
							}
						}
						o_extraParams.where = s_where;
					}
				}
			}
		});

		return i_grid;
	},
	createMemoryGrid: function(a_records) {

		var i_self = this;
		var model = i_self.grdStore.model;
		var a_columns = i_self.grid.columns.slice();
		var a_result = [];
		ip2.each(a_columns, function(o_column) {
			a_result.push(o_column.initialConfig);
		});
		var a_data = [];
		ip2.each(a_records, function(o_record) {
			a_data.push(o_record.data);
		});
		var data = {
			"total": a_records.length,
			"rows": a_data
		};
		var i_store = Ext.create("Ext.data.Store", {
			model: model,
			sorters: [
				{
					property: "FILNAME",
					direction: "ASC"
				}
			],
			proxy: {
				type: "pagingmemory",
				reader: {
					type: "json",
					rootProperty: "rows",
					totalProperty: "total"
				}
			},
			pageSize: 50
		});

		i_store.loadRawData(data);

		var sm = Ext.create("Ext.selection.CheckboxModel", {
			mode: "MULTI",
			enableKeyNav: true
		});

		var i_grid = Ext.widget("gridpanel", {
			store: i_store,
			columns: a_result,
			selModel: sm,
			dockedItems: [{
				xtype: "pagingtoolbar",
				store: i_store,
				dock: "top",
				displayInfo: true,
				items: [
				"-",
				{
					xtype: "textfield",
					itemId: "txtsearch",
					labelWidth: 35,
					width: 250,
					isFormField: false,
					enableKeyEvents: true,
					triggers: {
						clear: {
							cls: "x-form-clear-trigger",
							scope: "this",
							hidden: true,
							handler: "onClear"
						},
						search: {
							cls: "x-form-search-trigger",
							scope: "this",
							handler: "onSearch"
						}
					},
					onClear: function(i_field) {
						i_field.setValue("");
						i_field.onSearch(i_field);
					},
					onSearch: function(i_field) {
						var value = i_field.getValue();
						var i_trigger = i_field.getTrigger("clear");
						if (value == "") {
							i_store.clearFilter();
							delete i_store.filterName;
							i_trigger.hide();
						}
						else {
							i_trigger.show();
							if (i_store.filterName) {
								i_store.clearFilter();
								delete i_store.filterName;
							}
							var i_filter = Ext.create("Ext.util.Filter", {
								id: "f_name",
								filterFn: function(o_record) {
									var a_keys = Object.keys(o_record.data);
									var s_value = "";
									var found = false;
									for (var i = 0; i < a_keys.length; i++) {
										var s_key = a_keys[i];
										var s_value = JSON.stringify(o_record.get(s_key));
										s_value = s_value.toLowerCase();

										if (s_value.indexOf(value.toLowerCase()) != -1) {
											found = true;
											break;
										}
									}
									return found;
								}
							});
							i_store.addFilter(i_filter);
						}
						i_store.loadPage(1);
					},
					listeners: {
						keydown: function(i_field, e) {
							if (e.keyCode == e.ENTER) {
								i_field.onSearch(i_field);
							}
						}
					}
				}
				]
			}],
			listeners: {
				afterrender: {
					fn: function(i_grid) {
						var i_store = i_grid.getStore();
						i_store.loadPage(1);
					}
				},
				itemdblclick: {
					fn: function(view, record, html, index) {
						if (ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".update") ||
							ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".read")) {
							var wnd = i_self.createPreviewWindow(record);
							wnd.show();
						}
					}
				},
				itemcontextmenu: {
					fn: function(view, record, item, index, event) {
						event.preventDefault();
						var selModel = i_grid.getSelectionModel();
						if (!selModel.isSelected(index)) {
							view.select(index);
						}
						event.stopEvent();
						if (ip2.isAccessible("app." + i_self.dmdName + ".data." + i_self.entity + ".delete")) {
							if (view.menu) {
								view.menu.hide();
								view.menu.destroy();
							}
							var i_menu = Ext.widget("menu", {
								items: [
								{
									text: ip2.i18n({
										da: "Slet",
										en: "Delete"
									}),
									iconCls: "ip2-icon-delete",
									handler: function(i_menuitem) {

										var a_records = i_grid.getSelectionModel().getSelection();

										var msg = a_records.length == 1 ? ip2.i18n({
											da: "Ønsker du virkelig at slette?",
											en: "Do you really wish to delete?"
										}) : ip2.i18n({
											da: "Ønsker du virkelig at slette de " + a_records.length + " valgte?",
											en: "Do you really wish to delete the " + a_records.length + " selected?"
										});
										var title = ip2.i18n({
											da: "Slet",
											en: "Delete"
										});

										ip2.messageBox({
											icon: Ext.MessageBox.WARNING,
											title: title,
											closable: true,
											message: msg,
											yesText: ip2.i18n({
												da: "OK",
												en: "OK"
											}),
											yesFn: function () {
												var msg = ip2.i18n({
													da: "Sletter...",
													en: "Deleting..."
												});
												i_self.setLoading(msg, true);

												Ext.ux.file.util.Handler.unlinkRecords(a_records, function() {
													var path = a_records[0].get("FILPATH");
													Ext.ux.file.util.Handler.getRecordListByPath(path, function(a_records) {
														if (i_self.i_grid_memory) {
															var i_memestore = i_self.i_grid_memory.getStore();
															i_memestore.loadData(a_records);
															i_memestore.loadPage(1);
														}
														i_self.setLoading(false);
													});
												});
											},
											noText: ip2.i18n({
												da: "Annuller",
												en: "Cancel"
											})
										});
									}
								}
								]
							});
							view.menu = i_menu;
							var a_xy = event.getXY();
							i_menu.showAt(a_xy[0], a_xy[1]);
						}
					}
				}
			}
		});
		return i_grid;
	},

	createPreviewWindow: function(o_record) {
		var wndPreview = Ext.widget("filepreview", {
			record: o_record
		});
		return wndPreview;
	}
});
