var COLOR_STRINGS		= ['people', 'culture', 'brands'],
	PAST_STRING			= 'past', //update this if it changes in html
	OFFICES_STRING		= 'info',
	MEMBER_STRING		= 'member',
	JOB_STRING			= 'job',
	IMG_HOVER_OPACITY	= .8,
	ARTICLE_PADDING		= 30,
	FULL_MENU_HEIGHT	= 102,
	DEFAULT_COLOR		= '#c4273a',
	IE_NAVLINE_SPEED	= 300,
	IE_NAVLINE_EASE		= Fx.Transitions.Quad.easeOut
	MIN_SCREEN_WIDTH	= 1085;

var homeMenuY			= 51,
	subNavY				= 206-51,
	articlePositions	= [],
	currentArticle		= -1,
	navClicked			= false,
	isLoadingRss		= false,
	isHome				= false,
	isNews				= false,
	isEvents			= false,
	isBlogs				= false,
	isAbout				= false,
	isOffices			= false,
	isColorPage			= false,
	isSmallScreen		= false,
	currentOffice		= '',
	peopleColor,
	cultureColor,
	brandsColor,
	hashnav,
	firstHashChange;

window.addEvent('domready', function() {	//document ready
	var delay	= 0;
	if (isIpad) delay = 1000;
	
	setTimeout(function() {
		var wWidth	= window.getSize().x;
		if (wWidth <= MIN_SCREEN_WIDTH) isSmallScreen = true;
		else isSmallScreen	= false;
		
		//if ($$('.all > h1').hasClass('tall')[0]) tallHeading = true;
		
		if (isIpad) {
			FULL_MENU_HEIGHT	= 0;
			$$('body').addClass('ipad');
			
			$$('.toTop').addEvent('click', function(){
				var myFx = new Fx.Scroll(window).toTop();
				return false;
			});
		}
		
		//fix IE header width
		if (isIE) $$('.headercontent').setStyle('max-width', '960px');
		
		iniSlideshows();
		if ($$('body').hasClass('offices')[0]) iniOfficeSlides();
		ini();
		
		window.addEvent('resize', handleResize);
	}, delay);
});

function handleResize() {
	if (!isIpad) {
		var prevScreenSmall	= isSmallScreen;
		
		var wWidth	= window.getSize().x;
		if (wWidth <= MIN_SCREEN_WIDTH) isSmallScreen = true;
		else isSmallScreen	= false;

		if (prevScreenSmall != isSmallScreen) {
			//size went from small --> big or big --> small
			//reset thing here
			onScroll();
			
			if (!isSmallScreen) $$('header nav').setStyle('position', 'fixed');
			
			//TODO: move current-line under submenu
		}
		
		checkBottomMargin();
	}
	
}

function checkBottomMargin() {
	if (!isIpad) {
		//add bottom margin to make sure pages can scroll enough to change url
		var subElement			= $$('.sitecontent article');
		//if (isEvents) subElement= $$('.sitecontent > section');
		if (isBlogs) subElement	= $$('.sitecontent .contentrow');
		
		var lastArticle			= subElement[subElement.length-1],
			currentBottom		= FULL_MENU_HEIGHT + lastArticle.getSize().y + ARTICLE_PADDING,
			windowHeight		= window.getSize().y,
			diff				= windowHeight - currentBottom;
		
		//log('lastArticle.getSize().y = ' + lastArticle.getSize().y);
		//log('currentBottom = ' + currentBottom);
		//log('diff = ' + diff);
		
		if (diff > 0) {
			$$('.all').setStyle('margin-bottom', diff + 'px');
			//log('setting margin : ' + diff);
		} else {
			$$('.all').setStyle('margin-bottom', '30px');
			//log('setting margin : 30px');
		}
	}
}

