Ext.ns('Nexts.module');

Nexts.module.PreferencesModule = Ext.extend(Nexts.module.WindowModule, {
	
	id: 'Nexts.module.PreferencesModule',
	
	iconCls: 'pref-icon',

	shortcutIconCls: 'pref-shortcut',

	title: 'Preferences',
	tooltip: '<b>Preferences</b><br/>Allows you to modify your desktop',
	backButtonText: 'Back',
	nextButtonText: 'Next',
	closeButtonText: 'Close',
	
	configId: 'desktop.config',

	innerWallpapers: [
		[ 'Blank', 				'blank.gif',				'blank.gif'				],
		[ 'Nexts', 				'nexts.gif',				'nexts.gif'				],
		[ 'Blue Swirl', 		'blue-swirl.jpg',			'blue-swirl.jpg'		],
		[ 'Colorado Farm', 		'colorado-farm.jpg',		'colorado-farm.jpg'		],
		[ 'Emotion', 			'emotion.jpg',				'emotion.jpg'			],
		[ 'Fields of Peace', 	'fields-of-peace.jpg',		'fields-of-peace.jpg'	],
		[ 'Fresh Morning', 		'fresh-morning.jpg',		'fresh-morning.jpg'		],
		[ 'Ladybuggin', 		'ladybuggin.jpg',			'ladybuggin.jpg'		],
		[ 'Summer', 			'summer.jpg',				'summer.jpg'			]
	],

	windowConfig: {
		minWidth: 600,
		minHeight: 380,
		width: 800,
		height: 500
	},

	cardHistory: [
		'pref-card-nv' // default
	],
	
	contentPanel: null,

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

		this.addEvents('save');
		
		this.on({
			close: function() {
				this.saveConfig();
				this.fireEvent('save', this.app.desktop.config);
				delete this.contentPanel;
			},
			scope: this
		});
		
		if (!this.innerWallpaperPath) {
			this.innerWallpaperPath = '';
			if (Ext.BLANK_IMAGE_URL) {
				var i = Ext.BLANK_IMAGE_URL.lastIndexOf('/');
				if (i >= 0) {
					this.innerWallpaperPath = Ext.BLANK_IMAGE_URL.substring(0, i) + '/nexts/wallpapers/';
				}
			}
		};

		for (var i = 0, ws = this.innerWallpapers; i < ws.length; i++) {
			ws[i][1] = this.innerWallpaperPath + ws[i][1];
			ws[i][2] = this.innerWallpaperPath + 'thumbnails/' + ws[i][2];
		}
		this.wallpapers = this.innerWallpapers.concat(this.wallpapers || []);
	},

	saveConfig: function() {
		if (this.configId) {
			Ext.state.Manager.set(this.configId, Ext.encode(this.app.desktop.config));
		}
	},

	createChild: function() {
		var ps = [];
		
		this.cardConfig = this.cardConfig || {};
	
		if (this.cardConfig.shortcuts !== false) {
			ps.push(new Nexts.module.PreferencesModule.Shortcuts({owner: this, id: 'pref-card-sc'}));
		}
		if (this.cardConfig.quickStart !== false) {
			ps.push(new Nexts.module.PreferencesModule.QuickStart({owner: this, id: 'pref-card-qs'}));
		}
		if (this.cardConfig.autoRun !== false) {
			ps.push(new Nexts.module.PreferencesModule.AutoRun({owner: this, id: 'pref-card-ar'}));
		}
		if (this.cardConfig.appearance !== false) {
			ps.push(new Nexts.module.PreferencesModule.Appearance({owner: this, id: 'pref-card-ap'}));
		}
		if (this.cardConfig.background !== false) {
			ps.push(new Nexts.module.PreferencesModule.Background({owner: this, id: 'pref-card-bg'}));
		}
		
		var np = new Nexts.module.PreferencesModule.NavPanel({owner: this, id: 'pref-card-nv', panels: ps});
		
		var its = [ np ].concat(ps);
		
		this.contentPanel = new Ext.Panel({
			activeItem: 0,
			border: false,
			cls: 'pref-content-panel',
			items: its,
			layout: 'card',
			tbar: [{
				disabled: true,
				handler: this.navHandler.createDelegate(this, [-1]),
				scope: this,
				text: this.backButtonText
			},{
				disabled: true,
				handler: this.navHandler.createDelegate(this, [1]),
				scope: this,
				text: this.nextButtonText
			}]
		});
			
		return this.contentPanel;
	},

	handleButtonState: function() {
		var cards = this.cardHistory, activeId = this.contentPanel.getLayout().activeItem.id,
			items = this.contentPanel.getTopToolbar().items, back = items.get(0), next = items.get(1);
		
		for (var i = 0, len = cards.length; i < len; i++) {
			if (cards[i] === activeId) {
				if (i <= 0) {
					back.disable();
					next.enable();
				}
				else if (i >= (len-1)) {
					back.enable();
					next.disable();
				}
				else{
					back.enable();
					next.enable();
				}
				break;
			}
		}
	},
	
	navHandler: function(index) {
		var cards = this.cardHistory,
			activeId = this.contentPanel.getLayout().activeItem.id,
			nextId;
		
		for (var i = 0, len = cards.length; i < len; i++) {
			if (cards[i] === activeId) {
				nextId = cards[i+index];
				break;
			}
		}
		
		this.contentPanel.getLayout().setActiveItem(nextId);
		this.handleButtonState();
	},
	
	viewCard: function(card) {
		this.contentPanel.getLayout().setActiveItem(card);
		if (this.cardHistory.length > 1) {
			this.cardHistory.pop();
		}
		this.cardHistory.push(card);
		this.handleButtonState();
	}
});



