gCurrentHud = null;
gFxDuration = 250;
// This is needed because the HUD is hidden when
// we're about to show it; therefore its dimensions
// are 0x0
gHudSize = { width: 899, height: 509 };
gRequestPrefix = '/';
gWordCloudGrades = [23];//, 23, 28, 33, 38];
gPortfolioSpotlightCategories = {};
gColorForPortfolioCategory = {
	business: '#F8DFDF',
	systems : '#EAFDD6',
	internet: '#E1E8FD'
}
gCurrentlySpotlitPortfolioItems = [];
gCurrentlySpotlitPortfolioItemCategory = null;
gCurrentlySelectedPortfolioItems = new Hash();

window.addEvent('domready', function() {
	$$('body')[0].addClass(Browser.Engine.name);
	
	if ($('modalLayer')) $('modalLayer').addEvent('click', hideModalLayerAndCurrentHud);
	
	$$('.showsHudOnClick').each(function(elem) {
		elem.addEvent('click', showHud);
	})
	
	$$('.hudCloseButton').each(function(elem) {
		elem.addEvent('click', hideModalLayerAndCurrentHud);
	});
	
	$$('.teamItem').each(createHudForTeamItem);
	
	selectNavLinkForThisPage();
	selectThemeForThisPage();
	removePaddingForThisPage();
	
	if ($('carousel')) {
		new Carousel({
			itemWidth: 152,
			itemsToShow: 4,
			
			container: 'home_carousel',
			carousel: 'carousel',
			previousButton: 'carousel_previous',
			nextButton: 'carousel_next'
		});
	}
	
	if ($('header_search')) {
		$('header_search').fade(0.7);
		$('header_search').addEvent('mouseenter', function() { this.fade(1.0); });
		$('header_search').addEvent('mouseleave', function() { this.fade(0.7); });
	}
	
	$$('a.emailFromSibling').each(createEmailFromSibling);
	layoutPortfolioPage();
	
	showHudForAnchor();
});

/*** Invisible Email Addresses ***/
function createEmailAddressFromName(name) {
	if (!name || name.length == 0) return '';
	return name.charAt(0).toLowerCase() + '.' + name.split(' ')[1].toLowerCase() + '@longworth.com';
}

function createEmailFromSibling(a) {
	var sibling = a.getPrevious();
	if (!sibling) return;
	var address = createEmailAddressFromName(sibling.get('html'));
	a.href = 'mailto:' + address;
	a.set('html', address);
}

/*** Movable Type Custom Fields ***/
function selectNavLinkForThisPage() {
	var div = $('navToSelect');
	if (!div) return;
	var link = $('nav_' + div.get('html'));
	if (link) link.addClass('selected');
}

function selectThemeForThisPage() {
	var themeImage = 'greenleaf';
	if ($('pageTheme')) themeImage = $('pageTheme').get('html');
	if (themeImage == '') themeImage = 'bluebubbles';
	$('layout_header').setStyle('background-image', 'url(/longworth/images/headers/' + themeImage + '.jpg)');
}

function removePaddingForThisPage() {
	if ($('thisPageHasNoPadding')) {
		$('layout_body').setStyles({
			padding: '0',
			width: 850
		});
	}
}

/*** Modal Layer ***/
function showModalLayer() {
	var layer = $('modalLayer');
	layer.setStyles({ opacity: 0, display: 'block' });
	new Fx.Tween(layer, { property: 'opacity', duration: gFxDuration }).start(1.0);
}

function hideModalLayer() {
	var layer = $('modalLayer');
	return new Fx.Tween(layer, { property: 'opacity', duration: gFxDuration }).start(0.0).chain(function() {
		layer.setStyles({ display: 'none' });
	});
}
function hideModalLayerAndCurrentHud() {
	new Fx.Tween(gCurrentHud.getFirst(), {
		property: 'opacity',
		duration: gFxDuration
	}).start(0.0);
	hideModalLayer();
	if (!gCurrentHud) return;
	new Fx.Tween(gCurrentHud, {
		property: 'opacity',
		duration: gFxDuration
	}).start(0.0).chain(function() {
		gCurrentHud = null;
	});
}

/*** HUDs ***/
function showHudForAnchor() {
	var anchor = location.hash.slice(1);
	var target = $$('*[alt=' + anchor + ']')[0];
	if (target) showHud({ target: target });
}

