 /*
	Namespace: URSPIN.AddStuff
*/
URSPIN.AddStuff = new Class({

	isAddStuffOpened: false,
	addStuffEffect: null,
	addStuffEffectHideParams: {'height':0},
	addStuffEffectShowParams: {'height':218},
	addStuffEffectShowParamsX: {'height':234},
	addStuffEffectOptions: {'wait':false,'duration':500,'unit':'px','transition':Fx.Transitions.Expo.easeInOut},

	initialize: function (options) {
		var el = $('add-stuff');
	
		this.addStuffEffect = $('add-stuff').effects(this.addStuffEffectOptions);
		this.addStuffEffect.addEvent('onStart', function () {
			if (this.offsetHeight > 0) {
				this.fireEvent('beforeClose');
			} else {
				this.fireEvent('beforeOpen');
			}
		}.bind(el));

		this.addStuffEffect.addEvent('onComplete', function () {
			if (this.offsetHeight > 0) {
				this.fireEvent('open');
				this.isAddStuffOpened = true;
			} else {
				this.fireEvent('close');
				this.isAddStuffOpened = false;
			}
		}.bind(el));

		// set addStuff to have 'hidden' styles
		this.addStuffEffect.set(this.addStuffEffectHideParams);
		this.isAddStuffOpened = false;

		// create left-side header buttons
		var marker = $('as-hdr-close');
		var hdrBtnW = $('as-hdr-btns');
		var b = URSPIN.Webtop.buildButton({
			'id':'as-btn-1',
			'onClick':this.openDir.bindWithEvent(el, true),
			'text':URSPIN.l10n.getString('ui.addstuff.hdr_btn.dir'),
			'iconSrc':'as-1',
			'noActive':true
		});
		b.removeClass('alpha');
		b.injectBefore(marker);

		if (google && google.feeds) {
			var b = URSPIN.Webtop.buildButton({
				'id':'as-btn-2',
				'onClick':this.openAddFeedUni.bindWithEvent(el, true),
				'text':URSPIN.l10n.getString('ui.addstuff.hdr_btn.feeduni'),
				'iconSrc':'as-2',
				'noActive':true
			});
			b.removeClass('alpha');
			b.injectBefore(marker);
		}
		$('as-hdr-close').addEvent('mousedown', this.toggle.bind(el));
		$('as-hdr-close').getElement('.btn-txt').setText(URSPIN.l10n.getString('ui.basic.close'));
		


		// this.openDir();
		// this.openAddFeedUni();
		return $extend(el, this);
	},
	
	openDir: function (e, noEvent) {
		if ($defined(this.addStuffFeedUni)) {
			this.addStuffFeedUni.setStyle('display','none');
		}


		if (!$defined(this.addStuffDir)) {
			this.addStuffDir = new URSPIN.AddStuff.Dir();
			this.addEvent('beforeOpen', this.addStuffDir.onBeforeOpen.bind(this.addStuffDir));
			this.addEvent('open', this.addStuffDir.onOpen.bind(this.addStuffDir));
			this.addEvent('beforeClose', this.addStuffDir.onBeforeClose.bind(this.addStuffDir));
			this.addEvent('close', this.addStuffDir.onClose.bind(this.addStuffDir));
			$('as-con').adopt(this.addStuffDir);
			
			if (noEvent) {
				this.addStuffDir.onBeforeOpen();
				this.addStuffDir.onOpen();
			}
		} else {
			this.addStuffDir.reset.call(this.addStuffDir);
		}
		
		$('as-btn-1').addClass('on');
		$('as-btn-2').removeClass('on');
		
	},

	openAddFeedUni: function (e , noEvent) {
		if ($defined(this.addStuffDir)) {
			this.addStuffDir.setStyle('display','none');
		}

		if (!$defined(this.addStuffFeedUni)) {
			this.addStuffFeedUni = new URSPIN.AddStuff.FeedUni();
			this.addEvent('beforeOpen', this.addStuffFeedUni.onBeforeOpen.bind(this.addStuffFeedUni));
			this.addEvent('open', this.addStuffFeedUni.onOpen.bind(this.addStuffFeedUni));
			this.addEvent('beforeClose', this.addStuffFeedUni.onBeforeClose.bind(this.addStuffFeedUni));
			this.addEvent('close', this.addStuffFeedUni.onClose.bind(this.addStuffFeedUni));
			$('as-con').adopt(this.addStuffFeedUni);

			if (noEvent) {
				this.addStuffFeedUni.onBeforeOpen();
				this.addStuffFeedUni.onOpen();
			}

		} else {
			this.addStuffFeedUni.reset.call(this.addStuffFeedUni);
		}

		$('as-btn-2').addClass('on');
		$('as-btn-1').removeClass('on');

	},

	/*
		Method: toggle

		Parameters:
			None

		Returns:
			Nohthing
	*/
	toggle: function () {
		$('tab-bar').setStyle('display', 'block');
		$('content-bodies').setStyle('display', 'block');
		$('search-results').setStyle('display', 'none');

		if ($('as-fu-results')) {
			$('as-fu-results').remove();
		}


		$('add-stuff').setStyle('height', $('add-stuff').getStyle('height'));

		$('add-stuff').removeClass('footer-visible');
		$('add-stuff').removeClass('footer-opened');

		if (this.isAddStuffOpened) {
			$('add-stuff').removeClass('opened');
			this.addStuffEffect.start(this.addStuffEffectHideParams);
		} else {
			$('add-stuff').addClass('opened');
			this.reset();
			this.addStuffEffect.start(this.addStuffEffectShowParams);
		}
	},
	
	hide: function () {
		$('add-stuff').removeClass('footer-visible');
		$('add-stuff').removeClass('footer-opened');

		this.addStuffEffect.set(this.addStuffEffectHideParams);
		if ($('as-fu-results')) {
			$('as-fu-results').remove();
		}
		
		this.isAddStuffOpened = false;
	},
	

	reset: function () {
		this.openDir();
		// this.openAddFeedUni();
	}

});

URSPIN.AddStuff.implement(new Events);


