Ext.namespace("dlr.cmp.workSpace");
dlr.cmp.workSpace.workSpacePanel = function(cfg){
	// ------------------------------------------------
	// private properties
	// ------------------------------------------------
	var that = this;
	var settingsWin = null;
	var panelCfg = {
		layout: "border",
		frame: false,
		border: false,
		items:[{
			xtype: "panel",
			layout: "fit",
			region: "north",
			frame: false,
			border: false,
			split: false,
			bodyStyle: "padding-top:8px;background:#f4f7fc url(assets/images/blue-grad-sm.png) bottom repeat-x;",
			html: "&nbsp;<img src='assets/images/logo-sm.png' /> <div style='position:absolute;right:5px;top:5px;'><a href='mailto:joe@seemecreate.com?subject=I found a bug'>report bug</a> | <a id='helpPanelOpen' href='javascript:;'>help</a> | <a id='headerSettingsLink' href='javascript:;'>settings</a> | <a href='index.cfm?logout=true'>logout</a></div>",
			height: 45
		},{
			xtype: "panel",
			layout: "anchor",
			region: "west",
			title: "Queue Manager",
			frame: false,
			border: false,
			split: true,
			hidden: false,
			collapsible: true,
			width: 220,
			tbar:[/*{
					xtype: "button",
					cls: "x-btn-icon",
					icon: "assets/icons/page_save.png",
					tooltip: "Save Queue",
					disabled: true,
					handler: saveQueue
				},*/{
					xtype: "button",
					cls: "x-btn-icon",
					icon: "assets/icons/picture_go.png",
					tooltip: "Start Queue",
					disabled: true,
					handler: startQueue
				},{
					xtype: "button",
					cls: "x-btn-icon",
					icon: "assets/icons/server_compressed.png",
					tooltip: "Archive Finished Items",
					disabled: true,
					handler: archive
				},{
					xtype: "button",
					cls: "x-btn-icon",
					icon: "assets/icons/delete.png",
					tooltip: "Clear Queue",
					disabled: true,
					handler: clearQueue
				},"-",{
					xtype: "button",
					cls: "x-btn-icon",
					icon: "assets/icons/page_save.png",
					tooltip: "Save Queue items",
					disabled: false,
					handler: saveQueue
				}],
			items:[{
				id: "queueGridzz",
				xtype: "queueGrid"
			}]
		},{
			xtype: "tabpanel",
			region: "center",
			frame: false,
			border: false,
			split: true,
			activeTab: 0,
			enableTabScroll: true,
			tbar:[{
					text: 'Find Flickr Photos',
					iconCls:'new-tab',
					icon: "assets/icons/tab_go.png",
					handler: addFlickrMemberPanel
			}],
			items:[{
				xtype: "panel",
				id: "dlrConsole",
				frame: false,
				border: false,
				layout: "anchor",
				title: "Console",
				bodyStyle: "padding:20px;background:transparent url(assets/images/grass.gif) bottom repeat-x;",
				autoScroll: true,
				items:[{
					xtype: "panel",
					frame: false,
					border: false,
					bodyStyle: "margin-bottom:20px;",
					html: "<h1>Welcome to Fuisti, let's get started.</h1><p>This is where you can manage your archives and read any system messages. The console will become more functional as features are released.</p>"
				},{
					xtype: "consolePanel",
					id: "archiveListPanel",
					frame: false,
					border: false,
					which: "archives",
					title: "Archives"
				}]
			}],
			listeners: {
				"tabchange": function(cmp){
					if (cmp.getActiveTab().getId() == "dlrConsole"){
						var consoles = cmp.findByType("consolePanel");
						Ext.each(consoles, (function(itm, idx, len){
							itm.load({
								url: "console.cfm?which=" + itm.which + "&r=" + Math.random(),
								disableCaching: true
							});
						}));
					}
				} // end show
			} // end listeners
		},{
			xtype: "panel",
			layout: "anchor",
			region: "east",
			title: "<img src='assets/icons/help.png' align='left' /> Help",
			split: true,
			hidden: false,
			collapsible: true,
			collapsed: true,
			width: 300,
			hasLoaded: false,
			items:[{
				xtype: "panel",
				anchor: "100% 0",
				frame: false,
				border: false,
				bodyStyle: "padding:20px;background:transparent url(assets/images/grass.gif) bottom repeat-x;",
				autoScroll: true
			}],
			listeners:{
				"expand": function(cmp){
					var innerCmp = cmp.findByType("panel")[0];
					innerCmp.getUpdater().un("update", helpUpdaterSetEvents, innerCmp, innerCmp);
					innerCmp.getUpdater().on("update", helpUpdaterSetEvents, innerCmp, innerCmp);
					if (!cmp.hasLoaded){
						cmp.hasLoaded = true;
						innerCmp.load({
							url: "help.cfm?r=" + Math.random()
						});
					}
				}
			} // end listeners
		}]
	};
	var headerSettingsLink = null;
	var helpPanelOpen = null;
	// ------------------------------------------------
	// private functions
	// ------------------------------------------------
	function getCmps(){
		return {
			queueOwnerCt: that.items.get(1),
			//queueBbarSaveBtn: that.items.get(1).getTopToolbar().items.get(0),
			queueBbarStartBtn: that.items.get(1).getTopToolbar().items.get(0),
			queueBbarArchiveBtn: that.items.get(1).getTopToolbar().items.get(1),
			queueBbarDeleteBtn: that.items.get(1).getTopToolbar().items.get(2),
			queueGrid: that.items.get(1).items.get(0),
			tabPanelOwnerCt: that.items.get(2),
			helpOwnerCt: that.items.get(3)
		};
	}; // end getCmps
	function helpUpdaterSetEvents(){
		var questionLnks = Ext.DomQuery.select(".helpQuestion", this.getEl().dom);
		var backLnks = Ext.DomQuery.select(".helpBack", this.getEl().dom);
		var pnl = this;
		Ext.each(questionLnks, (function(itm, idx, len){
			Ext.get(itm).on("click", (function(){
				pnl.load({
					url: "help.cfm?r=" + Math.random() + "&question=" + itm.getAttribute("id") 
				});
			}));
		}));
		Ext.each(backLnks, (function(itm, idx, len){
			Ext.get(itm).on("click", (function(){
				pnl.load({
					url: "help.cfm?r=" + Math.random()
				});
			}));
		}));
	}; // end helpUpdaterSetEvents
	function addFlickrMemberPanel(){
		var tabPanel = getCmps().tabPanelOwnerCt;
		var queueOwnerCt = getCmps().queueOwnerCt;
		tabPanel.add({
			xtype: "flickrMemberPanel",
			workSpacePanel: that,
			queueOwnerCt: queueOwnerCt
		});
		queueOwnerCt.show();
		that.doLayout();
		tabPanel.activate(tabPanel.items.get(tabPanel.items.getCount() - 1));
	}; // end addFlickrMemberPanel
	function clearQueue(){
		var queueOwnerCt = getCmps().queueOwnerCt;
		var grid = queueOwnerCt.findByType("queueGrid")[0];
		//var selected = grid.getSelections();
		var store = grid.getStore();
		//Ext.each(selected, (function(itm, idx, len){
			//store.remove(itm);
		//}));
		store.removeAll();
	}; // end clearQueue
	function setEvents(){
		if (!headerSettingsLink) {
			headerSettingsLink = Ext.get("headerSettingsLink");
		}
		headerSettingsLink.un("click", headerSettingFn);
		headerSettingsLink.on("click", headerSettingFn);
		if (!helpPanelOpen) {
			helpPanelOpen = Ext.get("helpPanelOpen");
		}
		helpPanelOpen.un("click", helpPanelOpenFn);
		helpPanelOpen.on("click", helpPanelOpenFn);

		getCmps().queueGrid.getStore().un("add", tbarBtnEnable);
		getCmps().queueGrid.getStore().on("add", tbarBtnEnable);

		getCmps().queueGrid.getStore().un("remove", tbarBtnDisable);
		getCmps().queueGrid.getStore().on("remove", tbarBtnDisable);

		getCmps().queueGrid.getStore().un("clear", tbarBtnDisable);
		getCmps().queueGrid.getStore().on("clear", tbarBtnDisable);
		// set initial state
		if (getCmps().queueGrid.getStore().getCount())
			tbarBtnEnable();
	}; // setEvents
	function tbarBtnEnable(){
		var queueGrid = getCmps().queueGrid;
		//var store = getCmps().queueGrid.getStore();
		getCmps().queueBbarStartBtn.enable();
		getCmps().queueBbarArchiveBtn.enable();
		getCmps().queueBbarDeleteBtn.enable();
	}; // end tbarBtnEnable
	function tbarBtnDisable(){
		var queueGrid = getCmps().queueGrid;
		var store = getCmps().queueGrid.getStore();
		if (!store.getCount()){
			getCmps().queueBbarStartBtn.disable();
			getCmps().queueBbarArchiveBtn.disable();
			getCmps().queueBbarDeleteBtn.disable();
			//saveQueue(); // save ?
		}
	}; // end tbarBtnDisable
	function headerSettingFn(){
		settingsWin = settingsWin || new dlr.cmp.workSpace.settingsWindow();
		settingsWin.show();
	}; // end headerSettingFn
	function helpPanelOpenFn(){
		//getCmps().helpOwnerCt.setWidth((Ext.getBody().getWidth() * 0.33));
		getCmps().helpOwnerCt.toggleCollapse();
	}; // end helpPanelOpenFn
	function saveQueue(){
		var queueData = getCmps().queueGrid.getStore();//Ext.getCmp("queueGridzz").getStore().data.items;
		var queueDataArr = [];
		var queueId = layout.getQueueStore().getCount() ? layout.getQueueStore().getAt(0).data.queueid : "";
		var data = {};
		var queueGrid = getCmps().queueGrid;
		var store = queueGrid.getStore();//Ext.getCmp("queueGridzz").getStore();
		//var status = queueGrid.getBottomToolbar().items.get(0);

		queueData.each((function(record){
			if (record.get("progress") != 1){
				record.set("progress", 0);
			}
			queueDataArr.push(record.data);
		}));
		data = {queueDataArr: queueDataArr, queueId: queueId};
		//status.showBusy();
		Ext.Ajax.request({
			url: 'queueHelper.cfc',
			params: {
				method: "saveQueue",
				data: Ext.encode(data)
			},
			success: (function(response, options){
				var response = Ext.decode(response.responseText);
				if (response.status){
					//Ext.Msg.alert("", "Queue Saved.");
					store.commitChanges();
					//status.clearStatus();
					//status.setStatus({text: "Ready"});
					queueGrid.fireEvent("save");
				}
			}),
			failure: (function(){
				alert("fail");
			})
		});
	}; // end saveQueue
	function startQueue(){
		var startIndex = 0;
		saveQueue();
		nextQueue(startIndex);
	}; // end startQueue
	function nextQueue(idx){
		var idx = idx;
		var store = getCmps().queueGrid.getStore();//Ext.getCmp("queueGridzz").getStore();
		var record = store.getAt(idx);
		var isLast = (idx == store.getCount()) ? true : false;
		var recsLeft = store.getCount() - idx;
		var ldMsk = null;
		//var status = getCmps().queueGrid.getBottomToolbar().items.get(0);		var ldMsk = null;

		if (!ldMsk){
			ldMsk = new Ext.LoadMask(getCmps().queueOwnerCt.body, {msg: "Working..."});
		}
		if (!record){
			//Ext.Msg.alert("", "Queue Has Finished, Check the Console to Get Your Photos.");
			store.commitChanges();
			//status.clearStatus();
			//status.setStatus({text: "Ready"});
			ldMsk.hide();
			return;
		}
		if (!record.get("progress")){
			store.getAt(idx).set("progress", 2);
			store.getAt(idx).commit();
			//status.showBusy();
			ldMsk.show();
			Ext.Ajax.request({
				url: 'queueHelper.cfc',
				params: {
					method: "transfer",
					data: '{id: "'+record.data.id+'", secret: "'+record.data.secret+'"}'
				},
				success: (function(response, options){
					var response = Ext.decode(response.responseText);
					if (response.status){
						store.getAt(idx).set("progress", 1);
						store.getAt(idx).commit();
					}
					else{
						store.getAt(idx).set("progress", 3);
						store.getAt(idx).commit();
					}
					idx++;
					nextQueue(idx);
				}),
				failure: (function(response, options){
					alert("");
				})
			});
		}
		else{
			idx++;
			nextQueue(idx);
		}
	}; // end nextQueue
	function archive(){
		//var status = getCmps().queueGrid.getBottomToolbar().items.get(0);
		var store = getCmps().queueGrid.getStore();//Ext.getCmp("queueGridzz").getStore();
		if (store.getCount()){
			Ext.Msg.prompt('Name', 'Enter a name for the archive:', function(btn, text){
				if (btn == 'ok'){
					//status.showBusy();
					Ext.Ajax.request({
						url: 'queueHelper.cfc',
						params: {
							method: "createArchive",
							data: '{queueId: "'+layout.getQueueStore().getAt(0).get('queueid')+'", archiveName: "'+text+'"}'
						},
						success: (function(response, options){
							var response = Ext.decode(response.responseText);
							if (response.status)
								Ext.getCmp("archiveListPanel").load({url: "console.cfm?which=archives"});
							else{			
								Ext.Msg.show({
									title: "",
									msg: "Only 5 archives are allowed at this time.",   
									buttons: Ext.Msg.OK,
									icon: Ext.MessageBox.WARNING
								});
							}
							//status.clearStatus();
							//status.setStatus({text: "Ready"});
						}),
						failure: (function(response, options){
							alert("");
						})
					});
				}
			});
		}

	}; //end archive
	// ------------------------------------------------
	// public properties
	// ------------------------------------------------
	// ------------------------------------------------
	// public methods
	// ------------------------------------------------
	// ------------------------------------------------
	// constructor code
	// ------------------------------------------------
	Ext.apply(this, cfg);
	// apply private cfgs
	Ext.apply(this, panelCfg);
	dlr.cmp.workSpace.workSpacePanel.superclass.constructor.call(this, cfg);
	// events
	that.on("afterlayout", setEvents);
};
Ext.extend(dlr.cmp.workSpace.workSpacePanel, Ext.Panel);
Ext.reg("workSpacePanel", dlr.cmp.workSpace.workSpacePanel);