function ini() {
	window.addEvent('scroll', onScroll);
	
	//mouseover nav to hightlight word in headline
	$$('.leftnav a').addEvent('mouseover', navOver);
	$$('.leftnav a').addEvent('mouseout', navOut);
	
	//disable inactive links
	$$('section nav .inactive').addEvent('click', function() {
		return false;
	});
	
	if ($$('body').hasClass('people')[0] || $$('body').hasClass('culture')[0] || $$('body').hasClass('brands')[0]) {
		isColorPage	= true;
	} else {
		if ($$('body').hasClass('events')[0]) isEvents = true;
		if ($$('body').hasClass('news')[0]) isNews = true;
		else if ($$('body').hasClass('blogs')[0]) isBlogs = true;
		else if ($$('body').hasClass('offices')[0]) isOffices = true;
		else if ($$('body').hasClass('about')[0]) isAbout = true;
		else if ($$('body').hasClass('home')[0]) isHome	= true;
	}
	
	if (isOffices) {
		if (!isIpad) FULL_MENU_HEIGHT += 51;
		iniOffices();
	}
	
	if (isEvents || isNews) {
		$$('article').each(function(el) {
			var article		= el;
				isPastList	= article.hasClass('superpast'),
				toSlide		= article.getElement('.pasthidden'),
				toClick		= article.getElement('h2');
			
			article.setStyle('padding-bottom', '0');
			toClick.setStyle('cursor', 'pointer');
			//toClick.setStyle('padding-bottom', '20px');
			toClick.setStyle('margin-bottom', '0');
			toClick.addEvent('mouseover', setColorRed);
			toClick.addEvent('mouseout', setColorGrey);
			
			var myFx	= new Fx.Slide(toSlide, {
				duration: 700
			});
			
			if (isPastList) myFx.hide();
			
			toClick.addEvent('click', function() {
				myFx.toggle();
				
				if (article.hasClass('open')) {
					article.removeClass('open');
				} else {
					article.addClass('open');
				}
				
				return false;
			});
		});
		
	}
	
	/*if (isNews) {
		$$('.superpast').each(function(el) {
			var article		= el,
				toSlide		= article.getElement('.pasthidden'),
				toClick		= article.getElement('h2');
			
			toClick.addEvent('mouseover', setColorRed);
			toClick.addEvent('mouseout', setColorGrey);
			
			var myFx	= new Fx.Slide(toSlide, {
				duration: 700
			});
			myFx.hide();
			
			toClick.addEvent('click', function() {
				
				article.addClass('open');
				toClick.removeEvent('mouseover', setColorRed);
				toClick.removeEvent('mouseout', setColorGrey);
				toClick.setStyle('color', '#3F3F3F').setStyle('cursor', 'default');
				
				myFx.slideIn();
				
				return false;
			});
		});
	}*/
	
	if (isAbout) {
		$$('.hiddenDownload').each(function(el) {
			var parent	= el.getParent('li'),
				close	= parent.getElements('.closeDownload'),
				link	= parent.getChildren('h3 a');
			
			if (isIpad) link = parent.getChildren('h3'); //for fixing :hover
			
			var myFx	= new Fx.Slide(el, {
				duration: 400
			});
			myFx.hide();
			
			close.setStyle('opacity', 0); //IE fix
			
			link.addEvent('click', function() {
				myFx.slideIn();
				parent.addClass('open');
				close.setStyle('opacity', 1);
				close.setStyle('cursor', 'pointer');
				
				return false;
			});
			
			close.addEvent('click', function() {
				if (parent.hasClass('open')) {
					myFx.slideOut();
					parent.removeClass('open');
					close.setStyle('opacity', 0);
					close.setStyle('cursor', 'default');
				}
			});
		});
	}
	
	if (isIE) setupIE();
	
	
	if (!isLoadingRss) {
		if (!isHome && !isOffices) checkBottomMargin();
		setupSubNav();
	}
}

function setColorRed() {
	this.setStyle('color', DEFAULT_COLOR);
	
	//var datespan	= this.getElement('.date-heading');
	//if (datespan) datespan.setStyle('color', DEFAULT_COLOR);
}

function setColorGrey() {
	this.setStyle('color', '#3F3F3F');
	
	//var datespan	= this.getElement('.date-heading');
	//if (datespan) datespan.setStyle('color', '#b3b3b3');
}

function setupIE() {
	if ($$('body').hasClass('subnavexists')[0]) {
		$$('section nav .submenuLine').set('tween', {
			duration: IE_NAVLINE_SPEED
		});
		/*$$('section nav .submenuLine').set('tween', {
			duration: IE_NAVLINE_SPEED,
			transition: IE_NAVLINE_EASE
		});*/
	}
}

function setupSubNav() {	
	if ($$('body').hasClass('subnavexists')[0]) {
		
		/*var subElement			= $$('.sitecontent article');
		if (isEvents) subElement= $$('.sitecontent > section')
		if (isBlogs) subElement= $$('.sitecontent .contentrow')
		
		//setup subnav selection
		subElement.each(function(el){
			articlePositions.push(el.getPosition().y);
		});*/
		
		$$('section nav li a').addEvent('click', subnavClicked);
		
		//setup hash
		hashnav		= new HashNav();
		window.addEvent('navchange', handleHashChange);
		
		if (!isOffices) {
			firstHashChange	= true;
			hashnav.triggerEvent();
			firstHashChange	= false;
			if (!isIpad) onScroll();
		}
		else {
			var page	= hashnav.getStoredHashData()[1].page;
			if (!page) page = 'london';
			loadOffice(page, true);
		}
	}
	
//	if ($$('body').hasClass('subnavexists')[0]) setSubmenuSelection(window.getScroll().y);
	//setupImageHovers(); //done after loading feeds instead
}

