/*
	Section: urspin.webtop.js
*/


/*
	Class: URSPIN.Webtop
*/
URSPIN.Webtop = new Class({
	
	addStuff: null,

	/*
		Method: initialize
			Constructor
		
	    Parameters:
			webtopData - Object

	*/

	
	initialize: function (options) {
		document.title = URSPIN.l10n.getString('ui.title');

		// console.dir({'webtop data':options});
		
		var el = $('webtop');

		this.addStuff = new URSPIN.AddStuff();
		// this.addStuff.toggle();
		
		$('hdr-cmd-add-stuff').addEvent('mousedown', this.addStuff.toggle.bind(this.addStuff));
		$('hdr-cmd-add-stuff').getElement('.btn-txt').setText(URSPIN.l10n.getString('ui.cmdbar.l.addstuff'));

		if (options.username) {
			// move 'signed-in' css class to a common, outer element
			el.addClass('signed-in');
			$('page-hdr').addClass('signed-in');
			$('page-hdr-signedinas').setText(options['username']);
			$('page-hdr-signout').addEvent('click', this.signOut);

		} else {
			$('page-hdr').removeClass('signed-in');
		}
		$('page-hdr-r').setStyle('display','block');


		// apply theme skin

		if (options.theme) {
			// options.theme.css_url = '16.css';
			if (options.theme.css_url) {
				new Element('link', {'rel':'stylesheet', 'media':'screen', 'type':'text/css', 'href':'themes/' + options.theme.css_url}).inject(document.head);
			}
		}




		URSPIN.Notify.msg(options.msg);

		if (google) {
			if (!google.search) {
				URSPIN.Notify.msg('Error: Could not load Google AJAX Search API');
			} else {
				$(google.search.Search.getBranding(null, google.search.Search.VERTICAL_BRANDING)).injectTop($('hdr-search-provider-logo'));
			}
			if (!google.feeds) {
				URSPIN.Notify.msg('Error: Could not load Google AJAX Feeds API');
			}

		} else {
			URSPIN.Notify.msg('Error: Could not load initial Google AJAX API script');
		}

		$('hdr-search-btn').replaceWith(
			URSPIN.Webtop.buildButton({
				'onClick':this.search.bind(el),
				'text':URSPIN.l10n.getString('ui.hdr.searchbtn'),
				'id':'hdr-search-btn'
 			}));
		$('hdr-search-q').addEvent('keypress', function (e) {if (e.code == 13) {this.search();e.stop();}}.bindWithEvent(el));
		$('hdr-search-type-w').addEvent('click', function (e) {
			if (e.target.nodeName.toLowerCase() == 'span') {
				var s = $('hdr-search-type-w').getElement('.hdr-search-type-selected');
				if (s) {s.removeClass('hdr-search-type-selected');}
				$(e.target).addClass('hdr-search-type-selected');
			}
		}.bindWithEvent());

		var tabManager = new URSPIN.TabManager(
			options.tabs || [],
			 {'hasAddTabButton':true, 'openedUserTabID':options.openedUserTabID||null, 'taborder':options.taborder});

		this.getTabManager = function () {return tabManager;};




		$(document).addEvent('keypress', this.keyPress.bindWithEvent(el));

		$(document.body).addEvent('mousedown', this.removeMenus);

		$(document.body).addEvent('click', function (e) {
			var el = $(e.target);
			if (el.hasClass('openpopup')) {

				e.stop();

				var popup = $('popup');
				popup.empty();

				$('popup-w').setStyle('display', 'block');

				switch (el.getTag()) {
				case 'img':
					var imgSrc = el.getProperty('src');
					popup.adopt(new Element('img', {'src':imgSrc}));
					break;
				}

				$('popup-w').setStyle('margin-left', -($('popup-w').offsetWidth / 2));
				$('popup-w').setStyle('visibility', 'visible');
			}



		}.bindWithEvent());

		$('popup-w').addEvent('click', function (e) {
			$('popup-w').setStyle('visibility', 'hidden');
			$('popup-w').setStyle('display', 'none');
		});


		// create dock
		// var dock = new URSPIN.Dock(options['dock'] || {});
		// dock.injectInside($(document.body));
		// dock.show();
		// this.getDock = function () {return dock;};



		return $extend(el, this);
	},
	
	search: function () {
		var stype = $('hdr-search-type-w').getElement('.hdr-search-type-selected').getProperty('stype') || 'web';

		$('search-r-bg-top-close').removeEvents('click');
		$('search-r-bg-top-close').addEvent('click', function() {
			$('tab-bar').setStyle('display','block');
			$('content-bodies').setStyle('display','block');
			$('notify-w').setStyle('display','block');
			$('search-results').setStyle('display','none');
		});

		$('tab-bar').setStyle('display','none');
		$('notify-w').setStyle('display','none');
		$('content-bodies').setStyle('display','none');
		$('add-stuff').hide();

		$('search-r-head').setText(URSPIN.l10n.getString(['ui.search.results.header.', (stype || 'web')].join('')));

		// $('search-results-i').empty();
		$('search-results-i').setHTML('<div class="content-body-throbber"></div>');

		$('search-results').setProperty('class', ['search-type-', stype].join(''));
		$('search-results').setStyle('display','block');

		var q = $('hdr-search-q').getProperty('value');

		if (q && q.trim().length > 0) {
			var stype = $('hdr-search-type-w').getElement('.hdr-search-type-selected').getProperty('stype') || 'web';


			switch (stype) {
				case 'images':gs = new google.search.ImageSearch();break;
				case 'videos':gs = new google.search.VideoSearch();break;
				case 'news':gs = new google.search.NewsSearch();break;
				case 'blogs':gs = new google.search.BlogSearch();break;
				case 'local':gs = new google.search.LocalSearch();break;
				case 'web': // fall-through
				default:gs = new google.search.WebSearch();break;
			}

			gs.setNoHtmlGeneration();
			gs.setResultSetSize(google.search.Search.LARGE_RESULTSET);
			gs.setSearchCompleteCallback(this, this.onGoogleSearchResults, [gs, stype]);
			gs.execute(q);
		} else {
			this.onGoogleSearchResults(null, null);
		}
	},
	
	onGoogleSearchResults: function (gs, type) {

		var rw = $('search-results-i');
		rw.empty();

		if (gs && gs.results && gs.results.length > 0) {
			// console.log('onGoogleSearchResults', type);
			// console.dir({'GoogleSearchResults':gs.results});

			for (var i = 0; i < gs.results.length; i++) {
				var r = gs.results[i];

				var h = [];
				h.push('<div class="search-result');h.push(' search-result-type-');h.push(type);h.push('"><div class="search-result-content">');

				switch (type) {
					case 'videos':
						h.push('<a target="_blank" href="');h.push(r.url);h.push('">');
						h.push('<img src="');h.push(r.tbUrl);h.push('" width="130" />');
						h.push('</a>');

						h.push('<div class="txt">');

						h.push('<h2><a target="_blank" href="');h.push(r.url);h.push('">');h.push(r.title);h.push('</a></h2>');
						h.push('<div class="search-result-byline">');
						h.push(r.duration);
						h.push(' - ');h.push(r.published);
						h.push('</div>');

						h.push('<div class="search-result-snippet">');h.push(r.content);h.push('</div>');
						h.push('<div class="search-result-link">');h.push(r.publisher);h.push('</div>');

						h.push('</div><div class="cb"></div>');

						break;
					case 'images':
						h.push('<div class="search-result-image"><a target="_blank" href="');h.push(r.unescapedUrl);h.push('">');
						h.push('<img src="');h.push(r.tbUrl);h.push('" /></a></div>');
						h.push('<div class="search-result-snippet">');h.push(r.content);h.push('</div>');
						h.push('<div class="search-result-image-size">');h.push(r.width);h.push(' x ');h.push(r.height);h.push('</div>');
						h.push('<div class="search-result-link">');h.push(r.visibleUrl);h.push('</div>');
						break;
					case 'news':
					case 'blogs':
					case 'web':
					default:
						h.push('<h2><a target="_blank" href="');h.push(r.unescapedUrl || r.postUrl);h.push('">');h.push(r.title);h.push('</a></h2>');

						if (type == 'news' || type == 'blogs') {
							h.push('<div class="search-result-byline">');
							h.push(r.publisher || r.author);
							if (r.location) {
								h.push(' - ');h.push(r.location);
							}
							if (r.publishedDate) {
								h.push(' - ');h.push(r.publishedDate);
							}
							h.push('</div>');
						}

						h.push('<div class="search-result-snippet">');h.push(r.content);h.push('</div>');
					
						if (type == 'web' || type == 'blogs') {
							h.push('<div class="search-result-link">');h.push(r.visibleUrl || r.blogUrl);h.push('</div>');
						}
						break;
				}

				h.push('</div></div>');

				rw.setHTML(rw.innerHTML, h.join(''));
			}
		} else {
			console.warn('no results');
			rw.setHTML('No results');
		}

		rw.setHTML(rw.innerHTML, '<div class="cb"></div>');

		if (window.ie) {
			var x = $('search-r-bg-mid-c');
			var y = $('search-r-bg-mid');
			if (x.offsetHeight > 326) {
				y.setStyle('height', x.offsetHeight);
			} else {
				y.setStyle('height', '326px');
			}

			rw.setHTML(rw.innerHTML);
		}

	},
	
	
	removeMenus: function () {
		$$('.menu-w').each(function (menu) {
			if (menu.getParent()) {
				menu.remove();
			}
		});
	},
	
	getTabManager: Class.empty,
	
	signOut: function () {
		var xhr = new XHR({
			'onSuccess':function (text, xml) {
				var path = window.location.pathname;
				while (path.length > 0 && path.charAt(path.length - 1) != '/') {
					path = path.substring(0, path.length - 1);
				}
				window.location = ['http://', window.location.host, path, '?signout'].join('');
			}.bind(this)
		});

		var uri = 'services/wt/user/';
		xhr.send(uri, Object.toQueryString({'cmd':'signout'}));
		// show sign out throbber
	},
	
	
	
	
	/*
		Method: keyPress

		Parameters:
			None

		Returns:
			Nohthing
	*/
	keyPress: function (e) {
		// console.info(
		// 	'webtop keypress:',
		// 	(e.alt ? 'alt':''),
		// 	(e.meta ? 'meta':''),
		// 	(e.control ? 'control':''),
		// 	(e.shift ? 'shift':''),
		// 	e.key,
		// 	e.code
		// );

		if (e.target != document.childNodes[1]) {
			return null;
		}

		if (e.code >= 48 && e.code <= 57) {
			var i = e.code - 49;
			i = (i >= 0) ? i : 9;
			return this.getTabManager().openTabByIndex(i);
		}
	
		switch (e.code) {
			case 27://esc
				return this.removeMenus();
				break;
			case 78: //N (shift-n)
				return this.getTabManager().addNewTab();
				break;
			case 110: //n
				return this.getTabManager().openNextTab();
				break;
			case 112: //p
				return this.getTabManager().openPrevTab();
				break;
			case 111: //o
				return;
				break;
		}
		switch (e.key) {
			case '?':
				//TODO show help overlay
				break;
		}

		return null;
	},

	/*
		Method: hide
		
		Parameters:
			None
		
		Returns:
			Nohthing
	*/	
	hide: function () {
		this.setStyles({'display':'none'});
	}
});