function showHud(event) {
	var target = event.target;
	if (!target.get('alt')) target = event.target.getParent('*[alt]');
	if (!target) return;
	
	var hud = $('hud_' + target.get('alt'));
	if (!hud) return;
	
	if (!$defined(event.client)) event.client = { x: 0, y: 0 };
	var originalStyles = {
		top: event.client.y,
		left: event.client.x,
		opacity: 0.0,
		display: 'block',
		width: 20, height: 20
	};
	hud.store('hudId', target.get('alt'));
	hud.store('originalStyles', originalStyles);
	hud.setStyles(originalStyles);
	hud.getFirst().setStyle('opacity', 0.0);
	
	showModalLayer();
	
	new Fx.Morph(hud).start($merge({
		top: 50,
		left: (window.getSize().x - gHudSize.width) / 2,
		opacity: 1.0,
		duration: 200
	}, gHudSize)).chain(function() {
		gCurrentHud = hud;
		if (target.hasClass('portfolioItem')) {
			loadPortfolioItem();
		} else if (target.hasClass('wordCloudItem')) {
			loadWordCloud();
		} else if (target.hasClass('teamItem')) {
			loadTeamItem();
		} else {
			showCurrentHudContent();
		}
	})
}

function showCurrentHudContent() {
	return new Fx.Tween(gCurrentHud.getFirst(), {
		property: 'opacity',
		duration: gFxDuration
	}).start(1.0);
}

function createHudWithId(id) {
	var hud = $('hud_' + id)
	if (hud) return hud.getFirst();
	
	hud = new Element('div', {
		id: 'hud_' + id,
		'class': 'hud'
	});
	hud.inject($('layout_body'), 'bottom');
	
	var hudContent = new Element('div', { 'class': 'hudContent' });
	hud.adopt(hudContent);
	
	var closeButton = new Element('div', { 'class': 'hudCloseButton' });
	closeButton.addEvent('click', hideModalLayerAndCurrentHud);
	hud.adopt(closeButton);
	
	return hudContent;
}

function createHudForPortfolioItem(img) {
	img.addEvent('click', showHud);
	var hudContent = createHudWithId(img.alt);
	var companyHudImage = new Element('div', {
		'class': 'companyHudImage',
		styles: { 'background-image': 'url(/longworth/images/huds/companies/faded/' + img.alt + '.png)' }
	});
	hudContent.adopt(companyHudImage);
	companyHudImage.adopt(new Element('img', {
		src: '/longworth/images/huds/companies/logos/' + img.alt + '.png'
	}));
	var companyHudContent = new Element('div', { 'class': 'companyHudContent' });
	hudContent.adopt(companyHudContent);
}

function createHudForTeamItem(elem) {
	if ($('hud_' + elem.alt)) return;
	
	var hudContent = createHudWithId(elem.alt);
	var teamHudImage = new Element('div', {
		'class': 'teamHudImage',
		styles: {
			'background-image': 'url(/longworth/images/huds/team/' + elem.alt + '.png)'
		}
	});
	hudContent.adopt(teamHudImage);
	var teamHudContent = new Element('div', { 'class': 'teamHudContent' });
	hudContent.adopt(teamHudContent);
}

function showLoadingIndicator() {
	var div = $('loadingIndicator');
	if (!div) return;
	div.setStyle('display', 'block');
	div.fade('in');
}
function hideLoadingIndicator() {
	var div = $('loadingIndicator');
	if (!div) return;
	new Fx.Tween(div, { property: 'opacity' }).start(0.0).chain(function() {
		div.setStyle('display', 'none');
	});
}

function loadPortfolioItem() {
	var companyHudContent = gCurrentHud.getFirst().getChildren()[1];
	if (companyHudContent.getChildren().length != 0) {
		showCurrentHudContent();
		return;
	}
	
	showLoadingIndicator();
	new Request.HTML({
		url: gRequestPrefix + 'portfolio/' + gCurrentHud.retrieve('hudId') + '.html',
		
		onComplete: hideLoadingIndicator,
		onSuccess: function(tree, elements, html, js) {
			var table = null;
			for (var i = 0; i < elements.length; i++) {
				if (elements[i].get('tag') == 'table') {
					table = elements[i];
					break;
				}
			}
			if (table) table.inject(gCurrentHud.getFirst().getFirst());
			companyHudContent.adopt(tree);
			showCurrentHudContent();
		},
		onFailure: hideModalLayerAndCurrentHud
	}).get();
}