Nexts.module.PreferencesModule.NavPanel = function(config) {
	this.owner = config.owner;
	
	var lis = [];
	for (var i = 0; i < config.panels.length; i++) {
		var p = config.panels[i];
		lis.push('<li>'
			+ '<img src="' + Ext.BLANK_IMAGE_URL + '" class="' + p.iconCls + '"/>' 
			+ '<a id="view-' + p.id + '" href="#">' + p.title + '</a><br/>'
			+ '<span>' + p.description + '</span>'
			+ '</li>'
		);
	}
	
	Nexts.module.PreferencesModule.NavPanel.superclass.constructor.call(this, {
		autoScroll: true,
		bodyStyle: 'padding:15px',
		border: false,
		html: '<ul id="pref-nav-panel">' + lis.join('') + '</ul>',
		id: config.id
	});
};

Ext.extend(Nexts.module.PreferencesModule.NavPanel, Ext.Panel, {
	afterRender: function() {
		this.body.on({
			'mousedown': {
				fn: this.doAction,
				scope: this,
				delegate: 'a'
			},
			'click': {
				fn: Ext.emptyFn,
				scope: null,
				delegate: 'a',
				preventDefault: true
			}
		});
		
		Nexts.module.PreferencesModule.NavPanel.superclass.afterRender.call(this); // do sizing calcs last
	},
	
	doAction: function(e, t) {
		e.stopEvent();
		this.owner.viewCard(t.id.substring(5));
	}
});