URSPIN.Webtop.buildButton =  function (options) {
	options = options || {};
	var a = new Element('span',{'class':'btn alpha'});

	if (options.id) {
		a.setProperty('id', options.id);
	}

	if (options.onClick) {
		a.addEvent('click', options.onClick);

		if (!options.noActive) {
			a.addEvent('mousedown', function () {
				this.addClass('btn_a');
				this.mouseUp = function () {
					$(document).removeEvent('mouseup', this.mouseUp);
					this.removeClass('btn_a');
				}.bind(this);
				$(document).addEvent('mouseup', this.mouseUp);
			}.bind(a));
		}


	} else {
		a.addClass('disabled');
	}



	var c = new Element('div',{'class':'btn-c'});
	if (options.text && options.text.length > 0) {
		c.adopt(new Element('span',{'class':'btn-txt'}).setText(options.text));
	} else {
		c.addClass('btn-c-notext');
	}

	if (options.iconSrc) {
		c.adopt(new Element('div',{'class':['btn-icn btn-icn-', options.iconSrc].join('')}));
	} else {
		c.addClass('btn-c-noimage');
	}

	a.adopt(new Element('div',{'class':'btn-l'}));
	a.adopt(c);
	a.adopt(new Element('div',{'class':'btn-r'}));
	a.adopt(new Element('div',{'class':'cb'}));

	$extend(a, {
		setEnabled: function (enabled) {
			if (enabled) {
				this.removeClass('disabled')
			} else {
				this.addClass('disabled')
			}
		}
	});

	return a;
};