function loadTeamItem() {
	var teamHudContent = gCurrentHud.getFirst().getChildren()[1];
	if (teamHudContent.getChildren().length != 0) {
		showCurrentHudContent();
		return;
	}

	showLoadingIndicator();
	new Request.HTML({
		url: gRequestPrefix + 'team/' + gCurrentHud.retrieve('hudId') + '.html',
		
		onComplete: hideLoadingIndicator,
		onSuccess: function(tree, elements, html, js) {
			teamHudContent.adopt(tree);
			var h1 = teamHudContent.getFirst();
			h1.addClass('teamHudItem_title');
			/*var address = createEmailAddressFromName(h1.get('html'));
			h1.adopt(new Element('a', {
				href: 'mailto:' + address,
				html: address
			}));*/
			showCurrentHudContent();
		},
		onFailure: hideModalLayerAndCurrentHud
	}).get();
}

function loadWordCloud() {
	var content = gCurrentHud.getFirst().getChildren()[1];
	var hudId = gCurrentHud.retrieve('hudId');
	gCurrentHud.getFirst().getFirst().setStyle('background-image', 'url(/longworth/images/huds/industries/' + hudId + '.png)');
	
	if (content.getChildren().length != 0) {
		showCurrentHudContent();
		return;
	}
	
	showLoadingIndicator();
	new Request.HTML({
		url: gRequestPrefix + 'wordclouds/' + hudId + '.html',
		
		onComplete: hideLoadingIndicator,
		onSuccess: function(tree, elements, html, js) {
			/*var p = new Element('p');
			content.adopt(p);*/
			var words = elements[1].get('html').split(',').map(function(s) { return s.clean().replace(/\s/g, ''); });
			//console.log("words =", words);
			var wordIndex = 0, wordsPerGrade = Math.ceil(words.length / gWordCloudGrades.length);
			var halfway = Math.floor(words.length / 2);
			
			content.adopt(new Element('p', {
				html: words.splice(0, halfway).join(' ')
			}));
			var h1 = elements[0];
			var a = new Element('a', {
				href: gRequestPrefix + 'portfolio.html',
				html: h1.get('html')
			});
			content.adopt(h1.empty().adopt(a));
			content.adopt(new Element('p', {
				html: words.join(' ')
			}));
			/*var marginMultiplier = 5;
			//console.log("There are", wordsPerGrade, "WPG");
			for (var gradeIndex = 0; gradeIndex < gWordCloudGrades.length; gradeIndex++) {
				var stopIndex = wordIndex + wordsPerGrade;
				//console.log("Stopping at", stopIndex);
				for (; wordIndex < stopIndex; wordIndex++) {
					var word = words[wordIndex];
					if (!word) break;
					var span = new Element('span', {
						html: word,
						styles: {
							'font-size': gWordCloudGrades[gradeIndex],
							'margin-right': (marginMultiplier * (gradeIndex + 1)) + 5
						}
					});
					p.adopt(span);
				}
			}
			var h1 = elements[0];
			var a = new Element('a', {
				href: gRequestPrefix + 'portfolio.html',
				html: h1.get('html')
			});
			h1.empty().adopt(a).setStyle('font-size', gWordCloudGrades.getLast());
			content.adopt(h1);
			*/
			showCurrentHudContent();
		},
		onFailure: hideModalLayerAndCurrentHud
	}).get();
}