function loadMoreEvents() {
	
}

function onScroll() {

	var scrolled	= window.getScroll().y;
	
	if (isHome && !isIpad) {
		if (scrolled > homeMenuY) {
			$$('nav').setStyle('position', 'fixed');
		} else {
			$$('nav').setStyle('position', 'relative');
		}
	} else if ($$('body').hasClass('subnavexists')[0]) {
		var toCompare	= subNavY,
			toTop		= 0,
			officeTop	= 0;
		
		if (isSmallScreen) {
			toCompare += 51;
		}
		
		if (!isIpad) {
			if (scrolled > toCompare) {
				toTop		+= 51;
				officeTop	+= 102;
				
				if (!isOffices) {
					$$('section nav').setStyle('position', 'fixed').setStyle('top', toTop + 'px').setStyle('z-index', '30');
				} else {
					$$('nav.regions').setStyle('position', 'fixed').setStyle('top', toTop + 'px').setStyle('z-index', '30');
					$$('nav.subnav').setStyle('position', 'fixed').setStyle('top', officeTop + 'px').setStyle('z-index', '31');
				}
				
			} else {
				if (isSmallScreen) {
					//toCompare += 54;
					toTop += 51;
					officeTop += 51;
				}
				
				//fix tall titles
				if (isOffices) {
					toTop		+= 40;
					officeTop	+= 40;
				} else if (isEvents) {
					toTop		+= 40;
				}
				
				toTop		+= 206;
				officeTop	+= 257;
				
				if (!isOffices) {
					$$('section nav').setStyle('position', 'absolute').setStyle('top', toTop + 'px');
				} else {
					$$('nav.regions').setStyle('position', 'absolute').setStyle('top', toTop + 'px');
					$$('nav.subnav').setStyle('position', 'absolute').setStyle('top', officeTop + 'px');
				}
			}
		}
		
		//if screen is small, set the fixed/relative for header menu
		if (isSmallScreen && !isIpad) {
			if (scrolled > homeMenuY) {
				$$('header nav').setStyle('position', 'fixed');
			} else {
				$$('header nav').setStyle('position', 'relative');
			}
		}
		
		setSubmenuSelection(scrolled);
		
		if (isEvents || isNews) {
			//add hash for specific events
			var id	= '';
			var i	= 0;
			var urlString	= 'event';
			if (isNews) urlString = 'article';
			
			$$('.pastevents article').each(function(el){
				var pos		= el.getPosition().y;
				if (scrolled + FULL_MENU_HEIGHT + ARTICLE_PADDING >= pos) id = el.get('id');
				
				i++;
			});
			
			if (id != '') {
				var pastString	= hashnav.getStoredHashData()[1].page;
				hashnav.navigateTo(pastString, urlString + '=' + id);
			} else {
			
			}
		}
	}
}

function setSubmenuSelection(scrolled) {
	//set submenu selection
	var inArticle	= 0;
	
	var subElement			= $$('.sitecontent article');
	if (isEvents || isNews) subElement= $$('.sitecontent > section');
	if (isBlogs) subElement= $$('.sitecontent .contentrow');
	
	var aCount	= 0;
	subElement.each(function(el){
		var pos	= el.getPosition().y;
		if (scrolled + FULL_MENU_HEIGHT + ARTICLE_PADDING >= pos) inArticle = aCount;
		
		aCount++;
	});
	
	if (inArticle != currentArticle) {
		var menulinks	= $$('section nav li a');
		if (isOffices)	{
			menulinks	= [];
			//make sure facility is left out when inactive
			var links = $$('nav.subnav a');
			$$('nav.subnav a').each(function(el) {
				if (!el.hasClass('inactive')) menulinks.push(el);
			});
		} else if (isEvents) { //currently there is only one inactive in events and nowhere eslse
			menulinks	= [];
			$$('section nav li a').each(function(el) {
				if (!el.hasClass('inactive')) menulinks.push(el);
			});
		}
		
		if (!isIpad) {
			if (currentArticle >= 0) menulinks[currentArticle].removeClass('selected');
			menulinks[inArticle].addClass('selected');
			currentArticle	= inArticle;
			
			//move line
			if (!isOffices) { //offices dont have line on subnav
				var line		= $$('section nav .submenuLine');
				if (line) {
					var leftMargin	= 120;
					//var lineLeft	= Math.round( $$('section nav li a')[inArticle].getPosition().x + ($$('section nav li a')[inArticle].getSize().x / 2) - 12.5 );
					var lineLeft	= Math.round( menulinks[inArticle].getPosition().x + (menulinks[inArticle].getSize().x / 2) - 12.5 );
					if (isIE) {
						line.tween('left', lineLeft + 'px');
					} else {
						line.setStyle('left', lineLeft + 'px');
						//line.setStyle('left', '0px');
					}
				}
			}
		}
		
		var href		= menulinks[inArticle].get('href');
		
		if (hashnav.getStoredHashData()[1].page != href) {
			if (isOffices) {
				href		= menulinks[inArticle].getParent('li').get('id');
				var extra	= getCurrentExtra(href);
				hashnav.navigateTo(currentOffice, OFFICES_STRING + '=' + href + extra);
				
				/*var page 	= href.replace('#!/', '');
				var extra	= getCurrentExtra(page);
				hashnav.navigateTo(page, OFFICES_STRING + '=' + getCurrentSlideId(page) + extra);*/
			} else {
				hashnav.navigateTo(href);
			}
		}
	}
}

