Ext.ns('Nexts.module');

Nexts.module.WindowModule = Ext.extend(Nexts.module.Module, {
	mtype : 'window',

	iconCls: 'ne-module-icon',

	shortcutIconCls: 'ne-module-shortcut',

	singleton: true,
	
	configed: false,
	
	defaultWindowConfig: {
		stateful: true,
		modal: false,
		constrainHeader: true,
		closable: true,
		resizable: true,
		minimizable: true,
		maximizable: true,
		width: 800,
		height: 500,
		plain: true,
		layout: 'fit'
	},
	
	createChild: Ext.emptyFn,

	initModule: function() {
		Nexts.module.WindowModule.superclass.initModule.call(this);

		this.windowConfig = Ext.applyIf(this.windowConfig || {}, this.defaultWindowConfig);
		
		this.addEvents('launch', 'activate', 'beforeclose', 'close');
		
		this.on({
			launch: this.onLaunchModule,
			close: this.onCloseModule,
			scope: this
		});
	},

	initConfig: Ext.emptyFn,
	
	launchModule: function() {
		if (this.singleton) {
			if (this.isLaunched()) {
				this.activateModule();
				return;
			}
		}
		
		if (this.isLaunched()) {
			this.sequence = this.sequence || 0;
			this.sequence++;
			var m = this.cloneModule();
			m.id = m.id + '.' + m.sequence;
			m.createWindow();
		}
		else {
			if (!this.configed) {
				this.initConfig();
				this.configed = true;
			}
			this.createWindow();
		}
	},
	
	createWindow: function() {
		var c = this.createChild();

		var cfg = Ext.apply({}, this.windowConfig);
		
		Ext.applyIf(cfg, {
			module: this,
			iconCls: this.iconCls,
			title: this.title,
			items: [
				c
			]
		});
		
		this.window = this.app.desktop.createWindow(cfg);

		this.window.on({
			activate: function(w) {
				return this.fireEvent('activate', this, w);
			},
			beforeclose: function(w) {
				return this.fireEvent('beforeclose', this, w);
			},
			close: function(w) {
				return this.fireEvent('close', this, w);
			},
			scope: this
		});
		
		this.fireEvent('launch', this);

		this.activateModule();
	},
	
	isLaunched: function() {
		return typeof this.window == 'object';
	},
	
	activateModule: function(ani) {
		if (this.window) {
			this.app.desktop.activateWindow(this.window, ani);
		}
	},
	
	closeModule: function() {
		if (this.window) {
			this.app.desktop.closeWindow(this.window);
		}
	},
	
	onLaunchModule: Ext.emptyFn,
	
	onCloseModule: function(m) {
		delete this.window;
	}
	
});

