Ext.onReady(function() {
	Ext.History.init();
	Ext.History.on('change', function(token) {
		if (token) {
			var pnl = Ext.getCmp(token);
			treenode = Ext.getCmp('tree-panel').getRootNode().findDescendant('id', token);
			Ext.getCmp('tree-panel').fireEvent('click', treenode, null, true);
		} else {
			//Ext.getCmp('content-panel').layout.setActiveItem('welcome-panel');
		}
	});
	Ext.QuickTips.init();

		var buttonLogout = new Ext.Button({
			renderTo: 'topButtons',
			text: 'Logout',
			iconCls: 'logout',
			minWidth: 50,
			width: 65,
			cls: 'topButton',
			listeners: {
				click: function(b) {
					var conn = new Ext.data.Connection();
					conn.request({
						url: 'session.php',
						method: 'POST',
						params: {
							command: 'logout'
						},
						success: function(responseObject) {
							//alert(responseObject.responseText);      
							eval("var results = " + responseObject.responseText);
							if (results.success) {
								window.location = 'login/';
							}
						},
						failure: function() {
							Ext.Msg.alert('Status', 'Unable to logout at this time. Please try again later.');
						}
					});
				}
			}
		});
		var buttonPrefs = new Ext.Button({
			renderTo: 'topButtons',
			text: 'Preferences',
			iconCls: 'preferences',
			minWidth: 50,
			width: 95,
			cls: 'topButton',
			listeners: {
				click: function(b) {
					preferencepopup.show()
				}
			}
		});

		var shortcutBar = {
			xtype: 'panel',
			region: 'north',
			margins: '60 5 5 5',
			border: true,
			height: 28,
			id: 'shortcuts',
			tbar: {
				xtype: 'toolbar',
				id: 'shortcut_bar',
				height: 28,
				plugins: [
				new Ext.ux.ToolbarDroppable({
					createItem: function(data) {
						var itemId = data.sourceEl.attributes[data.sourceEl.attributes.length - 1].nodeValue;
						var record = data.draggedRecord;
						var newButton = new Ext.Button({
							text: data.text,
							iconCls: data.iconCls,
							itemId: itemId,
							reorderable: true,
							listeners: {
								click: function(btn) {
									var tree = Ext.getCmp('tree-panel');
									tree.fireEvent('click', tree.getNodeById(btn.itemId));
								}
							}
						});
						return newButton;
					},
					afterLayout: function() {
						this.toolbar.save();
					}
				}), new Ext.ux.ToolbarReorderer({})],
				items: [{
					xtype: 'tbspacer',
					width: 5
				},
				{
					xtype: 'label',
					text: 'My shortcuts'
				},
				{
					xtype: 'tbspacer',
					width: 5
				},
				{
					xtype: 'tbseparator'
				},
				{
					xtype: 'tbspacer',
					width: 5
				}],
				load: function() {
					var sc = SchoolDynamics.shortcuts;
					var tree = Ext.getCmp('tree-panel');
					if (sc != null) {
						for (var i = 0; i < sc.length; i++) {
							var node = tree.getNodeById(sc[i]).attributes;
							this.add({
								text: node.text,
								iconCls: node.iconCls,
								itemId: node.id,
								reorderable: true,
								listeners: {
									click: function(btn) {
										var tree = Ext.getCmp('tree-panel');
										tree.fireEvent('click', tree.getNodeById(btn.itemId));
									}
								}
							});
						}
					}
				},
				save: function() {
					var shortcutArray = new Array();
					var tbButtons = this.items.items;
					for (var i = 0; i < tbButtons.length; i++) {
						if (4 < i) {
							shortcutArray.push(tbButtons[i].itemId);
						}
					}
					Ext.Ajax.request({
						url: 'schooldynamics_data.json.php',
						params: {
							command: 'setUserShortcuts',
							shortcuts: Ext.encode(shortcutArray)
						},
						success: function(responseObject) {
							eval("var results = " + responseObject.responseText);
							if (results.success) {
								SchoolDynamics.shortcuts = results.shortcuts;
							}
						},
						failure: function() {
							Ext.Msg.alert('Status', 'Unable to save shortcut settings.');
						}
					});
				},
				listeners: {
					reordered: function(button, tbar) {
						tbar.save();
					}
				}
			}
		};

		var navTree = new Ext.tree.TreePanel({
			id: 'tree-panel',
			border: false,
			rootVisible: false,
			root: new Ext.tree.AsyncTreeNode(),
			lines: true,
			loader: new Ext.tree.TreeLoader(),
			root: new Ext.tree.AsyncTreeNode({
				expanded: true,
				children: menuArray
			}),
			listeners: {
				append: function(treePanel, parentnode, node, index) {
					if (node.attributes.type == 'branch') {
						SD.addBranch(node.id);
					}		
				},
				click: function(n, e, historyClicked, forceClick) {
					var sn = this.selModel.selNode || {}; // selNode is null on initial selection
					if (n.leaf && n.id != sn.id || forceClick) { // ignore clicks on folders and currently selected node    		
						var paths = n.attributes.path;
						Ext.each(paths, function(path) {
							jsLoader.load(path);
						});
						jsLoader.loadedCall(
						function() {
							SD.getChild(n.id).display(historyClicked);
						});
					}
				},
				render: function(tree) {
					this.dragZone = new Ext.dd.DragZone(tree.getEl(), {
						getDragData: function(e) {
							var sourceEl = e.getTarget('div.navTreeNode', 10);
							if (sourceEl) {
								d = sourceEl.cloneNode(true);
								d.id = Ext.id();
								var nodeName = d.children[d.children.length - 1].text;
								var nodeClassList = d.children[d.children.length - 2].className.split(' ');
								return {
									ddel: d,
									sourceEl: sourceEl,
									repairXY: Ext.fly(sourceEl).getXY(),
									text: nodeName,
									iconCls: nodeClassList[nodeClassList.length - 1]
								};
							}
						},
						getRepairXY: function() {
							return this.dragData.repairXY;
						}
					});
				}
			}
		});
		
		SD.viewport = new Ext.Viewport({
			layout: 'border',
			id: 'main_viewport',
			items: [
			shortcutBar,
			{
				region: 'west',
				width: 200,
				title: 'Navigation',
				collapsedTitle: 'Navigation',
				collapsedTitleCls: 'collapsedTitle',
				height: 1000,
				collapsible: true,
				margins: '0 5 25 5',
				cmargins: '0 5 25 5',
				autoScroll: true,
				border: true,
				items: navTree
			},
			{
				xtype: 'panel',
				id: 'content-panel',
				region: 'center',
				deferredRender: true,
				bodyStyle: 'background:#DFE8F6;',
				layout: 'card',
				margins: '0 5 25 0',
				border: false
			},
			{
				xtype: 'panel',
				title: 'Tools',
				region: 'east',
				width: 225,
				collapsible: true,
				margins: '0 5 25 0',
				cmargins: '0 5 25 0',
				bodyStyle: 'background-color: #cad9ec',
				padding: 6,
				id: 'tools-panel',
				layout: 'card'
			}		 ],
			renderTo: Ext.getBody()
		});

		Ext.getCmp('shortcut_bar').load();
		navTree.fireEvent('click', navTree.getRootNode().childNodes[0]);
		cookie.get();	
		

});