/*
	Class: URSPIN.AddStuff.FeedUni
*/
URSPIN.AddStuff.FeedUni = new Class({
	options: {},

	initialize: function (options) {
		this.setOptions(options);

		var el = new Element('div',{'id':'add-stuff-feed-uni-viewport'});
		
		var feedUni = new Element('div',{'class':'add-stuff-feed-uni'});
		el.adopt(feedUni);
		var bigIcon = new Element('div',{'class':'as-dir-big-icn'});
		feedUni.adopt(bigIcon);
		
		bigIcon.adopt(new Element('div',{'class':'as-dir-big-icn-bg'}));
		bigIcon.adopt(new Element('div',{'class':'as-dir-big-icn-img add-stuff-feed-uni-icn-img'}));

		feedUni.adopt(new Element('div',{'class':'as-dir-title'}).setText(URSPIN.l10n.getString('ui.addstuff.hdr_btn.feeduni')));
		// LEFT OFF
		var con = new Element('div',{'class':'add-stuff-feed-uni-content'});
		feedUni.adopt(con);
		
		var e1 = new Element('div',{'class':'add-stuff-feed-uni-search-w'});
		con.adopt(e1);
		
		e1.adopt(new Element('label',{'class':'', 'for':'add-stuff-feed-uni-search-field-in'}).setText(URSPIN.l10n.getString('ui.addstuff.feeduni.searchdesc')));
		var tfw = new Element('div',{'class':'tf-w', 'id':'add-stuff-feed-uni-search-field'});
		e1.adopt(tfw);
		var i1 = new Element('input',{'class':'textfield','id':'add-stuff-feed-uni-search-field-in'});
		i1.addEvent('keypress',
			function (e) {
				if (e.code == 13) {
					this.onSearchClick();
					e.stop();
				}
			}.bindWithEvent(el)
		);

		tfw.adopt(new Element('div',{'class':'tf-c'}).adopt(i1));
		tfw.adopt(new Element('div',{'class':'tf-l'}));
		tfw.adopt(new Element('div',{'class':'tf-r'}));
		e1.adopt(URSPIN.Webtop.buildButton({
			'text':URSPIN.l10n.getString('ui.addstuff.feeduni.search'),
			'iconSrc':'btn_icn_mag_glass',
			'onClick':this.onSearchClick.bind(el)
		}));
		e1.adopt(new Element('div',{'class':'cb'}));
		
		return $extend(el, this);
	},

	onBeforeOpen: function () {},
	onOpen: function () {},
	onBeforeClose: function () {},
	onClose: function () {},
	reset: function () {
		this.setStyle('display','block');
	},
	
	
	onSearchClick: function () {
		var q = $('add-stuff-feed-uni-search-field-in').getProperty('value');
		q = q.trim();



		this.onFeedUniSearch(q);
	},

	
	onFeedUniSearch: function (q) {
		// console.log('onFeedUniSearch:', q);


		$('add-stuff').addClass('footer-visible');
		$('add-stuff').addClass('footer-opened');
		$('add-stuff').setStyle('height', '');

		// hide part of webtop
		$('tab-bar').setStyle('display','none');
		$('content-bodies').setStyle('display','none');
		$('notify-w').setStyle('display','none');
		$('search-results').setStyle('display','none');


		var re = $('as-fu-results');
		if (!re) {
			// build as-fu-results
			re = new Element('div', {'id':'as-fu-results'});
			$('webtop').adopt(re);


			var c = new Element('div',{'id':'as-fu-results-c'});
			re.adopt(c);
			c.adopt(new Element('div',{'class':'as-fu-results-bg-lr', 'id':'as-fu-results-bg-l'}));
			c.adopt(new Element('div',{'class':'as-fu-results-bg-lr', 'id':'as-fu-results-bg-r'}));
			var content = new Element('div',{'id':'as-fu-results-content'});
			c.adopt(content);
			content.adopt(new Element('div',{'class':'as-fu-results-bg-lr as-fu-results-content-lr', 'id':'as-fu-results-content-l'}));
			content.adopt(new Element('div',{'class':'as-fu-results-bg-lr as-fu-results-content-lr', 'id':'as-fu-results-content-r'}));

			content.adopt(new Element('div',{'class':'as-bg-lrb as-fu-results-content-topbottom','id':'as-fu-results-content-top'}));
			content.adopt(new Element('div',{'class':'as-bg-lrb as-fu-results-content-topbottom','id':'as-fu-results-content-bottom'}));
			content.adopt(new Element('div',{'class':'as-bg-lrb as-fu-results-content-corner','id':'as-fu-results-content-corner-tl'}));
			content.adopt(new Element('div',{'class':'as-bg-lrb as-fu-results-content-corner','id':'as-fu-results-content-corner-tr'}));
			content.adopt(new Element('div',{'class':'as-bg-lrb as-fu-results-content-corner','id':'as-fu-results-content-corner-bl'}));
			content.adopt(new Element('div',{'class':'as-bg-lrb as-fu-results-content-corner','id':'as-fu-results-content-corner-br'}));


			var b = new Element('div',{'class':'as-bg-lrb', 'id':'as-fu-bg-b'});
			re.adopt(b);
			b.adopt(new Element('div',{'class':'as-bg-lrb', 'id':'as-fu-bg-b-l'}));
			b.adopt(new Element('div',{'class':'as-bg-lrb', 'id':'as-fu-bg-b-r'}));

			
			content.adopt(new Element('div',{'id':'as-fu-results-content-header'}).setText(URSPIN.l10n.getString('ui.addstuff.feeduni.results.header')));
			content.adopt(new Element('div',{'id':'as-fu-results-content-body'}));
		}
		
		var contentBody = $('as-fu-results-content-body');
		contentBody.empty();
		contentBody.adopt(new Element('div', {'class':'content-body-throbber'}));


		$('as-fu-results-content').setStyle('height', '');
		$('as-fu-results-content').setStyle('height', $('as-fu-results-content').offsetHeight);
		$('as-fu-results-c').setStyle('height', $('as-fu-results-content').offsetHeight);

	
		// set up -,+,x buttons
		
		$('as-b-btn-1').addEvent('click', function () {
			$('add-stuff').addClass('footer-opened');

			if ($('as-fu-results')) {
				$('as-fu-results').setStyle('display', 'block');
			}
		
			$('tab-bar').setStyle('display','none');
			$('content-bodies').setStyle('display','none');
		
		});
		$('as-b-btn-2').addEvent('click', function () {
			$('add-stuff').removeClass('footer-opened');

			if ($('as-fu-results')) {
				$('as-fu-results').setStyle('display', 'none');
			}

			$('tab-bar').setStyle('display','block');
			$('content-bodies').setStyle('display','block');
		});
		$('as-b-btn-3').addEvent('click', function () {
			$('add-stuff').removeClass('footer-visible');
			$('add-stuff').removeClass('footer-opened');

			if ($('as-fu-results')) {
				$('as-fu-results').remove();
			}			


			$('tab-bar').setStyle('display','block');
			$('content-bodies').setStyle('display','block');

		});

		google.feeds.findFeeds(q, this.onFeedResult.bind(this));
	},
	
	onFeedResult: function (results) {
		// console.dir(results);

		console.dir({'results':results});

		var contentBody = $('as-fu-results-content-body');
		if (contentBody) {
			contentBody.empty();

			if (results.entries && results.entries.length > 0) {
				for (var i = 0; i < results.entries.length; i++) {
					var r = results.entries[i];
					var h = [];

					h.push('<div class="as-fu-result-logo"></div><div class="as-fu-result-content"><h2>');
					h.push(r.title);
					h.push('</h2><div class="as-fu-result-snippet">');
					h.push(r.contentSnippet);
					h.push('</div><div class="as-fu-result-link"><a target="_blank" href="');
					h.push(r.link);
					h.push('">');				
					h.push(r.link);
					h.push('</a></div></div>');

					var x = new Element('div',{'class':'as-fu-result'}).setHTML(h.join(''));
					contentBody.adopt(x);

					var y = new Element('div',{'class':'as-fu-result-btns'});
					x.adopt(y);

					var btn = URSPIN.Webtop.buildButton({
						'text':URSPIN.l10n.getString('ui.addstuff.dir.btn.addto'),
						'iconSrc':'btn_icn_dwn_arr'
					});
				
					y.adopt(btn);

					btn.feedURI = r.url;

					btn.addEvent('click', function (e) {
						// console.log('btn click');
						var menuOptions = {
							'class':'as-dir-add-to-menu',
							'menuItems':[]
						};
				
						var module = {
							'moduleID':1,
							'type':'feed',
							'settings':{'feedURI':{'value':this.feedURI}}
						};
				
						var addModule = function (tab) {
							var mod = new URSPIN.FeedModule(module);
							tab.moveModule(mod, null, null, {'switchToTab':false});
							this.msgSpan.setText(URSPIN.l10n.getString('ui.addstuff.feeduni.results.addedmsg') + tab.getTitle());
						};

						URSPIN.getWebtop().getTabManager().getTabsThatCanAddModules().each(function (tab) {
							menuOptions.menuItems.push({'title':tab.getTitle(),'onClick':addModule.pass([tab], this)});
						}, this);

						if ($defined(this.menu) && this.menu.getParent()) {
							this.menu.remove();
						}

						this.menu = new URSPIN.Webtop.Menu(menuOptions); 

						var coord = this.getCoordinates();
						this.menu.show({'left':coord.left,'top':coord.bottom});

						e.stop();
					}.bindWithEvent(btn));

					btn.setEnabled(true);
					btn.msgSpan = new Element('span',{'class':'msg'});

					// var btn2 = URSPIN.Webtop.buildButton({
					// 	'text':URSPIN.l10n.getString('ui.addstuff.feeduni.results.previewbtn'),
					// 	'iconSrc':'btn_icn_plus'
					// });
					// y.adopt(btn2);

					y.adopt(btn.msgSpan);





					y.adopt(new Element('div',{'class':'cb'}));
				}
			} else {
				contentBody.setHTML(URSPIN.l10n.getString('ui.addstuff.feeduni.results.noresults'));
			}

			$('as-fu-results-content').setStyle('height', '');
			$('as-fu-results-content').setStyle('height', $('as-fu-results-content').offsetHeight);
			$('as-fu-results-c').setStyle('height', $('as-fu-results-content').offsetHeight);
		}
	}

});
URSPIN.AddStuff.FeedUni.implement(new Options);