function layoutPortfolioPage() {
	var header = $('portfolio_header');
	var items = $('portfolio_items');
	var footer = $('portfolio_footer');
	if (!header || !items) return;
	
	gNumPortfolioColumns = header.get('colspan').toInt();
	var table = new Element('table', {
		id: 'portfolio_table',
		cellpadding: 0,
		cellspacing: 0,
		border: 0
	});
	$('layout_body').adopt(table);
	
	var parent = header.getParent('table');
	header = header.dispose().removeClass('pageMetadata');
	parent.destroy();
	table.adopt(new Element('thead').adopt(new Element('tr').adopt(header)));
	
	var tbody = new Element('tbody');
	table.adopt(tbody);
	items = items.dispose().getChildren();
	items.push(new Element('dt', { html: 'yourlogohere' }));
	items.push(new Element('dd', { html: 'Please contact a Longworth team member' }));
	
	var index = 0;
	var numItems = items.length;
	var numRows = Math.ceil(numItems / 2 / gNumPortfolioColumns);
	//console.log(numItems / 2, 'items in', numRows, 'rows');
	var column = 1;
	var row = 1;
	
	for (; row < numRows+1; row++) {
		var tr = new Element('tr');
		tbody.adopt(tr);
		if (row == numRows) tr.addClass('lastRow');
		for (column = 1; column < gNumPortfolioColumns+1; column++) {
			var td = new Element('td', {
				'class': (column % 2 == 0 ? 'even' : 'odd') + 'Column'
			});
			tr.adopt(td);
			if (!items[index]) {
				td.addClass('noHover');
				continue;
			}
			
			var company  = items[index].get('html').toLowerCase().clean();
			var title 	 = items[index+1].get('html');
			var category = items[index].get('alt');
			
			var img = new Element('img', {
				src: '/longworth/images/portfolio/' + company + '.png',
				alt: company,
				'class': 'portfolioItem'
			});
			if (company == 'yourlogohere') {
				td.adopt(new Element('a', {
					href: gRequestPrefix + 'faq.html#meeting'
				}).adopt(img));
				td.set('title', title);
				td.addClass('hasTooltip');
			} else {
				img.addClass('showsHudOnClick');
				createHudForPortfolioItem(img);
				td.adopt(img);
				if (title.length > 0) {
					td.set('title', title);
					td.addClass('hasTooltip');
				}
				if (category && category.length > 0) {
					category.split(' ').each(function(c) {
						td.addClass(c + 'Category');
					});
					td.addClass('canBeSpotlit');
				};
			}

			index += 2;
		}
	}
	var tips = new Tips('td.hasTooltip', {
		className: 'portfolioItemTooltip'
	});
	tips.addEvent('show', function(tip, elem) {
		tip.fade(0.85);
	});
	createEventsForPortfolioSpotlights();
	
	/*parent = footer.getParent('table');
	footer = footer.dispose().removeClass('pageMetadata');
	parent.destroy();
	table.adopt(
		new Element('tfoot').adopt(
			new Element('tr').adopt(footer)
		)
	);*/
}

function createEventsForPortfolioSpotlights() {
	$$('.portfolioItemSpotlight').each(function(elem) {
		gPortfolioSpotlightCategories[elem.get('alt')] = $$('td.' + elem.get('alt') + 'Category');
		elem.addEvent('mouseleave', unspotlightPortfolioItems);
		elem.addEvent('mouseenter', spotlightPortfolioItems);
		elem.addEvent('click', setSpotlitPortfolioItems);
	});
	gSpotlightablePortfolioItemTds = $$('table#portfolio_table > tbody > tr > td.canBeSpotlit');
	gSpotlightablePortfolioItemTds.each(function(td) {
		td.store('backgroundColorBeforeSpotlight', td.getStyle('background-color'));
		td.store('colorMorphFx', new Fx.Morph(td, { link: 'chain' }));
		td.store('opacityMorphFx', new Fx.Morph(td, { duration: 200, link: 'chain' }));
	});
}

function setSpotlitPortfolioItems(event) {
	var category = event.target.get('alt');
	if (!category) return;
	
	if (gCurrentlySelectedPortfolioItems.has(category)) {
		//console.log("Releasing", category);
		releaseSpotlitPortfolioItemsForCategory(category);
	} else {
		releaseSpotlitPortfolioItemsForCategory('all');
		//console.log("Setting", category);
		gCurrentlySelectedPortfolioItems.set(category, event.target);
		new Fx.Tween(event.target, {
			property: 'background-color', duration: gFxDuration
		}).start(
			gColorForPortfolioCategory[category]
		);
	}
	//console.log("gCurrentlySelectedPortfolioItems =", gCurrentlySelectedPortfolioItems.toQueryString());
	unspotlightPortfolioItems();
}

function releaseSpotlitPortfolioItemsForCategory(category) {
	if (!category) return;
	
	var _release = function(cat) {
		//console.log("_release(",cat,")");
		if (!gCurrentlySelectedPortfolioItems.get(cat)) return;
		new Fx.Tween(gCurrentlySelectedPortfolioItems.get(cat), {
			property: 'background-color', duration: gFxDuration
		}).start(
			'#FFFFFF'
		);
		gCurrentlySelectedPortfolioItems.erase(cat);
	};
	//console.log("Releasing for category:", category);
	if (category == 'all')
		$H(gColorForPortfolioCategory).getKeys().each(_release);
	else
		_release(category);
}