Nexts.module.PreferencesModule.Shortcuts = function(config) {
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var ms = Nexts.module.ModuleManager.getModules(),
		ids = this.app.desktop.config.launchers.shortcut,
		nodes = expandNodes(ms, ids);
	
	Nexts.module.PreferencesModule.Shortcuts.superclass.constructor.call(this, {
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: false,
		cls: 'pref-card pref-check-tree',
		id: config.id,
		lines: false,
		listeners: {
			'checkchange': {
				fn: onCheckChange,
				scope: this
			}
		},
		loader: new Ext.tree.TreeLoader(),
		rootVisible: false,
		root: new Ext.tree.AsyncTreeNode({
			text: '',
			children: nodes
		}),
		title: this.title
	});
	
	new Ext.tree.TreeSorter(this, {dir: "asc"});
			
	function expandNodes(ms, ids) {
		var nodes = [];
		
		for(var i in ms) {
			var m = ms[i];
			if (m.mtype != 'system' && m.mtype != 'menu') {
				nodes.push({
					checked: isChecked(m.id, ids) ? true: false,
					iconCls: m.iconCls,
					id: m.id,
					leaf: true,
					selected: true,
					text: m.title
				});
			}
		}
		
		return nodes;
	}
	
	function isChecked(id, ids) {
		for(var i = 0, len = ids.length; i < len; i++) {
			if (id == ids[i]) {
				return true;
			}
		}
	}

	function onCheckChange(node, checked) {
		if (node.leaf && node.id) {
			if (checked) {
				this.app.desktop.addShortcut(node.id, true);
			}
			else{
				this.app.desktop.removeShortcut(node.id, true);
			}
			this.owner.saveConfig();
		}
		node.ownerTree.selModel.select(node);
	}
};

Ext.extend(Nexts.module.PreferencesModule.Shortcuts, Ext.tree.TreePanel, {
	iconCls : 'icon-pref-shortcuts',

	title		: 'Shortcuts',
	description	: 'Choose which applications appear in your shortcuts.'
});



Nexts.module.PreferencesModule.AutoRun = function(config) {
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var ms = Nexts.module.ModuleManager.getModules(),
		ids = this.app.desktop.config.launchers.autorun,
		nodes = expandNodes(ms, ids);
				
	Nexts.module.PreferencesModule.AutoRun.superclass.constructor.call(this, {
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: false,
		cls: 'pref-card pref-check-tree',
		id: config.id,
		lines: false,
		listeners: {
			'checkchange': {
				fn: onCheckChange,
				scope: this
			}
		},
		loader: new Ext.tree.TreeLoader(),
		rootVisible: false,
		root: new Ext.tree.AsyncTreeNode({
			text: '',
			children: nodes
		}),
		title: this.title
	});
	
	new Ext.tree.TreeSorter(this, {dir: "asc"});
			
	function expandNodes(ms, ids) {
		var nodes = [];
		
		for (var i in ms) {
			var m = ms[i];
			if (m.mtype != 'system' && m.mtype != 'menu' && m.autorun !== false) {
				nodes.push({
					checked: isChecked(m.id, ids) ? true: false,
					iconCls: m.iconCls,
					id: m.id,
					leaf: true,
					selected: true,
					text: m.title
				});
			}
		}
		
		return nodes;
	}
	
	function isChecked(id, ids) {
		for(var i = 0, len = ids.length; i < len; i++) {
			if (id == ids[i]) {
				return true;
			}
		}
	}

	function onCheckChange(node, checked) {
		if (node.leaf && node.id) {
			if (checked) {
				this.app.desktop.addAutoRun(node.id, true);
			}
			else{
				this.app.desktop.removeAutoRun(node.id, true);
			}
			this.owner.saveConfig();
		}
		node.ownerTree.selModel.select(node);
	}

};

Ext.extend(Nexts.module.PreferencesModule.AutoRun, Ext.tree.TreePanel, {
	iconCls: 'icon-pref-autorun',
	
	title		: 'Auto Run Applications',
	description	: 'Choose which applications open automatically once logged in.'
});


