Ext.define("Portfolio.designer.ui.ifsExplorer", {
	extend: "Ext.window.Window",
	alias: ["widget.ifsExplorer"],
	iconCls: "ip2-icon-add-dmd",
	closable: true,
	closeAction: "hide",
	width: 600,
	minWidth: 350,
	height: 400,
	layout: {
		type: "border",
		padding: 5
	},
	initComponent: function() {

		var me = this;
		me.items = [];
		me.panel = {};
		me.field = {};
		me.selection = {};

		me.action = (me.action) ? me.action : "open";
		me.saveAction = (me.action.toLowerCase() == "save" || me.action.toLowerCase() == "saveas") ? true : false;
		me.title = ip2.i18n(me.action);

		me.field.path = Ext.widget("textfield", {
			name: "path",
			fieldLabel: "Explorer",
			labelWidth: 40,
			allowBlank: true,
			anchor: "100%",
			value: (me.path) ? me.path : "",
			enableKeyEvents: true,
			listeners: {
				keydown: {
					fn: function(item, e) {
						if (e.keyCode == 13) {
							me.selection.folder = item.getValue();
							var i_root = me.panel.navigator.getRootNode();
							i_root.removeAll(false);
							me.panel.navigator.store.load({
								node: i_root
							});
						}
					}
				}
			}
		});

		me.panel.path = Ext.create("Ext.panel.Panel", {
			region: "north",
			split: false,
			collapsible: false,
			floatable: false,
			bodyStyle: "padding:3px;",
			layout: {
				type: "anchor"
			},
			items: [
				me.field.path
			]
		});
		me.items.push(me.panel.path);

		ip2.ifsExplorerService = (ip2.isOffline) ? "ip2DmdProxy.php" : "webBios.aspx";

		// object list (grid)
		if (!Ext.ClassManager.isCreated("objectList")) {
			Ext.define("objectList", {
				extend: "Ext.data.Model",
				proxy: {
					type: "ajax",
					url: "/ip2-services/" + ip2.ifsExplorerService,
					extraParams: {
						func: "listdir",
						metaData: true,
						sort: true
					},
					reader: {
						type: "json",
						rootProperty: "rows",
						totalProperty: "totalRows"
					}
				}
			});
		}
		function objectIcon (v) {

			var s_icon = "";

			var s_url = "";

			switch (v) {
				case "bmp":
					s_url = "portfolio/Themes/Default/bmp.gif";
					break;
				case "dbm":
					s_url = "portfolio/Themes/Default/branch.png";
					break;
				case "doc":
					s_url = "portfolio/Themes/Default/doc.gif";
					break;
				case "docx":
					s_url = "portfolio/Themes/Default/doc.gif";
					break;
				case "eml":
					s_url = "portfolio/Themes/Default/eml.gif";
					break;
				case "folder":
					s_url = "portfolio/Themes/Default/folder.gif";
					break;
				case "gif":
					s_url = "portfolio/Themes/Default/gif.gif";
					break;
				case "htm":
					s_url = "portfolio/Themes/Default/html.gif";
					break;
				case "html":
					s_url = "portfolio/Themes/Default/html.gif";
					break;
				case "jpg":
					s_url = "portfolio/Themes/Default/jpg.gif";
					break;
				case "jpeg":
					s_url = "portfolio/Themes/Default/jpg.gif";
					break;
				case "pdf":
					s_url = "portfolio/Themes/Default/pdf.gif";
					break;
				case "png":
					s_url = "portfolio/Themes/Default/png.gif";
					break;
				case "ppt":
					s_url = "portfolio/Themes/Default/ppt.gif";
					break;
				case "tif":
					s_url = "portfolio/Themes/Default/tif.gif";
					break;
				case "xls":
					s_url = "portfolio/Themes/Default/xls.gif";
					break;
				case "xlsx":
					s_url = "portfolio/Themes/Default/xls.gif";
					break;
				case "xml":
					s_url = "portfolio/Themes/Default/xml.gif";
					break;
				default:
					s_url = "portfolio/Themes/Default/document.png";
					break;
			}

			var s_icon = "<img src=\"" + s_url + "\"/>";

			return s_icon;
		}
		me.panel.objectGrid = Ext.create("Ext.grid.Panel", {
			region: "center",
			store: Ext.create("Ext.data.Store", {
				model: "objectList",
				listeners: {
					beforeload: {
					fn: function(store, operation) {

						var s_path = me.selection.folder;
						var i_proxy = store.getProxy();
						var o_extraParams = i_proxy.getExtraParams();

						Ext.apply(o_extraParams, {
							path: s_path
						});
					}
				}
				}
			}),
			columns: [
				{ header: "", dataIndex: "ext", renderer: objectIcon, width: 24 },
				{ header: "Name", dataIndex: "text", flex: 2 },
				{ header: "Changed", dataIndex: "mtime", width: 68 },
				{ header: "Size (kb)", dataIndex: "size", align: "right", width: 66 }
			],
			listeners: {
				itemkeyup: {
					fn: function(i_view, i_selected, i_element, n_index, i_event) {

						var i_store = i_view.grid.getStore();
						var a_records = i_store.getRange();
						var i_newSelect;
						var n_prev;

						var s_key = String.fromCharCode(i_event.keyCode).toLowerCase();
						if (i_event.keyCode != 13) {
							Ext.Array.each(a_records, function(i_record) {
								var s_text = i_record.get("text") || "";
								s_text = s_text.toLowerCase();
								if (Ext.String.startsWith(s_text, s_key)) {
									var n_current = i_store.find("text", i_record.get("text"));
									if (Ext.isEmpty(n_prev)) {
										if (n_current < n_index) {
											n_prev = n_current;
										}
									}
									if (n_current > n_index) {
										i_newSelect = i_record;
										return false;
									}
								}
							});

							if (!i_newSelect && !Ext.isEmpty(n_prev)) {
								i_newSelect = i_store.getAt(n_prev);
							}
							if (i_newSelect) {
								i_view.select(i_newSelect);
								i_view.focusNode(i_newSelect, 20);
							}
						}
						else {
							var i_grid = i_view.grid;
							i_grid.fireEvent("itemdblclick", i_view, i_selected, i_element, n_index, i_event);
						}
					}
				},
				select: {
					fn: function(i_view, i_record) {

						var b_valid = i_record.get("ext") == me.validSelectionExtention;
						var i_form = me.panel.controlFields;
						me.panel.controlFields.fireEvent("validityChange", i_form, b_valid);
						if (i_record.get("ext") == "folder") {
							me.field.path.setValue(ip2.cleanPath(i_record.get("id")));
						}
						if (me.saveAction && i_record.get("ext") != "folder") {
							me.field.filename.setValue(i_record.get("text"));
						}
					}
				},
				itemdblclick: function(view, i_record, item, index, e) {
					e.preventDefault();
					if (i_record.get("ext") == "folder") {
						var store = me.panel.objectGrid.store;
						me.selection.folder = ip2.cleanPath(i_record.get("id"));
						store.proxy.extraParams.path = me.selection.folder;
						store.proxy.extraParams.extention = me.field.extention.getValue();
						store.load();

						me.field.path.setValue(me.selection.folder);
					}
					else if (i_record.get("ext") == me.validSelectionExtention) {

						var f_select = me.onSelect || Ext.emptyFn;
						me.close();

						f_select(ip2.cleanPath(i_record.get("id")));
					}
				}
			}
		});
		me.items.push(me.panel.objectGrid);

		// Folder navigator
		me.panel.navigator = Ext.create("Ext.tree.Panel", {
			region: "west",
			width: 200,
			split: true,
			collapsible: false,
			floatable: false,
			xtype: "treepanel",
			lines: false,
			useArrows: true,
			singleExpand: true,
			autoScroll: true,
			animate: true,
			enableDD: true,
			containerScroll: true,
			rootVisible: false,
			frame: false,
			store: Ext.create("Ext.data.TreeStore", {
				folderSort: true,
				proxy: {
					type: "ajax",
					url: "/ip2-services/" + ip2.ifsExplorerService
				},
				root: {
					id: "",
					expanded: false
				}
			}),
			listeners: {
				select: function(rm, record, index, eOpts) {
					var i_button = me.down("#dmdModel-button-ok");
					if (record.get("ext") == "folder") {
						var store = me.panel.objectGrid.store;
						me.selection.folder = record.get("id");
						store.load();
					}
					if (i_button && me.field.extention) {
						var s_extension = me.field.extention.getValue();
						if (s_extension === "") {
							i_button.enable();
						}
						else {
							if (record.get("ext") == s_extension) {
								i_button.enable();
							}
							else {
								i_button.disable();
							}
						}
					}
				},
				beforeload: {
					fn: function(store, operation) {

						var node = operation.node;
						var s_path = "";
						if (!node.isRoot()) {
							if (!node.parentNode.isRoot()) {
								s_path = node.get("path");
								if (node.get("id").indexOf(s_path) != -1) {
									s_path = node.get("id");
								}
								else {
									s_path = node.get("parentId") + node.get("path");
								}
							}
							else {
								s_path = node.get("path");
								if (node.get("id").indexOf(s_path) != -1) {
									s_path = node.get("id");
								}
								else {
									s_path = node.get("path");
								}
							}
							me.selection.folder = s_path;
						}
						else {
							s_path = me.selection.folder || me.path || "/";
						}

						var i_proxy = store.getProxy();
						var o_params = operation.getParams();

						var s_extensions = "folder";
						if (me.field.extention) {
							s_extensions = me.field.extention.getValue();
						}
						if (me.field.path) {
							me.field.path.setValue(s_path);
						}

						Ext.Object.merge(o_params, {
							func: "listdir",
							extension: s_extensions,
							path: s_path,
							sort: true,
							node: null
						});
						delete operation.node;
					}
				}
			}
		});
		me.items.push(me.panel.navigator);

		// control with buttons, file extention dropdown
		me.fileExtention = (me.fileExtention) ? me.fileExtention : [{ ext: "", desc: "All Files (*.*)" }];
		me.buttonText = (me.buttonText) ? me.buttonText : { ok: "OK" };

		me.panel.controlFields = Ext.widget("form", {
			border: 0,
			layout: {
				type: "anchor"
			},
			listeners: {
				validityChange: {
					fn: function(i_form, b_valid) {

						var i_button = me.down("#dmdModel-button-ok");

						if (i_button) {
							i_button[b_valid ? "enable" : "disable"]();
						}
					}
				}
			}
		});

		var controlHeight = 72;
		if (me.saveAction) {
			controlHeight += 30;
			me.field.filename = Ext.widget("textfield", {
				name: "filename",
				fieldLabel: ip2.i18n("filename"),
				allowBlank: false,
				anchor: "100%",
				validator: function(value) {

					var i_field = this;
					var value = i_field.getValue();
					var b_valid = true;
					var s_pop = value.split(".").pop();
					var s_extension = me.field.extention.getValue();

					b_valid = s_pop == s_extension;

					if (!b_valid) {
						return "This must have the same extention";
					}
					return b_valid;
				}
			});
			me.panel.controlFields.add(me.field.filename);

			me.panel.controlFields.setHeight(60);
		}

		if (!Ext.ClassManager.isCreated("fileExtention")) {
			Ext.define("fileExtention", {
				extend: "Ext.data.Model",fields: [
					{
						type: "string",
						name: "ext"
					},
					{
						type: "string",
						name: "desc"
					}
				]
			});
		}

		var ds = Ext.create("Ext.data.Store", {
			model: "fileExtention",data: me.fileExtention
		});
		me.field.extention = Ext.create("Ext.form.field.ComboBox", {
			displayField: "desc",
			valueField: "ext",
			store: ds,
			queryMode: "local",
			typeAhead: true,
			anchor: (me.saveAction) ? "100%" : null,
			hideLabel: (me.saveAction) ? false : true,
			fieldLabel: (me.saveAction) ? ip2.i18n("saveAsType") : null,
			style: (me.saveAction) ? null : { float: "right" },
			listeners: {
				render: function(box) {
					box.setValue(me.fileExtention[0].ext);
				},
				select: function(box, i_record) {
					var store = me.panel.objectGrid.store;
					store.proxy.extraParams.path = me.selection.folder;
					store.proxy.extraParams.extention = i_record.get("ext");
					store.load();
				}
			}
		});
		me.panel.controlFields.add(me.field.extention);

		me.panel.control = Ext.create("Ext.panel.Panel", {
			region: "south",
			height: controlHeight,
			split: true,
			collapsible: false,
			floatable: false,
			bodyStyle: "padding:10px;",
			items: [
				me.panel.controlFields,
				{
					xtype: "panel",
					border: 0,
					items: [
						{
							xtype: "button",
							text: "Cancel",
							type: "button",
							handler: function() {
								me.close();
								Ext.getBody().unmask();
							},
							style: { float: "right" }
						},
						{
							xtype: "button",
							text: (me.buttonText.ok) ? me.buttonText.ok : "OK",
							type: "button",
							itemId: "dmdModel-button-ok",
							style: {
								float: "right",
								"margin-right": "10px"
							},
							handler: function() {
								if (me.saveAction) {
									if (me.field.filename.isValid()) {
										var filename = me.field.filename.getValue();
										var ext = "";
										if (filename.lastIndexOf('.') == -1) {
											filename += "." + me.field.extention.getValue();
										}
										else {
											var found = false;
											ext = filename.substring(filename.lastIndexOf(".") + 1);
											for (var i = 0; i < me.fileExtention.length; i++) {
												if (me.fileExtention[i].ext == ext) {
													found = true;
													break;
												}
											}
											if (!found) {
												filename += "." + me.field.extention.getValue();
											}
										}
										var fullname = me.field.path.getValue() + "/" + filename;

										// validate if file already exists
										Ext.Ajax.request({
											url: "/ip2-services/" + ip2.ifsExplorerService,
											params: {
												func: "checkstmf",name: fullname
											},
											success: function(response) {

												var result = Ext.decode(response.responseText, true) || {};

												if (result.exists) {

													ip2.messageBox({
														title: ip2.i18n("replaceExisting"),
														message: Ext.String.format(ip2.i18n("fileAlreadyExists"), fullname),
														yesText: ip2.i18n({
															da: "Ok",
															en: "Ok"
														}),
														yesFn: function () {
															me.onOk(fullname);
															me.close();
														}
													});
												}
												else {
													me.onOk(fullname);
													me.close();
												}
											}
										});
									}
								}
								else {
									if (me.panel.objectGrid.rendered) {
										var a_records = me.panel.objectGrid.getSelection();
										var a_nodes = me.panel.navigator.getSelection();
										var s_path = "";
										if (a_records.length > 0) {
											var i_record = a_records[0];
											if (i_record.get("ext") == me.validSelectionExtention) {
												s_path = i_record.get("id");
											}
										}
										else {
											if (a_nodes.length > 0) {
												var i_node = a_nodes[0];
												if (i_node.get("ext") == me.validSelectionExtention) {
													s_path = i_node.get("id");
												}
											}
										}
										if (s_path) {
											var f_select = me.onSelect || Ext.emptyFn;
											me.close();
											f_select(s_path);
										}
									}
								}
							}
						}
					]
				}
			]
		});
		me.items.push(me.panel.control);

		me.callParent();
	},
	onOk: function() {
	},
	onSelect: function() {
	}
});