function spotlightPortfolioItems(event) {
	var category = event.target.get('alt');
	if (!category) return;
	if (gCurrentlySpotlitPortfolioItemCategory == category) return;
	
	gCurrentlySpotlitPortfolioItemCategory = category;
	gCurrentlySpotlitPortfolioItems = gPortfolioSpotlightCategories[gCurrentlySpotlitPortfolioItemCategory];
	// Dim non-spotlit items
	gSpotlightablePortfolioItemTds.each(function(td) {
		if (!gPortfolioSpotlightCategories[gCurrentlySpotlitPortfolioItemCategory].contains(td))
			td.retrieve('opacityMorphFx').start({
				'opacity': 0.1
			});
	});
}
function unspotlightPortfolioItems() {
	// Make sure something is selected
	var selectedCategoriesCount = gCurrentlySelectedPortfolioItems.getKeys().length;
	// Create a RegExp so we can quickly find out if the current td is part of a selected category
	var selectedCategoriesRegexp = new RegExp(gCurrentlySelectedPortfolioItems.getKeys().map(function(key) {
		return key + 'Category';
	}).join('|'));
	gSpotlightablePortfolioItemTds.each(function(td) {
		if (selectedCategoriesCount == 0) {
			// No categories are selected, go ahead and undim them all
			//console.log("selectedCategoriesCount == 0. This td will be restored.");
			td.retrieve('opacityMorphFx').start({ 'opacity': 1.0 });
		} else if (td.getProperty('class').match(selectedCategoriesRegexp) == null) {
			//console.log("This td is NOT in", selectedCategoriesRegexp, ". It will not change.");
			return;
		} else {
			//console.log("This td IS in", selectedCategoriesRegexp, ". It will be restored");
			td.retrieve('opacityMorphFx').start({ 'opacity': 1.0 });
		}
	});
	gCurrentlySpotlitPortfolioItems = [];
	gCurrentlySpotlitPortfolioItemCategory = null;
}

var Carousel = new Class({
	initialize: function(options) {
		this.itemWidth = options.itemWidth;
		this.itemsToShow = options.itemsToShow;
		this.carousel = $(options.carousel);
		this.itemCount = this.carousel.getChildren().length;
		this.carousel.setStyle('width', this.itemWidth * this.itemCount);
		$(options.container).setStyle('width', this.itemWidth * this.itemsToShow);
		this.range = { start: 0, end: this.itemsToShow };
		this.animationDuration = (typeof options.animationDuration) == 'undefined' ? 500 : options.animationDuration;
		
		$(options.nextButton).addEvent('click', this.scrollToLeft.bind(this));
		$(options.previousButton).addEvent('click', this.scrollToRight.bind(this));
	},
	scrollToLeft: function() {
		var coords = this.carousel.getCoordinates();
		this.range.start += this.itemsToShow;
		this.range.end += this.itemsToShow;
		//console.log('Scrolling to left. New range is', this.range.start, '...', this.range.end, '/', this.itemCount);
		//console.log('Moving left from', coords.left, 'to', (this.range.start * this.itemWidth) * -1);
		if (this.range.start >= this.itemCount)
			this.reset();
		else
			new Fx.Morph(this.carousel).start({ 'left': (this.range.start * this.itemWidth) * -1 });
		
	},
	scrollToRight: function() {
		var coords = this.carousel.getCoordinates();
		this.range.start -= this.itemsToShow;
		this.range.end -= this.itemsToShow;
		//console.log('Scrolling to right. New range is', this.range.start, '...', this.range.end, '/', this.itemCount);
		//console.log('Moving left from', coords.left, 'to', (this.range.start * this.itemWidth) * -1);
		if (this.range.start <= 0)
			this.reset(0);
		else
			new Fx.Morph(this.carousel).start({ 'left': (this.range.start * this.itemWidth) * -1 }).chain(function() {
		}.bind(this));
	},
	reset: function(multiplier) {
		if (multiplier == null) multiplier = 1;
		new Fx.Morph(this.carousel, { duration: this.animationDuration * multiplier }).start({ 'left': 0 });
		this.range = { start: 0, end: this.itemsToShow };
		//console.log('Range has been reset to', this.range.start, '...', this.range.end, '/', this.itemCount);
	}
});