Nexts.module.PreferencesModule.QuickStart = function(config) {
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var ms = Nexts.module.ModuleManager.getModules(),
		ids = this.app.desktop.config.launchers.quickstart,
		nodes = expandNodes(ms, ids);
				
	Nexts.module.PreferencesModule.QuickStart.superclass.constructor.call(this, {
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: false,
		cls: 'pref-card pref-check-tree',
		id: config.id,
		lines: false,
		listeners: {
			'checkchange': {
				fn: onCheckChange,
				scope: this
			}
		},
		loader: new Ext.tree.TreeLoader(),
		rootVisible: false,
		root: new Ext.tree.AsyncTreeNode({
			text: '',
			children: nodes
		}),
		title: this.title
	});
	
	new Ext.tree.TreeSorter(this, {dir: "asc"});
			
	function expandNodes(ms, ids) {
		var nodes = [];
		
		for(var i in ms) {
			var m = ms[i];
			if (m.mtype != 'system' && m.mtype != 'menu') {
				nodes.push({
					checked: isChecked(m.id, ids) ? true: false,
					iconCls: m.iconCls,
					id: m.id,
					leaf: true,
					selected: true,
					text: m.title
				});
			}
		}
		
		return nodes;
	}
	
	function isChecked(id, ids) {
		for(var i = 0, len = ids.length; i < len; i++) {
			if (id == ids[i]) {
				return true;
			}
		}
	}
	
	function onCheckChange(node, checked) {
		if (node.leaf && node.id) {
			if (checked) {
				this.app.desktop.addQuickStartButton(node.id, true);
			}
			else{
				this.app.desktop.removeQuickStartButton(node.id, true);
			}
			this.owner.saveConfig();
		}
		node.ownerTree.selModel.select(node);
	}
	
};

Ext.extend(Nexts.module.PreferencesModule.QuickStart, Ext.tree.TreePanel, {
	iconCls: 'icon-pref-quickstart',
	
	title		: 'Quick Start Applications',
	description	: 'Choose which applications appear in your Quick Start panel.'
});



Nexts.module.PreferencesModule.Appearance = function(config) {
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var desktop = this.app.getDesktop();
	
	var store = new Ext.data.SimpleStore({
		fields: Nexts.Theme.fields,
		data: Nexts.Theme.data,
		listeners: {
			'load': {
				fn: function(store, records) {
					if (records) {
						//defaults.setTitle(this.themesText.format(records.length));
						
						var css = this.app.desktop.config.styles.theme.css;
						if (css) {
							view.select('theme-' + css);
						}
					}
				},
				scope: this,
				delay: 500
			}
		}
	});
	
	this.store = store;
	
	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
			'<div class="pref-view-thumb-wrap" id="theme-{css}">',
				'<div class="pref-view-thumb"><img src="' + Ext.BLANK_IMAGE_URL + '" class="{thumbCls}" title="{name}" /></div>',
			'<span>{shortName}</span></div>',
		'</tpl>',
		'<div class="x-clear"></div>'
	);

	var view = new Ext.DataView({
		autoHeight:true,
		cls: 'pref-thumbnail-view',
		emptyText: this.noThemesText,
		itemSelector:'div.pref-view-thumb-wrap',
		singleSelect: true,
		overClass:'x-view-over',
		prepareData: function(data) {
			data.shortName = String.ellipsiz(data.name, 17);
			return data;
		},
		store: store,
		tpl: tpl
	});
	view.on('selectionchange', onSelectionChange, this);
	
	var themes = new Ext.Panel({
		id: 'pref-theme-view',
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: true,
		height: 135,
		items: view
	});
	
	var chkTransparency = new Ext.form.Checkbox({
		boxLabel: this.taskbarTransparencyText,
		checked: this.app.desktop.config.styles.transparency ? true: false
	});
	chkTransparency.on('check', toggleTransparency, this);
	
	var dl = this.app.desktop.config.layout;
	var layout = new Ext.Panel({
		id: 'pref-layout-view',
		border: false,
		height: 180,
		layout: 'table',
		layoutConfig: {
			columns: 2
		},
		items: [{
			colspan: 2,
			border: false,
			bodyStyle: 'padding: 0px 0px 2px 0px',
			html: this.layoutText
		}, {
			xtype: 'radio',
			name: 'desktoplayout',
			boxLabel: this.windowLayoutText,
			inputValue: 'desktop',
			checked: dl == 'desktop',
			listeners: {
				check: toggleLayout,
				scope: this
			}
		}, {
			xtype: 'radio',
			name: 'desktoplayout',
			boxLabel: this.frameLayoutText,
			inputValue: 'frame',
			checked: dl == 'frame',
			listeners: {
				check: toggleLayout,
				scope: this
			}
		}, {
			border: false,
			width: 220,
			html: '<img class="pref-dl-desktop" src="'+Ext.BLANK_IMAGE_URL+'" width="192" height="105" border="0" alt="" />'
		}, {
			border: false,
			width: 220,
			html: '<img class="pref-dl-frame" src="'+Ext.BLANK_IMAGE_URL+'" width="192" height="105" border="0" alt="" />'
		}, chkTransparency, {
			border: false
		}]
	});
	
	Nexts.module.PreferencesModule.Appearance.superclass.constructor.call(this, {
		id: config.id,
		cls: 'pref-card',
		border: false,
		autoScroll: true,
		items: [
			themes,
			layout
		],
		title: this.title
	});
	
	function onSelectionChange(view, sel) {
		if (sel.length > 0) {
			var c = this.app.desktop.config.styles.theme.css;
			var r = view.getRecord(sel[0]);
			var d = r.data;
			
			if (c != d.css) {
				desktop.setTheme(d);
				this.owner.saveConfig();
			}
		}
	}
	
	function toggleLayout(field, checked) {
		if (checked === true) {
			desktop.config.layout = field.inputValue;
			this.owner.saveConfig();
		}
	}

	function toggleTransparency(field, checked) {
		desktop.setTransparency(checked);
		this.owner.saveConfig();
	}
};