URSPIN.Webtop.Menu = new Class({
	options: {
		'class':null,
		'menuItems':null // array of menuItem objects ({title,onClick})
	},
	
	effectOptions: {'wait':false,'duration':400},
	
	initialize: function (options) {
		this.setOptions(options);
		
		if (!this.options.menuItems) {
			throw 'No menuItems defined';
		}
		
		
		
		var div = new Element('div',{'class':'menu-w'});
		if (this.options['class']) {
			div.addClass(this.options['class']);
		}
		div.adopt(new Element('div',{'class':'menu-hdr'})
			.adopt(new Element('div',{'class':'menu-hdr-c'}))
			.adopt(new Element('div',{'class':'menu-hdr-l'}))
			.adopt(new Element('div',{'class':'menu-hdr-r'}))
		);
		var menuC = new Element('div',{'class':'menu-con'});
		div.adopt(menuC);
		
	
		var bg = new Element('div',{'class':'menu-con-bg'});
		menuC.adopt(bg);

		div.adopt(new Element('div',{'class':'menu-ftr'})
			.adopt(new Element('div',{'class':'menu-ftr-c'}))
			.adopt(new Element('div',{'class':'menu-ftr-l'}))
			.adopt(new Element('div',{'class':'menu-ftr-r'}))
		);

		var ul = new Element('ul',{'class':'menu'});
		menuC.adopt(ul);
		
		for (var i = 0; i < this.options.menuItems.length; i++) {
			var menuItem = this.options.menuItems[i];
			var li = new Element('li');
			if (i == 0) {
				li.addClass('first');
			}
			var a = new Element('span',{'class':'menu-item', 'href':'javascript:void(0);'}).setHTML(menuItem.title);
			li.adopt(a);

			if (menuItem.subMenu && $type(menuItem.subMenu == 'array')) {
				new Element('span',{'class':'menu-item-submenu-icon'}).injectTop(a);
				a.subMenu = menuItem.subMenu;
				a.addEvent('mousedown', function (e) {
					this.getParent().toggleClass('menu-item-submenu-open');
					e.stop();
				}.bindWithEvent(a));

				var x = new Element('div',{'class':'menu-item-submenu-w'});
				li.adopt(x);

				for (var j = 0; j < menuItem.subMenu.length; j++) {
					var subMenu = menuItem.subMenu[j];
					x.adopt(new Element('div',{'class':'menu-item-submenu-item'}).setText(subMenu.title || ''));
				}

			} else if ($type(menuItem.onClick) == "function" ) {
				a.addEvent('mousedown', menuItem.onClick);
			} else {
				a.addClass('disabled');
			}

			ul.adopt(li);
		}

		// var effect = div.effects(this.effectOptions);
		// effect.set({'opacity':0.0});

		
		this.show = function (options) {
			options = options || {};
			// effect.start({'opacity':1.0})
			this.setStyles({'display':'block','left':options.left||0,'top':options.top||0});
			// bg.setStyles('width', ul.offsetWidth, 'height', ul.offsetHeight);
			// menuC.setStyles('width', ul.offsetWidth, 'height', ul.offsetHeight);
			// alert(bg.offsetWidth);

		};
		
		this.hide = function () {
			div.setStyles({'display':'none'});
			// effect.start({'opacity':0.0})
		};

		div.setStyles({'display':'none'});

		$(document.body).adopt(div);

		// Menu bg element is the same size as the menu because it uses:
		// position:absolute;
		// width:100%;
		// height:100%
		// but MSIE 6, doesn't understand so we have to set the pixel size
		if (window.ie6) {
			bg.setStyles({'width':div.offsetWidth,'height':div.offsetHeight});
		}

		return $extend(div, this);
	},
	
	show: Class.empty,
	hide: Class.empty
	
});

URSPIN.Webtop.Menu.implement(new Options, new Events);