AP.SearchLayout = Class.create({
	initialize: function(opts) {
		this.opts = Object.extend({
			anonymous: false,
			selectedCount: 0,
			validateSelectedCount: true,
			navPanelSelector: ".nav-panel",
			enableStickyScroll: false
		}, opts || {});

		this.resultMenu = this.CreateResultMenu();
		this.compilationAction = this.CreateCompilationsMenu();
		this.leftViewAction = this.CreateLeftViewMenu();
		if (!this.opts.anonymous) {
			this.rightViewAction = this.CreateRightViewMenu();
			this.folderMenu = this.CreateFolderMenu();
			this.masterRequestMenu = this.CreateMasterRequestMenu();
			this.screenerRequestMenu = this.CreateScreenerRequestMenu();
		}

		Ext.onReady(this.hookMenus.bind(this));
		if (this.opts.validateSelectedCount)
			document.observe("selecteditemscount:changed", this.UpdateSelectedItemCount.bindAsEventListener(this));
	},

	showMenu: function(event) {
		this.show(event.element());
	},

	hookMenus: function() {
		//		if($("searchResultsRoot"))
		//			$("searchResultsRoot").observe('contextmenu', ShowSearchHitMenu);

		Event.observe(this.opts.compilationsMenu, "click", this.showMenu.bind(this.compilationAction));

		this.resultMenu.render(); //so that the globalSlectedItemNum div will be available
		for (var i = 0; i < this.opts.searchActions.length; i++) {
			if ($(this.opts.searchActions[i]))
				Event.observe(this.opts.searchActions[i], "click", this.showMenu.bind(this.resultMenu));
		}

		var nav = $(this.opts.leftNav);
		if (nav) {
			this.leftPanels = nav.select(this.opts.navPanelSelector);
			this.createPanels(this.leftPanels, this.leftViewAction, "leftNav");
		}
		nav = $(this.opts.rightNav);
		if (nav) {
			this.rightPanels = nav.select(this.opts.navPanelSelector);
			this.previewPanel = this.rightPanels[0];
			this.previewHole = $(this.opts.previewContainer);

			if (!this.opts.anonymous) {
				Event.observe(this.opts.collectionsMenu, "click", this.showMenu.bind(this.folderMenu));
				Event.observe(this.opts.mastersMenu, "click", this.showMenu.bind(this.masterRequestMenu));
				Event.observe(this.opts.screenersMenu, "click", this.showMenu.bind(this.screenerRequestMenu));

				this.createPanels(this.rightPanels, this.rightViewAction, "rightNav");
				this.previewMenuItem = this.rightViewAction.items[0];
			}
		}
		document.fire("searchlayout:loaded");

		if (this.opts.enableStickyScroll) {
			var f = $("footer");
			var bp = f ? { bottomPadding: (Position.GetPageSize().height - f.cumulativeOffset().top + 23)} : {};
			AP.Scroll.Register("leftNav", "topLeft", true, "scrolling", bp);
			AP.Scroll.Register("rightNav", "topRight", true, "scrolling", bp);
		}
	},

	createPanels: function(panels, toggleMenu, groupName) {
		for (var i = 0; i < panels.length; i++) {
			var header = panels[i].down("H2");
			if (header) {
				Event.observe(header, "click", this.showMenu.bind(toggleMenu));

				toggleMenu.insert(i, new Ext.menu.CheckItem({
					text: header.innerHTML.trim(),
					group: groupName,
					checked: panels[i].visible(),
					handler: this.ShowPanel.bind(this, panels, panels[i])
				}));
			}
		}
	},

	load: function() {
		//Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

		this.resultsPanel = this.CreateResultsPanel(this.resultMenu);
		this.compilationsPanel = this.CreateCompilationsPanel(this.compilationAction);
		this.previewPanel = this.CreatePreviewPanel();
		this.leftNav = this.CreateLeftNav(this.leftViewAction, this.compilationsPanel);
		this.rightNav = this.CreateRightNav(this.rightViewAction, this.folderMenu, this.previewPanel);

		/*
		this.searchLayout = new Ext.Panel({
		applyTo: 'innerSearchChrome',
		layout: 'border',
		defaults: { hideMode: 'offsets' },
		autoShow: true,
		autoWidth: true,
		cls: 'search-panel',
		items: [this.resultsPanel, this.leftNav, this.rightNav],
		Resize: function(e) {
		this.setSize(0, document.viewport.getHeight() - 325);
		}
		});
		*/

		//		this.searchLayout.preview = searchLayout.layout.east.panel.items.items[1];
		//		this.searchLayout.compilations = searchLayout.layout.west.panel
		//		this.searchLayout.center = searchLayout.layout.center.panel.layout.center.panel;
		//		this.searchLayout.centerSearch = searchLayout.layout.center.panel.layout.north.panel;
		//		this.searchLayout.UpdatePreview = searchLayout.preview.UpdatePreview;

		//Ext.EventManager.onWindowResize(this.searchLayout.Resize, this.searchLayout);
		//this.searchLayout.Resize();

		document.fire("searchlayout:loaded");

		//this.ScrollPanel(this.leftNav, 230, "leftNavFixed");
		//this.ScrollPanel(this.rightNav,230, "rightNavFixed");
		if (this.opts.enableStickyScroll) {
			AP.Scroll.RegisterExtPanel(this.leftNav, "topLeft", 230, "leftNavFixed");
			AP.Scroll.RegisterExtPanel(this.rightNav, "topRight", 230, "rightNavFixed");
		}
	},

	UpdateSelectedItemCount: function(event) {
		var elem = event.element();
		if (elem) {
			var count = elem.innerHTML;
			if (this.addSelectedMenuItem)
				this.addSelectedMenuItem[count <= 0 ? "disable" : "enable"]();
			if (this.addToMasterMenuItem)
				this.addToMasterMenuItem[count <= 0 ? "disable" : "enable"]();
			if (this.addToScreenerMenuItem)
				this.addToScreenerMenuItem[count <= 0 ? "disable" : "enable"]();
			if (this.viewSelectedMenuItem)
				this.viewSelectedMenuItem[count <= 0 ? "disable" : "enable"]();
			if (this.printSelectedMenuItem)
				this.printSelectedMenuItem[count <= 0 ? "disable" : "enable"]();
			if (this.exportSelectedMenuItem)
				this.exportSelectedMenuItem[count <= 0 ? "disable" : "enable"]();
		}
	},

	LoadFolderActions: function(items) {
		this.folderMenu.removeAll();
		this.folderMenu.add.apply(this.folderMenu, items);
	},

	LoadMasterRequestActions: function(items) {
		this.masterRequestMenu.removeAll();
		this.masterRequestMenu.add.apply(this.masterRequestMenu, items);
	},

	LoadScreenerRequestActions: function(items) {
		this.screenerRequestMenu.removeAll();
		this.screenerRequestMenu.add.apply(this.screenerRequestMenu, items);
	},

	LoadSortActions: function(actions) {
		//this.resultMenu.addSeparator()
		this.resultMenu.add(actions);
	},

	LoadSearchResults: function(url) {
		this.resultsPanel.load({ url: url/*, callback: this.searchLayout.SetSearch*/ });
	},

	LoadPreview: function(url, ajaxOpts) {
		this.ShowPreview();
		new Ajax.Updater(this.previewHole, url, Object.extend({
			method: "get"
		}, ajaxOpts || {}));
	},

	ShowPreview: function() {
		this.ShowPanel(this.rightPanels, this.previewPanel);
		if (this.previewMenuItem)
			this.previewMenuItem.setChecked(true);
	},

	ShowSecondaryItems: function() {
		this.rightNav.setActiveTab(0);
	},

	HideRightNav: function() {
		this.rightNav.toggleCollapse(true);
	},

	ShowPanel: function(panels, activePanel) {
		for (var i = 0; i < panels.length; i++)
			panels[i][panels[i] == activePanel ? "show" : "hide"]();
	},

	ShowLeftPanel: function(activePanel) {
		this.ShowPanel(this.leftPanels, activePanel);
	},

	ShowCompilations: function() {
		this.leftNav.setActiveTab(0);
	},

	ShowCategories: function() {
		this.leftNav.setActiveTab(1);
	},

	HideLeftNav: function() {
		this.leftNav.toggleCollapse(true);
	},

	CreatePreviewPanel: function() {
		return new Ext.Panel({
			contentEl: 'preview',
			layout: 'fit',
			width: 220,
			split: true,
			titlebar: false,
			collapsible: true,
			tbar: ['<h2>Preview</h2>', new Ext.Toolbar.Fill()],
			autoScroll: true,
			getState: function() { return { collapsed: this.collapsed }; }
		});
	},

	CreateRightNav: function(rightViewAction, folderMenu, previewPanel) {
		var panels, tbars;

		if (this.opts.anonymous) {
			panels = previewPanel;
			tbars = null;
		}
		else {
			var folderAction = new Ext.Action({
				text: 'Actions',
				cls: 'action-toolbar',
				menu: folderMenu
			});
			panels = [
				new Ext.Panel({
					contentEl: 'rightNav',
					layout: 'fit',
					autoScroll: true,
					tbar: ['<h2>Secondary Items</h2>', new Ext.Toolbar.Fill(), folderAction]
				}),
				previewPanel
			];
			tbars = [new Ext.Toolbar.Fill(), rightViewAction];
		}

		return new Ext.TabPanel({
			region: 'east',
			applyTo: 'rightNavTab',
			baseCls: 'x-tab-panel-noborder',
			width: 225,
			split: true,
			deferredRender: false,
			activeTab: 0,
			tabPosition: 'none',
			collapsible: true,
			collapseMode: 'mini',
			tbar: tbars,
			stateEvents: ["collapse", "expand"],
			getState: function() { return { collapsed: this.collapsed }; },
			items: panels
		});
	},

	CreateLeftNav: function(leftViewAction, compilationsPanel) {
		return new Ext.TabPanel({
			region: 'west',
			applyTo: 'leftNavTab',
			split: true,
			deferredRender: false,
			activeTab: 0,
			baseCls: 'x-tab-panel-noborder',
			tabPosition: 'none',
			collapsible: false,
			collapsed: false,
			//collapseMode: 'mini',
			titlebar: true,
			tbar: [new Ext.Toolbar.Fill(), leftViewAction],
			items: [
				compilationsPanel,
				new Ext.Panel({
					contentEl: 'leftNavCategories',
					layout: 'fit',
					cls: 'categories',
					tbar: ['<h2>Categories</h2>'],
					autoScroll: true
				})
			]
		});
	},

	CreateCompilationsPanel: function(compilationAction) {
		return new Ext.Panel({
			layout: 'border',
			tbar: ['<h2>Compilations</h2>', new Ext.Toolbar.Fill(), compilationAction],
			autoScroll: false,
			autoShow: true,
			items: [{
				region: 'north',
				layout: 'fit',
				contentEl: 'requestRoot',
				hidden: $('requestRoot').empty()
			}, {
				region: 'center',
				layout: 'fit',
				contentEl: 'leftNav',
				//cls:'leftNav',
				autoScroll: true
			}
			]
		});
	},

	CreateResultsPanel: function(resultActions) {
		//return null;
		//		return new Ext.Panel({
		//		    applyTo: 'innerSearchChrome',
		//			region: 'center',
		//			layout: 'border',
		//			cls: 'mainBodyPanel',
		//			items: [{
		//				contentEl: 'topSearchBar',
		//				region: 'north',
		//				layout: 'fit',
		//				autoWidth:true,
		//				height: 70,
		//				titlebar: false,
		//				tbar: [
		//					'<h2>Results</h2>',
		//					new Ext.Toolbar.Fill(), {
		//						text: 'Actions',
		//						cls: 'action-toolbar',
		//						menu: resultActions
		//					}
		//				]
		//			}, {
		//				region: 'center',
		//				contentEl: 'mainBody',
		//				cls: 'mainBody',
		//				layout: 'fit',
		//				autoScroll: true
		//			}
		//			]
		//		});

		var tb = new Ext.Toolbar();
		tb.render('topSearchBar');
		tb.add('<h2>Results</h2>',
					new Ext.Toolbar.Fill(), {
						text: 'Actions',
						cls: 'action-toolbar',
						menu: resultActions
					});
	},

	CreateRightViewMenu: function(elements) {
		var menu = new Ext.menu.Menu({
			items: ['-', {
				text: 'Hide This Panel',
				handler: this.HideRightNav.bind(this)
			}
			]
		});

		return menu;
	},

	CreateLeftViewMenu: function(elements) {
		var menu = new Ext.menu.Menu({
			items: ['-', {
				text: 'Hide This Panel',
				handler: this.HideLeftNav.bind(this)
			}
			]
		});

		return menu;
	},

	CreateCompilationsMenu: function(element) {
		var crs = { text: 'Clear Recent Searches', handler: function() { ClearRecentSearches(); } };
		var items;

		if (!this.opts.anonymous) {

			items = [{
				text: 'Create New Folder',
				handler: function() { ViewDetails(-1, 'New Folder'); }
			}, {
				text: 'Submit Screener Request',
				handler: function() { Go('/secured/order/Screener.aspx'); }
			}, {
				text: 'Submit Master Request',
				handler: function() { Go('/secured/order/Master.aspx'); }
			}, {
				text: 'Manage Folders',
				handler: function() { Go('/secured/lightbox/Default.aspx'); }
			}, {
				text: 'Manage Saved Searches',
				handler: function() { Go('/secured/ssearch/Multiple.aspx'); }
			}, '-', crs
			];
		}
		else {
			items = [crs];
		}

		return new Ext.menu.Menu(items);
	},

	CreateResultMenu: function() {
		this.viewSelectedMenuItem = new Ext.menu.Item({
			text: 'View Selected (<span id="globalSlectedItemNum">' + this.opts.selectedCount + '</span>)...',
			cls: 'nonc',
			handler: function() { Go('/Selected.aspx?st=sel&xslt=sel'); },
			disabled: this.opts.selectedCount <= 0
		});
		this.printSelectedMenuItem = new Ext.menu.Item({
			text: 'Print Selected...',
			handler: PrintSelected,
			disabled: this.opts.selectedCount <= 0
		});

		var items = [{
			text: 'Select Page',
			cls: 'nonc',
			handler: function() { cm.MarkAllChecks(null, true, true); }
		}, {
			text: 'Deselect Page',
			cls: 'nonc',
			handler: function() { cm.MarkAllChecks(null, false, true); }
		}, {
			text: 'Deselect All',
			cls: 'nonc',
			handler: ClearSelectedItems
		}, this.viewSelectedMenuItem, this.printSelectedMenuItem, '-', {
			text: 'Change View...',
			handler: function() {
				new AP.ModalDialog('changeLayout', { title: 'Layout Preference' }).show();
			}
		}, {
			text: 'Refresh Results',
			handler: function() {
				window.location.reload();
			} .bind(this)
		}
		];

		items.push({ text: 'Print Results', handler: PrintResults });

		var idx = 4;

		if (!this.opts.anonymous) {
			var addToFolder = [
				{ text: 'New Folder', handler: function() { AddSelectedToLightbox('New', -1); } },
				{ text: 'Current Folder', handler: function() { AddSelectedToLightbox(); } }
			];

			this.addToScreenerMenuItem = new Ext.menu.Item({ text: 'Add to Screener Request', handler: function() { AddSelectedToLightbox('screener', 'cart'); }, disabled: this.opts.selectedCount <= 0 });
			this.addToMasterMenuItem = new Ext.menu.Item({ text: 'Add to Master Request', handler: function() { AddSelectedToLightbox('master', 'master'); }, disabled: this.opts.selectedCount <= 0 });
			items.splice(idx, 0, this.addToScreenerMenuItem);
			items.splice(idx, 0, this.addToMasterMenuItem);

			this.addSelectedMenuItem = new Ext.menu.Item({ text: 'Add to Folder', hideOnClick: false, menu: addToFolder, disabled: this.opts.selectedCount <= 0 });
			items.splice(idx, 0, this.addSelectedMenuItem);
			items.splice(idx, 0, '-');

			this.exportSelectedMenuItem = new Ext.menu.Item({ text: 'Export Selected...', handler: function() { ExportSearchXls('st=sel&', null, null, true); }, disabled: this.opts.selectedCount <= 0 });
			items.splice(idx, 0, this.exportSelectedMenuItem);

			items.push({ text: 'Export Results', handler: function() { ShowExcel('exportToExcel'); }});
		}
		/*{ text: 'Remove from Folder', handler: function() { m('You did it'); } } */


		// IF THIS IS FOLDER/REQUEST SEARCH RESULTS,
		// SHOW DELETE MENU ITEM.
		if (this.opts.searchType == "lbx") {
			var lbxId = this.opts.lbxId;
			var deleteMenuItem = new Ext.menu.Item({ text: 'Delete Selected...', handler: function() { DeletePhoto.call(this, null, lbxId, "selected") } });
			items.splice(idx, 0, deleteMenuItem);

			var manageMenuItem = new Ext.menu.Item({ text: 'Manage Folders', handler: function() { Go('/secured/lightbox/Default.aspx'); } });
			items.splice(0, 0, manageMenuItem);
			items.splice(1, 0, '-');
		}
		else {
			var manageMenuItem = new Ext.menu.Item({ text: 'Manage Saved Searches', handler: function() { Go('/secured/ssearch/Multiple.aspx'); } });
			items.splice(0, 0, manageMenuItem);
			items.splice(1, 0, '-');
		}

		return new Ext.menu.Menu({
			text: 'Actions',
			cls: 'action-toolbar',
			items: items
		});
	},

	CreateFolderMenu: function(element) {
		return new Ext.menu.Menu({
			text: 'Actions',
			cls: 'action-toolbar',
			defaultAlign: 'tr-br'
		});
	},

	CreateMasterRequestMenu: function(element) {
		return new Ext.menu.Menu({
			text: 'Actions',
			cls: 'action-toolbar',
			defaultAlign: 'tr-br'
		});
	},

	CreateScreenerRequestMenu: function(element) {
		return new Ext.menu.Menu({
			text: 'Actions',
			cls: 'action-toolbar',
			defaultAlign: 'tr-br'
		});
	}

});