/*
	Class: URSPIN.AddStuff.Dir
		Implements Mootools.<Options>
*/
URSPIN.AddStuff.Dir = new Class({

	rootSection: null,

	/*
		Property: options
	*/
	options: {},

	initialize: function (options) {
		this.setOptions(options);

		var el = new Element('div',{'id':'as-dir-viewport'});
		return $extend(el, this);
	},

	// directory itself doesn't do anything when opened or closed
	// but the sections may need to handle these events
	// basically we are pushing the event down
	onBeforeOpen: function () {
		if (!$defined(this.rootSection)) {
			// var rootSectionData = {
			// 	'sectionID':'1',
			// 	'type':'directory',
			// 	'color':'grey',
			// 	'hasBackButton':false
			// };
			var rootSectionData = {
				'sectionID':'1',
				// 'moduleID':'7',
				'type':'directory',
				'color':'grey',
				'hasBackButton':false,
				'title':'ui.addstuff.dir.section.1'
			};
			
			
			this.rootSection = new URSPIN.AddStuff.DirSection(rootSectionData);
			this.addSection(this.rootSection);
		}
		// move root section to visible area
		this.rootSection.setStyle('margin-left','0');
		this.fireEvent('dirBeforeOpen');
	},
	onOpen: function () {
		this.fireEvent('dirOpen');
		URSPIN.getWebtop().getTabManager().getCurrentTab().getContentArea().fireEvent('resize');
	},
	onBeforeClose: function () {this.fireEvent('dirBeforeClose');},
	onClose: function () {
		this.fireEvent('dirClose');
		this.getChildren().each(this.removeSection, this);
		this.rootSection = null;
	},

	addSection: function (section) {
		if (!this.hasChild(section)) {
			this.addEvent('dirBeforeOpen', section.boundFn.onBeforeOpen);
			this.addEvent('dirOpen', section.boundFn.onOpen);
			this.addEvent('dirBeforeClose', section.boundFn.onBeforeClose);
			this.addEvent('dirClose', section.boundFn.onClose);
			section.injectInside(this);
		}
		return section;
	},
	
	removeSection: function (section) {
		// if (section != this.rootSection) {
			section.remove();
			this.removeEvent('dirClose', section.boundFn.onClose);
			this.removeEvent('dirBeforeClose', section.boundFn.onBeforeClose);
			this.removeEvent('dirOpen', section.boundFn.onOpen);
			this.removeEvent('dirBeforeOpen', section.boundFn.onBeforeOpen);
		// }
		return section;
	},

	reset: function (options) {
		var options = options || {};
		var m = this.getChildren().filter(function (item, index) {
			return (item.getStyle('margin-left').toInt() >= 0 && item.getStyle('margin-left').toInt() < 100)
		});
		
		if ($defined(m[0]) && this.rootSection != m[0]) {
			if (options.noAnimate) {
				this.rootSection.setStyle('margin-left', 0);
				m[0].setStyle('margin-left', '100%');
			} else {
				var effect = new Fx.Elements([this.rootSection, m[0]], URSPIN.AddStuff.DirSection.prototype.effectNextPrevOptions);

				effect.addEvent('onStart', this.rootSection.onEffectStart.bind(effect));
				effect.addEvent('onComplete', this.rootSection.onEffectComplete.bind(effect));

				effect.start(URSPIN.AddStuff.DirSection.prototype.effectPrevTransParams);
			}
		}

		this.getChildren().each(function (child) {
			if (child != this.rootSection && child != m[0]) {
				child.setStyle('margin-left', '100%');
			}
		});
		
		this.setStyle('display','block');
		
		// console.log('URSPIN.AddStuff.Dir.reset');
	}

});
URSPIN.AddStuff.Dir.implement(new Options);