function navOver() {
	var color	= this.get('class');
	var toColor	= $$('.all h1 .' + color);
	if (toColor) toColor.addClass('color' + color);
}

function navOut() {
	for (var c in COLOR_STRINGS) {
		$$('.all h1 .' + COLOR_STRINGS[c]).removeClass('color' + COLOR_STRINGS[c]);
	}
}

function subnavClicked() {
	navClicked	= true;
}

function handleHashChange(storedHashData) {
	//log('handleHashChange() storedHashData : ');
	//log(storedHashData);
	
	var page		= storedHashData[1].page,
		domId		= page,
		officeChange= false;
	
	if (isOffices) {
		var subpage	= storedHashData[1].pathParsed[OFFICES_STRING];
		handleSubHashChange(page, subpage, storedHashData[1].pathParsed);
	}
	
	//only handle hashchange when link was clicked, not when changed from scrolling
	if (navClicked || firstHashChange) {
		
		navClicked		= false;
		
		if (isOffices) {
			if (currentOffice == storedHashData[1].page) {
				currentOffice	= storedHashData[1].page;
				page 			= storedHashData[1].pathParsed[OFFICES_STRING];
				domId			= 'office_' + page;
			} else {
				//load new office
				
				officeChange	= true;
				loadOffice(page, firstHashChange);
			}
		}
		
		if (!officeChange) {
			var toArticleY	= $(domId).getPosition().y - FULL_MENU_HEIGHT - ARTICLE_PADDING;
			
			if (firstHashChange) {
				
				//check for url for specific past event
				if ((isEvents && page == PAST_STRING) || isNews) {
					var urlString	= 'event';
					if (isNews) urlString = 'article';
					
					var event	= storedHashData[1].pathParsed[urlString];
					var eCount	= 0;
					$$('.pastevents article').each(function(el){
						if (el.get('id') == event) {
							toArticleY	= el.getPosition().y - FULL_MENU_HEIGHT - ARTICLE_PADDING;
						}
						
						eCount++;
					});
					
				} else {
					//TODO: webkit & opera scrolls a bit too much in blogs
				}
			}
			
			if (firstHashChange) { //the first time event is triggered is on page load, so dont animate
				window.scrollTo(0, toArticleY);
			} else {
				var myFx = new Fx.Scroll(window, {
					offset: {
						x: 0,
						y: toArticleY
					}
				}).toTop();
			}
		}
	}
	
	
}

function setupImageHovers() {
	if (!isIpad) {
		$$('section a img').each(function(el){
			var link		= el.getParent('a'),
				image		= el;
			
			if (link.getChildren('.blogSummareImgCont')[0]) {
				image		= link.getChildren('.blogSummareImgCont')[0];
			}
			
			var	size		= image.getSize(),
				addedHtml	= '<div class="hoverimg" style="width:' + size.x + 'px;height:' + size.y + 'px"><div class="bg"></div></div>',
				currentHtml	= link.get('html'),
				parent		= el.getParent('section');
			
			if (!parent.hasClass('flickr')) {
				link.setStyle('display', 'block').setStyle('width', size.x + 'px').setStyle('height', size.y + 'px').setStyle('float', 'left');
				link.setStyle('margin', el.getStyle('margin'));
				link.addClass('imgLink'); //for IE7
				link.set('html', addedHtml + currentHtml);
				
				var myFx = new Fx.Tween(link.getElement('div'), {duration:200});
				myFx.set('opacity', 0);
				
				link.addEvent('mouseover', function() {
					//this.getElement('div').fade(IMG_HOVER_OPACITY);
					myFx.cancel();
					myFx.start('opacity', IMG_HOVER_OPACITY);
					//myFx.start('opacity', 1);
				});
				
				link.addEvent('mouseout', function() {
					myFx.cancel();
					myFx.start('opacity', 0);
				});
			}
		});
	}
}