AP.SearchGrid = Class.create({
	initialize: function(opts) {
		this.opts = Object.extend({
			showPager: false,
			renderTo: 'mainGrid',
			data: null
		}, opts || {});

		if (!$(this.opts.renderTo))
			alert('Must specify valid container for grid:' + this.opts.renderTo);

		Ext.onReady(this.CreateGrid.bind(this));
	},

	CreateGrid: function() {
		if (!this.grid) {
			this.sm = new Ext.grid.CheckboxSelectionModel();
			this.store = this.CreateStore(this.opts.data);

			this.grid = new Ext.grid.GridPanel({
				stripeRows: true,
				loadMask: true,
				enableDragDrop: false,
				trackMouseOver: true,
				autoHeight: true,
				store: this.store,
				autoExpandColumn: this.opts.expand,
				bbar: this.CreateToolBar(),
				tbar: this.CreatePagerBar(this.opts.pageSize, this.store),
				cm: this.CreateColumns(),
				sm: this.sm,
				viewConfig: {
					forceFit: true
				}
			});
			var self = this;
			this.grid.addListener('rowcontextmenu', this.ShowCM, this);
			this.grid.addListener('rowdblclick', this.Select, this);
			//this.grid.addListener('cellclick', this.Check,this);
			this.sm.on('rowdeselect', this.Check, { action: 'rem' });
			this.sm.on('rowselect', this.Check, { action: 'add' });

			//        var rz = new Ext.Resizable(this.opts.renderTo, {
			//			wrap:true,
			//			minHeight:200,
			//			minWidth:200,
			//			width:$(this.opts.renderTo).getWidth()-10,
			//			height:$(this.opts.renderTo).getHeight()-10,
			//			pinned:true
			//		});
			//		
			//		rz.on('resize', self.Resize, self.grid);
			this.grid.render(this.opts.renderTo);
		}
	},

	CreateColumns: function() {
		var cm = new Ext.grid.ColumnModel([
			this.sm,
			new Ext.grid.RowAction(),
      { header: "Video", sortable: false, fixed: true, width: 50, renderer: this.RenderVideo },
      { header: "Story #", dataIndex: 'storyid', draggable: true, width: 50, sortable: true },
      { header: "Title", dataIndex: 'slug', width: 150, sortable: true },
      { header: "Source", dataIndex: 'source', width: 130, align: 'left', renderer: this.Trim, sortable: true },
      { header: "Duration", dataIndex: 'totalduration', fixed: true, width: 50, sortable: true },
      new Ext.grid.RowNumberer()
    ]);
		return cm;
	},

	CreateStore: function(data) {
		var searchArgs = __searchResults.newPageArgs();
		searchArgs.set("xslt", "json");

		var jstore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: 'search.ashx?' + searchArgs.toQueryString()
			}),
			reader: new Ext.data.JsonReader({
				root: 'HitList',
				totalProperty: 'TotalHits',
				id: 'RecordID',
				fields: ['slug', 'source', 'totalduration', 'storyid']
			}),
			remoteSort: true
		});

		if (data)
			jstore.loadData(data);

		//jstore.addListener('beforeload', this.SortChange, this);

		return jstore;
	},

	CreatePagerBar: function(pageSize, store) {
		var pager = new Ext.PagingToolbar({
			pageSize: pageSize,
			cls: 'grid-toolbar',
			store: store,
			displayInfo: true,
			displayMsg: 'Displaying results {0} to {1} of {2}',
			emptyMsg: "No records found"
		});
		pager.addListener('beforechange', this.Pager_BeforeChange, this);
		return pager;
	},

	Pager_BeforeChange: function(tool, params) {
		params.page = (params.start / tool.pageSize) + 1;
	},

	SortChange: function(obj, params) {
	},

	CreateToolBar: function() {
		return null;
	},
	Load: function(data) {
		this.store.loadData(data);
	},
	Select: function(g, r, c) {
		//alert('Selected Row :'+ g.store.data.items[r].data.title + ' - ['+g.store.data.items[r].id +']');
		OneUpEast(g.store.data.items[r].id);
	},
	Check: function(g, r, a) {
		var action = g.selections.containsKey(g.grid.store.data.items[r].id) ? 'add' : 'rem';
		SaveChecked(action, g.grid.store.data.items[r].id);
	},
	RenderVideo: function(value, p, r) {
		return String.format('<a id="lv_{0}" recordid="{0}" class="hasrecordid" href="#{0}" onclick="OneUp(\'{0}\');" title="{1}">Video</a>', r.id, r.data['itemname']);
	},
	Resize: function(c, w, h, e) {
		self.grid.grid.setSize(w - 3, h);
	},
	Trim: function(val) {
		return '<div  class="wrap">' + val.substr(0, 20) + '</div>';
	},
	ShowCM: function(g, r, e) {
		e.stopEvent();
		var recordId = g.store.data.items[r].id;
		var items = eval(window._searchHitMenuItems);
		var cm = new Ext.menu.Menu({ items: items });
		cm.showAt([e.xy[0], e.xy[1]]);
	}
});

function m(mess) {
	Ext.MessageBox.show({
		title: 'Video Archive',
		msg: mess,
		buttons: Ext.MessageBox.YESNOCANCEL,
		icon: Ext.MessageBox.QUESTION
	});
}