Ext.extend(Nexts.module.PreferencesModule.Appearance, Ext.Panel, {
	iconCls: 'icon-pref-appearance',
	
	title		: 'Window Color and Appearance',
	description	: 'Fine tune window color and style of your windows.',
	
	themesText: 'Themes Available ({0})',
	noThemesText: 'No themes to display',

	layoutText			: 'Desktop Layout: (*Takes effect on your next time login)',
	windowLayoutText	: 'Desktop Windows',
	frameLayoutText		: 'Frame Tabs',
	taskbarTransparencyText: 'Taskbar Transparency'
});



Nexts.module.PreferencesModule.Background = function(config) {
	this.owner = config.owner;
	this.app = this.owner.app;
	
	var desktop = this.app.getDesktop();
	
	var store = new Ext.data.SimpleStore({
		fields: [ 'name', 'image', 'thumbnail' ],
		data: this.owner.wallpapers,
		listeners: {
			'load': {
				fn: function(store, records) {
					if (records) {
						//defaults.setTitle(this.wallpapersText.format(records.length));
						
						var image = this.app.desktop.config.styles.wallpaper.image;
						if (image) {
							view.select('wallpaper-' + image);
						}
					}
				},
				scope: this,
				delay: 500
			}
		}
	});
	
	this.store = store;
	
	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
			'<div class="pref-view-thumb-wrap" id="wallpaper-{image}">',
				'<div class="pref-view-thumb"><img src="{thumbnail}" title="{name}" /></div>',
			'<span>{shortName}</span></div>',
		'</tpl>',
		'<div class="x-clear"></div>'
	);

	var view = new Ext.DataView({
		autoHeight:true,
		cls: 'pref-thumbnail-view',
		emptyText: this.noWallpapersText,
		itemSelector:'div.pref-view-thumb-wrap',
		singleSelect: true,
		overClass:'x-view-over',
		prepareData: function(data) {
			data.shortName = String.ellipsiz(data.name, 17);
			return data;
		},
		store: store,
		tpl: tpl
	});
	view.on('selectionchange', onSelectionChange, this);
	
	var wallpapers = new Ext.Panel({
		id: 'pref-wallpaper-view',
		autoScroll: true,
		bodyStyle: 'padding:10px',
		border: true,
		height: 135,
		items: view
	});
	
	var wpp = this.app.desktop.config.styles.wallpaper.position;
	
	var background = new Ext.Panel({
		id: 'pref-background-view',
		border: false,
		height: 140,
		bodyStyle: 'width:100%;',
		layout: 'table',
		layoutConfig: {
			columns: 2
		},
		defaults: {
			border: false,
			cellCls: 'pref-bg-cell',
			bodyStyle: 'padding:10px'
		},
		items: [{
			layout: 'table',
			layoutConfig: {
				columns: 2
			},
			defaults: {
				cellCls: 'pref-bg-cell'
			},
			items: [{
				colspan: 2,
				border: false,
				html: this.wallpaperPositionText,
				bodyStyle: 'padding-bottom:10px'
			}, {
				border: false,
				width: 80,
				html: '<img class="pref-bg-pos-tile" src="'+Ext.BLANK_IMAGE_URL+'" width="64" height="44" border="0" alt="" />'
			}, {
				border: false,
				width: 80,
				html: '<img class="pref-bg-pos-center" src="'+Ext.BLANK_IMAGE_URL+'" width="64" height="44" border="0" alt="" />'
			}, {
				xtype: 'radio',
				name: 'wallpos',
				boxLabel: this.wallpaperTileText,
				inputValue: 'tile',
				checked: wpp == 'tile',
				listeners: {
					check: togglePosition,
					scope: this
				}
			}, {
				xtype: 'radio',
				name: 'wallpos',
				boxLabel: this.wallpaperCenterText,
				inputValue: 'center',
				checked: wpp == 'center',
				listeners: {
					check: togglePosition,
					scope: this
				}
			}]
		}, {
			layout: 'table',
			layoutConfig: {
				columns: 2
			},
			defaults: {
				cellCls: 'pref-bg-cell'
			},
			items: [{
				border: false,
				margins: '0 5 5 0',
				html: this.backgroundColorText
			}, {
				border: false,
				margins: '0 0 5 5',
				html: this.shortcutFontColorText
			}, {
				xtype: 'colorpalette',
				value: this.app.desktop.config.styles.backgroundcolor,
				listeners: {
					select: function(p, hex) {
						desktop.setBackgroundColor(hex);
						this.owner.saveConfig();
					},
					scope: this
				}
			}, {
				xtype: 'colorpalette',
				value: this.app.desktop.config.styles.fontcolor,
				listeners: {
					select: function(p, hex) {
						desktop.setFontColor(hex);
						this.owner.saveConfig();
					},
					scope: this
				}
			}]
		}]
	});

	Nexts.module.PreferencesModule.Background.superclass.constructor.call(this, {
		id: config.id,
		cls: 'pref-card',
		title: this.title,
		border: false,
		autoScroll: true,
		items: [
			wallpapers,
			background
		]
	});
	
	function onSelectionChange(view, sel) {
		if (sel.length > 0) {
			var c = this.app.desktop.config.styles.wallpaper.image;
			var r = view.getRecord(sel[0]);
			var d = r.data;
			
			if (c != d.image) {
				desktop.setWallpaperImage(d.image);
				this.owner.saveConfig();
			}
		}
	}
	
	function togglePosition(field, checked) {
		if (checked === true) {
			desktop.setWallpaperPosition(field.inputValue);
			this.owner.saveConfig();
		}
	}
};

Ext.extend(Nexts.module.PreferencesModule.Background, Ext.Panel, {
	iconCls: 'icon-pref-background',

	title					: 'Desktop Background',
	description				: 'Choose from available wallpapers or colors to decorate you desktop.',

	wallpapersText			: 'Wallpapers Available ({0})',
	noWallpapersText		: 'No wallpapers to display',
	wallpaperPositionText	: 'Wallpaper position:',
	wallpaperTileText		: 'Tile',
	wallpaperCenterText		: 'Center',
	backgroundColorText		: 'Background color:',
	shortcutFontColorText	: 'Shortcut font color:'
});

/* 
 * Will ensure that the checkchange event is fired on 
 * node double click
 */
Ext.override(Ext.tree.TreeNodeUI, {
	toggleCheck: function(value) {
		var cb = this.checkbox;
		if (cb) {
			cb.checked = (value === undefined ? !cb.checked : value);
			this.fireEvent('checkchange', this.node, cb.checked);
		}
	}
});