/*
	Class: URSPIN.AddStuff.DirSection
		Implements Mootools.<Options>
*/
URSPIN.AddStuff.DirSection = new Class({

	/*
		Property: options
	*/
	options: {
		'title':null,
		'defaultTitle':'Default Title',
		'color':'grey',
		'type':null,
		'hasBackButton':true,
		'hasSearch':false,
		'loadContent':true,
		'breadcrumbs':null,
		'sectionID': null,
		'moduleID': null,
		'collection': null
	},

	/*
		Property: unboundFn
			
			Constructor will bind the functions in this object to its
			instance.
	
			Do not overwrite these functions.
	*/	
	unboundFn: {
		onBeforeOpen: function () {
			// Section is display:none when closed
			// change to display:block so we can see the animation
			this.setStyle('display','block');
		},
		onOpen: function () {
			// Scrollbars are not shown when section is closed or while
			// animating open/close effect because in FF/OSX, scrollbars
			// will be visible even if element is behind another
			// when the section is completely open, we switch to
			// overflow:auto

			this.getElements('.as-dir-no-scroll').each(function (el) {
				el.removeClass('as-dir-no-scroll');
				el.addClass('as-dir-has-scroll');
			});

			// If called in onBeforeOpen, then content can load during the
			// animation. But the animation gets choppy. 
			// Instead load the content here, after the animation.
			if (this.options.loadContent) {
				this.loadContent();
			}
		},
		onBeforeClose: function () {
			// See onOpen for explanation of why we change overflow
			// before section begins close animation, we switch to
			// overflow:hidden

			this.getElements('.as-dir-has-scroll').each(function (el) {
				el.removeClass('as-dir-has-scroll');
				el.addClass('as-dir-no-scroll');
			});
		},
		onClose: function () {
			// Section should be hidden outside the viewport (viewport has
			// overflow:hidden), but we change section to display:none just
			// in case
			this.setStyle('display','none');
		}

	},

	/*
		Property: boundFn
	*/
	boundFn: null,

	effectNextPrevOptions: {'duration':350,'unit':'%','transition':Fx.Transitions.Expo.easeInOut},

	effectNext: null,
	effectNextTransParams: {0:{'margin-left':-100},1:{'margin-left':0}},

	effectPrev: null,
	effectPrevTransParams: {0:{'margin-left':0},1:{'margin-left':'100%'}},

	contentLoadingThrobber:new Element('div',{'class':'as-dir-con-loading'}),// .setText('loading...'),

	/*
		Method: initialize
			Constructor

	    Parameters:
			options - Object

	*/
	initialize: function (options) {
		this.setOptions(options);
		
		if (!$defined(this.options.breadcrumbs)) {
			this.options.breadcrumbs = [];
		}
		
		// this.options.sectionID = this.options.sectionID || this.options.moduleID || this.options.collectionID || $rand(1, 1000);
		
		

		
		var id = $defined(this.options.sectionID) ? ['dir-s',  this.options.sectionID].join('') :
			$defined(this.options.moduleID) ? ['dir-m', this.options.moduleID].join('') :
			$defined(this.options.collectionID) ? ['dir-c', this.options.collectionID].join('') :
			['dir-r', $random(1, 100000)].join('');
		var dir = new Element('div',{'class':'as-dir','id':id});
		dir.addClass(['as-dir-', this.options.color].join(''));
		$extend(dir, this);


		// bind event functions to this instance
		dir.boundFn = {};
		for (var fn in dir.unboundFn) {
			dir.boundFn[fn] = dir.unboundFn[fn].bind(dir)
		}

		/*
			Back button
		*/
		if (dir.options.hasBackButton) {
			dir.adopt(new Element('div',{'class':'as-dir-btn-back'})
				.addEvent('mousedown', dir.openPrev.bind(dir)));
		}

		/*
			Big Icon
		*/
		var bigIcon = new Element('div',{'class':'as-dir-big-icn'});
		bigIcon.adopt(new Element('div',{'class':'as-dir-big-icn-bg'}));

		var x = new Element('div',{'class':'as-dir-big-icn-img'});
		if ($defined(dir.options.type)) {
			x.setStyle('background-image',['url(\'a/images/add_stuff/dir/icon_big/', dir.options.type, '.png\')'].join(''));
		}
		bigIcon.adopt(x);
		dir.adopt(bigIcon);

		/*
			Breadcrumbs
		*/
		var crumbs = '';
		for (var i = 1; i < dir.options.breadcrumbs.length; i++) {
			crumbs = [crumbs, dir.options.breadcrumbs[i].getTitle(), ' > '].join(''); //» 
		}

		dir.adopt(new Element('div',{'class':'as-dir-breadcr'}).setText(crumbs));

		/*
			Title
		*/
		dir.titleEl = new Element('div',{'class':'as-dir-title'});
		dir.adopt(dir.titleEl);
		dir.setTitle(dir.options.title || dir.options.defaultTitle);

		/*
			Content wrapper
		*/
		var contentW = new Element('div',{'class':'as-dir-con-w'});
		dir.adopt(contentW);

		/*
			Content Title
		*/
		dir.contentTitleEl = new Element('div',{'class':'as-dir-con-title'});
		contentW.adopt(dir.contentTitleEl);
		

		/*
			Content
		*/
		dir.contentEl = new Element('div',{'class':'as-dir-con'});
		dir.contentEl.addClass('as-dir-has-scroll');
		contentW.adopt(dir.contentEl);


		if (this.options.sectionID == 6) {
			var createWishList = function () {
				var n = $('as-wishlist-name').getValue().trim();
				var k = $('as-wishlist-keyword').getValue().trim();
				console.log(n, k);


				var onFeedResult = function (results) {
					if (results.entries && results.entries.length > 0) {
						var addResults = function () {
							for (var i = 0; i < results.entries.length; i++) {
								var mod = new URSPIN.FeedModule({'settings':{'feedURI':{'value':results.entries[i].url}}});
								this.addNewModule(mod, i % 3);
							}
						};

						var t = URSPIN.getWebtop().getTabManager().addNewTab(null, {'title':n}, addResults);


					} else {
						// TODO ?
						console.warn('no feeds found');
					}

				};

				google.feeds.findFeeds(k, onFeedResult);				
			};


			var e2 = new Element('div',{'id':'as-wishlist-w'});
			dir.contentEl.adopt(e2);
			e2.adopt(new Element('div',{'id':'as-wishlist-desc'}).setText(URSPIN.l10n.getString('ui.addstuff.dir.wishlist.desc')));

			var f = new Element('div',{'id':'as-wishlist-form'});
			e2.adopt(f);

			var f1 = new Element('div',{'id':'as-wishlist-f1'});
			f.adopt(f1);
			f1.adopt(new Element('label',{'for':'as-wishlist-name'}).setText(URSPIN.l10n.getString('ui.addstuff.dir.wishlist.label1')));
			var tfw = new Element('div',{'class':'tf-w'});
			f1.adopt(tfw);

			var i2 = new Element('input',{'class':'textfield', 'id':'as-wishlist-name'});
			i2.addEvent('keypress',function (e) {
				if (e.code == 13) {
					createWishList();
				}
			}.bindWithEvent());

			tfw.adopt(new Element('div',{'class':'tf-c'}).adopt(i2));
			tfw.adopt(new Element('div',{'class':'tf-l'}));
			tfw.adopt(new Element('div',{'class':'tf-r'}));




			var f2 = new Element('div',{'id':'as-wishlist-f2'});
			f.adopt(f2);
			f2.adopt(new Element('label',{'for':'as-wishlist-keyword'}).setText(URSPIN.l10n.getString('ui.addstuff.dir.wishlist.label2')));

			var tfw = new Element('div',{'class':'tf-w'});
			f2.adopt(tfw);

			var i2 = new Element('input',{'class':'textfield', 'id':'as-wishlist-keyword'});
			i2.addEvent('keypress',function (e) {
				if (e.code == 13) {
					createWishList();
				}	
			}.bindWithEvent());
			tfw.adopt(new Element('div',{'class':'tf-c'}).adopt(i2));
			tfw.adopt(new Element('div',{'class':'tf-l'}));
			tfw.adopt(new Element('div',{'class':'tf-r'}));

			f2.adopt(URSPIN.Webtop.buildButton({
				'text':URSPIN.l10n.getString('ui.addstuff.dir.wishlist.createbtn'),
				'onClick':createWishList,
				'iconSrc':'btn_icn_wand'
			}));
			f2.adopt(new Element('div',{'class':'cb'}));


		} else if (this.options.sectionID == 7) {
			var e2 = new Element('div',{'class':'as-from-web-add-w'});
			dir.contentEl.adopt(e2);

			e2.adopt(new Element('label',{'class':'', 'for':'as-from-web-field-in'}).setText(URSPIN.l10n.getString('ui.addstuff.feeduni.adddesc')));
			var tfw = new Element('div',{'class':'tf-w', 'id':'as-from-web-field'});
			e2.adopt(tfw);

			var onAddClick = function () {
				var uri = $('as-from-web-field-in').getProperty('value').trim();
				$('as-from-web-error').setText(URSPIN.l10n.getString('ui.addstuff.dir.fromweb.searching'));
				// console.log('onAddClick:', uri);
				google.feeds.lookupFeed(
					uri,
					function (result) {
						if ($defined(result.error)) {
							$('as-from-web-error').setText(URSPIN.l10n.getString('ui.addstuff.dir.fromweb.error'));
							// console.warn('googe.feeds.lookupFeed callback', result.error.code, result.error.message);
						} else {
							// console.info('googe.feeds.lookupFeed returned feed uri:', result.url);
							$('as-from-web-error').setText(URSPIN.l10n.getString('ui.addstuff.dir.fromweb.addedto') + URSPIN.getWebtop().getTabManager().getCurrentTab().getTitle());
							var mod = new URSPIN.FeedModule({'settings':{'feedURI':{'value':result.url}}});
							URSPIN.getWebtop().getTabManager().addNewModule(mod);
						}
					}
				);
			};

			var i2 = new Element('input',{'class':'textfield', 'id':'as-from-web-field-in'});
			i2.addEvent('keypress',function (e) {if (e.code == 13) {onAddClick();e.stop();}}.bindWithEvent());
			
			tfw.adopt(new Element('div',{'class':'tf-c'}).adopt(i2));
			tfw.adopt(new Element('div',{'class':'tf-l'}));
			tfw.adopt(new Element('div',{'class':'tf-r'}));

			e2.adopt(URSPIN.Webtop.buildButton({
				'text':URSPIN.l10n.getString('ui.addstuff.feeduni.add'),
				'iconSrc':'btn_icn_plus',
				'onClick':onAddClick
			}));
			
			e2.adopt(new Element('div',{'class':'cb'}));
			
			e2.adopt(new Element('div',{'id':'as-from-web-error'}));

		} else {
			/*
				Search
			*/
			if (dir.options.hasSearch || dir.options.color == 'orange') {
				dir.setContentSearch();
			}
		}


		// set the style otherwise effect is buggy.
		dir.setStyles(dir.effectPrevTransParams[1]);

		dir.options.breadcrumbs.push(dir);

		return dir;
	},
	
	getTitle: function () {return this.options.title;},

	setTitle: function (title) {
		if ($defined(title)) {
			title = URSPIN.l10n.getString(title) ? URSPIN.l10n.getString(title) : title;
			this.options.title = title;
			this.titleEl.setText(this.options.title);
		}
	},


	// onEffectStart and onEffectComplete will call the apporpriate
	// on(Before)Open|Close functions
	onEffectStart: function () {
		// 'this' refers to Fx.Elements object

		if (this.elements[0].getStyle('margin-left').toInt() == 0) {
			this.elements[0].boundFn.onBeforeClose();
			this.elements[1].boundFn.onBeforeOpen();
		} else {
			this.elements[1].boundFn.onBeforeClose();
			this.elements[0].boundFn.onBeforeOpen();
		}
	},

	onEffectComplete: function () {
		// 'this' refers to Fx.Elements object

		if (this.elements[0].getStyle('margin-left').toInt() == 0) {
			this.elements[1].boundFn.onClose();
			this.elements[0].boundFn.onOpen();
		} else {
			this.elements[0].boundFn.onClose();
			this.elements[1].boundFn.onOpen();
		}
	},


	/*
		Method: openPrev

	    Parameters:

		Returns:

	*/
	openPrev: function () {
		if ($defined(this.effectPrev)) {
			this.effectPrev.start(this.effectPrevTransParams);
		} else {
			throw 'No previous';
		}
	},


	/*
		Method: openNext

	    Parameters:

		Returns:

	*/
	openNext: function (nextSection) {
		if (!$defined(nextSection.effectPrev)) {
			// create effect
			nextSection.effectPrev = new Fx.Elements($$(this, nextSection), this.effectNextPrevOptions);
			nextSection.effectPrev.addEvent('onStart', this.onEffectStart.bind(nextSection.effectPrev));
			nextSection.effectPrev.addEvent('onComplete', this.onEffectComplete.bind(nextSection.effectPrev));
		}

		// the previous effect for the next object is the same as the next effect for this object
		// so they can be the same (i.e. the work on the same elements and the have the same options)
		this.effectNext = nextSection.effectPrev;

		this.effectNext.start(this.effectNextTransParams);
	},

	loadContent: function (options) {
		
		options = options || {};

		if (!$defined(this.content) || options.forceReload) {

			var uri = null;
			if ($chk(this.options.sectionID) && this.options.sectionID != 4) {
				uri = ['services/wt/addstuffdir/section/', URSPIN.l10n.getLocale(), '/', this.options.sectionID, '.json'].join('');
				if (this.options.hasSearch) {
					uri = [uri, '?kw='].join('');
				}
				// var uri = 'services/wt/addstuffdir/section/en/' + this.options.sectionID + '.json';
			} else if ($chk(this.options.feedID)) {
				uri = ['services/wt/addstuffdir/feed/', URSPIN.l10n.getLocale(), '/', encodeURIComponent(this.options.feedID), '.json'].join('');
			} else 	if ($chk(this.options.moduleID)) {
				uri = ['services/wt/addstuffdir/module/', URSPIN.l10n.getLocale(), '/', encodeURIComponent(this.options.moduleID), '.json'].join('');
			} else if ($chk(this.options.collectionID)) {
				uri = ['services/wt/addstuffdir/collection/', URSPIN.l10n.getLocale(), '/', encodeURIComponent(this.options.collectionID), '.json'].join('');
			}

			if ($defined(uri)) {
				this.setContent({'element':this.contentLoadingThrobber});
				this.content = null;

				new XHR({
					'method':'get',
					'onSuccess': function (text, xml) {
						this.content = Json.evaluate(text);
						this.setContent(this.content);
					}.bind(this),
					'onFailure': function (xhr) {
						this.setContent({'error': {'uri':uri,'status':xhr.status,'statusText':xhr.statusText}});
					}.bind(this)
				}).send(uri, null);
			}			
		}
	},

	setContent: function (content) {
		content = content  || {};
		// console.log('AddStuff.DirSection.setContent', content);

		this.setTitle(content.title);

		if ($defined(content.type)) {
			this.getElement('.as-dir-big-icn-img')
				.setStyle('background-image',['url(\'a/images/add_stuff/dir/icon_big/', content.type, '.png\')'].join(''));
		}

		if ($defined(content.color)) {
			this.addClass(['as-dir-', content.color].join(''));
		}

		if (content.hasSearch) {
			this.setContentSearch();
		}
		

		// remove any previous content (e.g. the "loading.." text or throbber)
		this.contentEl.empty();

		if ($defined(content.error)) {

			var m = [
						URSPIN.l10n.getString('ui.basic.error'),
						':<br /><br />\n',
						URSPIN.l10n.getString('ui.addstuff.dir.loaderror'),
						'<br /><br />\n',
						content.error.uri,
						'<br />\n',
						content.error.status,
						' ',
						content.error.statusText
					].join('');

			this.contentEl.adopt(new Element('div',{'class':'as-dir-con-load-err'}).setHTML(m));
		} else if ($defined(content.list)) {

			this.setContentList(content['list'], content['listType']);
		} else if ($defined(content.feed)) {

			this.setContentFeed(content.feed);

		} else if ($defined(content.module)) {

			this.setContentModule(content.module);		

		} else if ($defined(content.collection)) {

			this.setContentCollection(content.collection);		

		} else if ($defined(content.element)) {

			this.contentEl.adopt(content.element);

		} else if ($type(content) == 'string') {

			this.contentEl.setText(content);
		} else {
			
		}
	},
	
	setContentFeed: function (feedRaw) {
		// console.log('setContentFeed');

		var moduleRaw = [];
		moduleRaw[0] = 1;
		moduleRaw[1] = feedRaw[3];
		moduleRaw[2] = 'feed';
		moduleRaw[10] = feedRaw[2];
		moduleRaw[11] = '1.png';
		moduleRaw['s'] = {'feedURI':{'value':feedRaw[1]}};
		this.setContentModule(moduleRaw);
	},
	
	setContentModule: function (moduleRaw) {
		// console.log('setContentModule');

		var module = {
			'moduleID': moduleRaw[0],
			'title': moduleRaw[1],
			'type': moduleRaw[2],
			'contentType': moduleRaw[4],
			'content': moduleRaw[5],
			'contentWidth': moduleRaw[6],
			'contentWidthUnit': moduleRaw[7],
			'contentHeight': moduleRaw[8],
			'contentHeightUnit': moduleRaw[9],
			'desc': moduleRaw[10],
			'previewImageFilename': moduleRaw[11],
			'settings':moduleRaw['s']
		};

		this.setTitle(module.title);

		if ($defined(module.type)) {
			this.getElement('.as-dir-big-icn-img')
				.setStyle('background-image', ['url(\'a/images/add_stuff/dir/icon_big/', module.type, '.png\')'].join(''));
		}

		this.addClass('as-dir-black');

		this.contentTitleEl.setText(URSPIN.l10n.getString('ui.addstuff.dir.preview'));

		var preview = new Element('div',{'class':'as-dir-con-preview'});
		this.contentEl.adopt(preview);

		preview.addClass(['as-dir-con-preview-type-', module.type].join(''));
		preview.adopt(new Element('div',{'class':'as-dir-con-preview-hdr'}));
		preview.adopt();
		var pc =  new Element('div',{'class':'as-dir-con-preview-con'});
		preview.adopt(pc);

		if (module.previewImageFilename) {
			pc.setStyle('background-image', ['url(\'a/images/add_stuff/dir/previews/modules/', module.previewImageFilename, '\')'].join(''));
		} else {
			pc.adopt(new Element('div',{}).setText(URSPIN.l10n.getString('ui.addstuff.dir.nopreview')))
		}
		preview.adopt(new Element('div',{'class':'as-dir-con-preview-ftr'}));

		// preview.adopt(new Element('img',{'src':'a/images/add_stuff/dir/previews/modules/' + module.moduleID + '.png'}));

		

			var desc = new Element('div', {'class':'as-dir-con-desc'});
			this.contentEl.adopt(desc);
			desc.addClass('as-dir-has-scroll');
		if ($defined(module.desc)) {
			desc.setHTML(module.desc.replace(/\n/g, '<br />\n'));
		} else {
			desc.setText(URSPIN.l10n.getString('ui.addstuff.dir.section.nodesc'));
		}

		var btnWrap = new Element('div',{'class':'as-dir-con-add-wrapper'});
		this.contentEl.adopt(btnWrap);

		btnWrap.adopt(URSPIN.Webtop.buildButton({
			'text':URSPIN.l10n.getString('ui.addstuff.dir.btn.add'),
			'iconSrc':'btn_icn_plus',
			'onClick':function () {
				var mod = URSPIN.ModuleFactory.createModule(module);
				// if (module.type == 'feed') {
				// 	var mod = new URSPIN.FeedModule(module);
				// } else {
				// 	var mod = new URSPIN.Module(module);
				// }
				URSPIN.getWebtop().getTabManager().addNewModule(mod);
			}

		}));

		btn = URSPIN.Webtop.buildButton({
			'text':URSPIN.l10n.getString('ui.addstuff.dir.btn.addto'),
			'iconSrc':'btn_icn_dwn_arr'
		});
		btn.addEvent('mousedown', function (e) {
			var menuOptions = {
				'class':'as-dir-add-to-menu',
				'menuItems':[]
			};

			URSPIN.getWebtop().getTabManager().getTabsThatCanAddModules().each(function (tab) {
				menuOptions.menuItems.push({
					'title':tab.getTitle(),
					'onClick':function () {
						var mod = URSPIN.ModuleFactory.createModule(module);
						// if (module.type == 'feed') {
						// 	var mod = new URSPIN.FeedModule(module);
						// } else {
						// 	var mod = new URSPIN.Module(module);
						// }
						tab.moveModule(mod, null, null, {'switchToTab':true});
					}
				});
			});
			
			if ($defined(this.menu) && this.menu.getParent()) {
				this.menu.remove();
			}

			this.menu = new URSPIN.Webtop.Menu(menuOptions); 
			
			var coord = this.getCoordinates();
			this.menu.show({'left':coord.left,'top':coord.bottom + 1});

			e.stop();
		}.bindWithEvent(btn));

		btn.setEnabled(true);
		btnWrap.adopt(btn);


		btnWrap.adopt(new Element('div',{'class':'cb'}));

		// TODO remove module when section is closed
	},
	
	setContentCollection: function (collection) {
		// TODO
		
		this.contentTitleEl.setText(URSPIN.l10n.getString('ui.addstuff.dir.preview'));

		var preview = new Element('div',{'class':'as-dir-con-preview'});
		this.contentEl.adopt(preview);

		// preview.addClass('as-dir-has-scroll');
		preview.adopt(new Element('img', {'src':collection.previewImageSource}));	
	

		var desc = new Element('div', {'class':'as-dir-con-desc'});
		this.contentEl.adopt(desc);

		desc.addClass('as-dir-has-scroll');
		desc.setHTML(collection.desc.replace(/\n/g, '<br />\n'));


		var btnWrap = new Element('div',{'class':'as-dir-con-add-wrapper'});
		this.contentEl.adopt(btnWrap);

		btnWrap.adopt(URSPIN.Webtop.buildButton({
			'text':URSPIN.l10n.getString('ui.addstuff.dir.btn.addtab'),
			'iconSrc':'btn_icn_plus',
			'onClick':function () {
				collection.tabData.iconImgSrc = collection.tabData.iconImgSrc || 'a/images/tab_bar/tab_icon_collection.png';
				var tab = URSPIN.getWebtop().getTabManager().addTabByData(collection.tabData);
				URSPIN.getWebtop().getTabManager().openTab(tab);
			}

		}));
	},

	setContentList: function (list, listType) {
		this.listUL = new Element('div',{'class':'as-dir-con-lst'});
		this.listUL.addClass('as-dir-has-scroll');
		this.contentEl.adopt(this.listUL);
		
		for (var i = 0; i < list.length; i++) {
			var s = null;
			if (listType == 'sections') {
				var s = {
					'sectionID':list[i][0],
					'type':list[i][1],
					'color':list[i][2],
					'loadContent':list[i][3],
					'hasSearch':list[i][4],
					'title':list[i][5],
					'defaultTitle':list[i][6],
					'moduleCount':list[i][7]
				};				
			} else if (listType == 'modules') {
				var s = {
					'moduleID':list[i][0],
					'type':list[i][1],
					'title':list[i][2],
					'feedID':list[i][3] || null
				};
			} else {

			}
			
			var li = new Element('div',{'class':'as-dir-con-lst-i'});
			this.listUL.adopt(li);
			
			
			if ($defined(s.type)) {
				li.adopt(new Element('div',{'class':['icn icn-type-', s.type].join('')}));
			}

			var title =
				(s['title'] || s['defaultTitle'] || '???');
				// + ($defined(s['moduleCount']) ? ' (' + (s['moduleCount'] || 0) + ')' : '');

			li.adopt(
				new Element('a',{'class':'as-dir-con-lst-itm-txt'})
					.adopt(new Element('div',{'class':'as-dir-con-lst-itm-txt-c'}).setText(title))
					.adopt(new Element('div',{'class':'as-dir-con-lst-itm-txt-l'}))
					.adopt(new Element('div',{'class':'as-dir-con-lst-itm-txt-r'}))	
			);

			li.addEvent('mousedown', function (options) {
				options = options || {};

				var id = $defined(options.sectionID) ? ['dir-s', options.sectionID].join('') :
					$defined(options.moduleID) && options.moduleID != 1 ? ['dir-m', options.moduleID].join('') :
					$defined(options.collectionID) ? ['dir-c', options.collectionID].join('') :
					$defined(options.feedID) ? ['dir-f', options.feedID].join('') :
					['dir-r', $random(1, 100000)].join('');
					
				var sec = this.getParent().getElementById(id);

				if (!sec) {
					// section not found, so create it

					// use this section's icon if next section doesn't have one defined
					options.type = options.type || this.options.type;
					options.breadcrumbs = this.options.breadcrumbs.copy();
					options.color = options.color || 'black';

					// Create next section
					sec = new URSPIN.AddStuff.DirSection(options);
					this.getParent().addSection(sec);
				}

				this.openNext(sec);

			}.pass([s], this));
		
		}

		return this.listUL;
	},

	setContentSearch: function () {
		if ($defined(this.getElement('.as-dir-search'))) {
			return;
		}

		var search = new Element('div', {'class':'as-dir-search'});
		this.adopt(search);

		search.adopt(new Element('div', {'class':'as-dir-search-desc'})
			.setText(URSPIN.l10n.getString('ui.addstuff.dir.searchdesc')));
			
		var fieldWrap = new Element('div', {'class':'as-dir-search-field'});
		search.adopt(fieldWrap);

		var c = new Element('div', {'class':'tf-c as-dir-search-field-c'});
		fieldWrap.adopt(c);
		
		var input = new Element('input', {
			'type':'text'
			// 'value':URSPIN.l10n.getString('ui.addstuff.dir.searchdefaulttext')
		});
		c.adopt(input);

		/*
			Events
		*/
		input.addEvent('focus', function (e) {
			// clear any default value
			if (!this.defaultCleared) {
				this.setProperty('value', '');
				this.defaultCleared = true;	
			}
		}.bindWithEvent(input));

		input.addEvent('blur', function (e) {
			// reset if nothing was entered
			
			// TODO: refactor this function as it is almost the same as the
			// click event handler for the "clear button"
			if (this.defaultCleared && !this.valueEntered) {
				// this.setProperty('value', URSPIN.l10n.getString('ui.addstuff.dir.searchdefaulttext'));
				this.defaultCleared = false;
				this.valueEntered = false;

				if (this.xhr) {
					this.xhr.cancel();
					this.xhr = null;
				}
			}
		}.bindWithEvent(input));

		input.addEvent('keypress', function (e) {
			// stop anything else from handling with this event
			e.stopPropagation();
		}.bindWithEvent(input));

		// define the following so that the function below can access this value
		var sectionID = this.options.sectionID;
		var section = this;

		input.addEvent('keyup', function (e) {
			// use keyup instead of keypress because with keypress, the
			// value returned by getProperty('value') doesn't include the
			// latest inputted character
			
			if (e.code == 27) {
				this.blur();
				return;
			}
			
			var value = this.getValue().trim();
			if (value.length >= 0) {
				this.valueEntered = true;
				var uri = ['services/wt/addstuffdir/section/', URSPIN.l10n.getLocale(), '/', encodeURIComponent(sectionID), '.json', '?kw=', encodeURIComponent(value)].join('');

				// console.log('Requesting:', uri);

				// TODO timeout to start request. Wait before sending request
				// when the user first enters characters. See behavior of
				// Mac OS X's Spotlight


				// use XHR instead of Ajax because we can reuse the XHR object
				// with different URIs. Reusing XHR gives us the built-in
				// auto-cancel functionaility
				this.xhr = this.xhr || new XHR({
					'method':'get',
					'autoCancel':true,
					'onSuccess':function (text, xml) {section.setContent(text ? Json.evaluate(text):null);}
				});

				this.xhr.send(uri, null);

				e.stopPropagation();
			}
		}.bindWithEvent(input));

		fieldWrap.adopt(new Element('div', {'class':'tf-l'}));
		fieldWrap.adopt(new Element('div', {'class':'tf-r'}));
		
		search.adopt(URSPIN.Webtop.buildButton({'iconSrc':'btn_icn_mag_glass'}));
		
	}
});
URSPIN.AddStuff.DirSection.implement(new Options);