/**
 * @author	  Bas
 * @since	   18-sep-2010 22:36:24
 */

function debug(message)
{
	if (typeof console == "object" && console.log)
		console.log(message);
}
if (Browser.ie && Browser.version == 7)
{
	Element.implement('hasAttribute', function(name){
		return this.getProperty(name) == '';
	});
}

var Site = {
	start: function()
	{
		Menu.initialize();
		if (document.id('content') && document.id('content').hasClass('portfolio') && document.id('content').hasClass('overview'))
			PortfolioAnimator.initialize();
		if (document.id('content') && document.id('content').hasClass('employees'))
			OminesTeam.initialize();
		if (document.getElement('.readOptions'))
		{
			var onClickFunc	= function(action){
				var counter = (action == 'left' ? 'justify' : 'left');
				document.id('blog-post-content').removeClass(counter).addClass(action);
				document.id('blog-textalign-'+action).addClass('active');
				document.id('blog-textalign-'+counter).removeClass('active');
				Cookie.write('blogPrefTA', action);
				return false;
			};
			var optionBlock	= document.getElement('.readOptions').addClass('js');
			var cookiePref	= false;
			if (!(cookiePref = Cookie.read('blogPrefTA')))
				cookiePref	= 'left';
			onClickFunc(cookiePref);
			document.id('blog-textalign-justify').addEvent('click', function(){return onClickFunc('justify')});
			document.id('blog-textalign-left').addEvent('click', function(){return onClickFunc('left')});
		}
	}
};

var Menu = {
	timers: {
		menuHover: null,
		menuOut: null
	},
	initialize: function()
	{
		this.mainMenu		= document.id('mainMenu').getFirst('ul');
		this.subContainer	= document.id('subMenus');
		if (!this.mainMenu.getFirst('.active'))
			this.mainMenu.getFirst().addClass('active');
		this.initialMenu	= this.mainMenu.getFirst('.active').get('id');
		this.activeMenu		= this.initialMenu;
		this.baseOffset		= document.id('mainMenu').offsetLeft;
		this.position();
	},
	position: function()
	{
		this.mainMenu.getChildren('li').each(function(li){
			var liMid	= (li.offsetLeft.toInt() - this.baseOffset) + (li.getDimensions().x / 2).toInt();
			li.store('mid', liMid);
			if (document.id('sub-'+li.get('id')))
			{
				var subMenu		= document.id('sub-'+li.get('id'));
				var isActive	= subMenu.hasClass('active');
				subMenu.addClass('active').setStyle('top', '-10000px');
				var subWidth	= subMenu.getWidth() + (subMenu.getChildren('li').length);
				var baseLeft	= (liMid - (subWidth / 2).toInt());
				if (baseLeft + subWidth > this.subContainer.getWidth())
					baseLeft	= this.subContainer.getWidth() - subWidth;
				if (baseLeft < 0)
					baseLeft	= 0;
				subMenu.store('baseLeft', baseLeft);
				subMenu.setStyles({'left': baseLeft, 'top':''});
				if (!isActive)
					subMenu.removeClass('active');
				subMenu.set('morph', {
					duration: 500,
					transition: Fx.Transitions.Sine.easeOut,
					onStart: function(el){
						if (!el.hasClass('active'))
							el.setStyle('display','block');
					},
					onComplete: function(el){
						document.getElements('.subMenu').each(function(ul){
							if (ul.get('id') != 'sub-'+this.activeMenu)
								ul.removeClass('active').removeProperty('style').setStyle('left', ul.retrieve('baseLeft'));
						});
						document.id('sub-'+this.activeMenu).addClass('active').removeProperty('style').setStyle('left', document.id('sub-'+this.activeMenu).retrieve('baseLeft'));
					}.bind(this)
				});
			}
			li.addEvents({
				mouseout:	function() { this.onMouseOut(li.get('id')); }.bind(this),
				mouseover:	function() { this.cancelMouseOut(); this.onMouseOver(li.get('id')); }.bind(this)
			});
		}, this);
	},
	restoreBase: function()
	{
		clearTimeout(this.timers.menuOut);
		clearTimeout(this.timers.menuHover);
		this.displayMenu(this.initialMenu);
	},
	onClick: function(id)
	{
		clearTimeout(this.timers.menuHover);
		this.displayMenu(id);
	},
	onMouseOver: function(id)
	{
		clearTimeout(this.timers.menuOut);
		clearTimeout(this.timers.menuHover);
		this.setHoverTimer(id);
	},
	onMouseOut: function()
	{
		clearTimeout(this.timers.menuHover);
		if (this.activeMenu != this.initialMenu)
			this.setOutTimer();
	},
	setHoverTimer: function(id)
	{
		this.timers.menuHover	= this.onClick.delay(300, this, id);
	},
	setOutTimer: function()
	{
		clearTimeout(this.timers.menuOut);
		clearTimeout(this.timers.menuHover);
		this.timers.menuOut	= this.restoreBase.delay(4000, this);
	},
	cancelMouseOut: function()
	{
		clearTimeout(this.timers.menuOut);
	},
	hideMenu: function(id)
	{
		document.id(id).removeClass('active');
		if (document.id('sub-'+id))
			document.id('sub-'+id).removeClass('active');
	},
	displayMenu: function(id)
	{
		if (id == this.activeMenu)
			return;
		this.mainMenu.getChildren('li').each(function (r) {
			if (!r.hasClass('active'))
			{
				if (document.id('sub-'+r.get('id')))
					document.id('sub-'+r.get('id')).setStyle('display', 'none').removeClass('active');
				return;
			}
			r.removeClass('active');
			if (document.id('sub-'+r.get('id')))
				document.id('sub-'+r.get('id')).morph({'top':-5, 'opacity':.1});
		});
		if (document.id('sub-'+this.activeMenu))
			document.id('sub-'+this.activeMenu).removeEvents('mouseout').removeEvents('mouseover');

		document.id(id).toggleClass('active');
		if (document.id('sub-'+id))
		{
			document.id('sub-'+id).setStyles({'top':-5}).morph({'top':5});
			document.id('sub-'+id).addEvents({
				mouseout:	function() { this.onMouseOut(id); }.bind(this),
				mouseover:	function() { this.cancelMouseOut(id); this.cancelMouseOut(); }.bind(this)
			});
		}
		this.activeMenu	= id;
	},
	activateMenu: function(id)
	{
		if (!document.id(id))
			id	= this.initialMenu;
		document.id(id).addClass('active');
		if (document.id('sub-'+id))
			document.id('sub-'+id).addClass('active');
	}
};

var ShowCase = {
	initialize: function(slides)
	{
		this.preloadQueue	= slides;
		this.previousCaseId	= null;
		this.activeCaseId	= null;
		this.activeCase		= null;
		this.activeSlideIdx	= null;
		this.direction		= 0;
		this.container		= document.id('showcase');
		this.display		= document.id('showcase-inner');
		this.showCases		= [];
		this.repository		= document.id('showcase-slider');
		this.caseList		= document.id('showcase-list');
		this.btnNextCase	= document.id('showcase-next');
		this.btnPrevCase	= document.id('showcase-prev');
		this.currentCase	= this.container.getFirst('.active');
		this.projectInfo	= this.projectTitle = this.projectDesc = this.projectLink = this.caseSlides = this.slideSelect = null;
		if (this.currentCase)
		{
			this.projectInfo	= this.currentCase.getFirst('.project');
			this.projectTitle	= this.projectInfo.getFirst('.title');
			this.projectDesc	= this.projectInfo.getFirst('.desc');
			this.projectLink	= this.projectInfo.getFirst('.link');
			this.slideSelect	= this.projectInfo.getFirst('.slide-select');
			this.caseSlides		= this.currentCase.getFirst('.slides');
		}
		this.showCaseWidth	= false;
		this.slideTimer		= null;
		this.timeout		= 5000;
		this.index			= [];
		
		this.display.getChildren('.showcase').each(function(sc){
			if (!this.showCaseWidth)
				this.showCaseWidth	= sc.offsetWidth;
			var caseKey	= sc.get('id').replace('showcase-','');
			this.index.push(caseKey);
			this.showCases[sc.get('id').replace('showcase-','')]	= {
				id: sc.get('id').replace('showcase-',''),
				title: sc.getFirst('.project').getFirst('.title').get('text'),
				desc: sc.getFirst('.project').getFirst('.desc').get('html'),
				caseLink: sc.getFirst('.project').getFirst('.link').getFirst('a').get('href'),
				slides: [],
				thumb: document.id('thumb-'+sc.get('id')),
				slideSelector: sc.getFirst('.project').getFirst('.slide-select')
			};
		}.bind(this));
		
		if (this.preloadQueue[this.container.getProperty('data-active')])
			this.preloadImages(this.container.getProperty('data-active'));

		if (this.index.length == 0)
			return;

		this.preloadCaseId	= this.container.get('data-active') != '' ? (this.index.indexOf(this.container.get('data-active')) != -1 ? this.container.get('data-active') : false ) : false;
		this.container.removeAttribute('data-active');

		window.addEvent('resize', function(){
			this.handleResize();
		}.bind(this));
		this.initCaseList();
		this.handleResize();
		this.changeShowCase(this.preloadCaseId || this.index[0], 0);
	},
	preloadImages: function(key)
	{
		if (!this.preloadQueue[key] || !document.id('showcase-'+key) || !document.id('showcase-'+key).getFirst('.slides'))
			return;
		Object.each(this.preloadQueue[key].images, function(image, idx){
			var div	= new Element('div', {'class':'slide'});
			div.set('morph', {duration:1000, link:'cancel', transition:Fx.Transitions.Sine.easeOut, onComplete:function() { this.element.removeAttribute('style'); }});
			div.adopt(new Element('img', {'src': image.src, 'alt':image.alt, 'height': 321, 'width': 660}));
			document.id('showcase-'+key).getFirst('.slides').adopt(div);
			this.showCases[key].slides.push({ image: image.src, alt: image.alt, title: '' });
		}.bind(this));
		this.loadSelector(key);
		this.preloadQueue[key]	= false;
	},
	loadSelector: function(showcase)
	{
		var slideOverImage	= document.id('slide-over-default');
		document.id('showcase-'+showcase).getFirst('.project').getFirst('.slide-select').empty();
		document.id('showcase-'+showcase).getFirst('.slides').getChildren('.slide').each(function(sl, idx){
			var image	= sl.getFirst('img');
			if (!document.id('slide-select-'+showcase+'-'+(idx.toInt()+1)))
			{
				debug('Creating slide selector voor '+image.src);
				var sel		= new Element('a', {
					'id': 'slide-select-'+showcase+'-'+(idx.toInt()+1),
					'class': 'slide',
					'href': '#slide'+(idx.toInt()+1),
					'title': image.title
				}).inject(this.showCases[showcase].slideSelector);
				sel.adopt(slideOverImage.clone(true, false));
				sel.addEvent('click', function(){clearTimeout(this.slideTimer); this.rotateSlide(idx, true); return false;}.bind(this));
				sel.set('tween', {
					duration:1000,
					link:'cancel',
					onStart: function(){
						this.element.store('wasActive', this.element.hasClass('active'));
						this.element.setStyle('background-position', (this.element.hasClass('active') ? '-10px' : '0')+' 0');
						this.element.removeClass('active');
					},
					onComplete: function(){
						if (!this.element.retrieve('wasActive'))
							this.element.addClass('active');
						this.element.eliminate('wasActive');
						this.element.removeAttribute('style');
					}
				});
				if (idx == 0)
					sel.addClass('active');
			}
		}.bind(this));
	},
	handleResize: function()
	{
		this.leftMargin	= (document.body.offsetWidth - document.id('wrap').offsetWidth);
		if (this.leftMargin % 2 != 0)
			this.leftMargin++;
		this.leftMargin	= this.leftMargin / 2;
		this.setLeftOffset();
	},
	initCaseList: function()
	{
		this.index.each(function(sck){
			var sc			= this.showCases[sck];
			document.id('thumb-'+sc.id).set('tween',{duration:500}).addEvent('click', function(){
				this.changeShowCase(sck, (this.index.indexOf(sck) < this.index.indexOf(this.activeCaseId) ? -1 : 1));
				return false;
			}.bind(this));
			document.id('showcase-'+sc.id).removeClass('hidden');
			if (this.preloadCaseId && sck == this.preloadCaseId)
			{
				document.id('thumb-'+sc.id).addClass('active');
				document.id('showcase-'+sc.id).addClass('active');
				this.currentCase	= document.id('showcase-'+sc.id);
				this.projectInfo	= this.currentCase.getFirst('.project');
				this.projectTitle	= this.projectInfo.getFirst('.title');
				this.projectDesc	= this.projectInfo.getFirst('.desc');
				this.projectLink	= this.projectInfo.getFirst('.link');
				this.slideSelect	= this.projectInfo.getFirst('.slide-select');
				this.caseSlides		= this.currentCase.getFirst('.slides');
			}
			var caseImage	= document.id('thumb-'+sc.id).getFirst('a').getFirst('img');
			if (caseImage.get('alt') != caseImage.getAttribute('alt'))
				caseImage.set('alt', caseImage.getAttribute('alt'));
			caseImage.getParent().set('title', caseImage.get('alt'));
		}.bind(this));
		if (!this.preloadCaseId)
			this.caseList.getFirst().addClass('active');
		this.display.setStyle('width', this.index.length * this.showCaseWidth);
		this.caseListFx		= new Fx.Tween(this.caseList, {
			duration:500,
			onComplete:function(){this.caseList.getElements('li').each(function(li){li.setStyle('text-align', '');});}.bind(this)
		});
		this.containerFx	= new Fx.Tween(this.display, {
			duration:500,
			onComplete:function(){
				this.activeSlideIdx	= 0;
				var t	= this.display.getFirst('.active');
				if (!t) t = this.display.getFirst().addClass('active');
				if (this.direction == 1 && t.getNext('.showcase'))
					t.getNext('.showcase').addClass('active');
				else if (this.direction == -1 && t.getPrevious('.showcase'))
					t.getPrevious('.showcase').addClass('active');
				else
					this.display.getFirst('.showcase').addClass('active');
				t.removeClass('active');
				this.caseSlides		= this.display.getFirst('.active').getFirst('.slides');
				this.slideSelect	= this.display.getFirst('.active').getFirst('.project').getFirst('.slide-select');
				this.slideSelect.getFirst('.slide').addClass('active');
				t.getFirst('.project').getChildren('.slide-select').getChildren()[0].each(function(s,idx){s.removeClass('active'); if (idx == 0) { s.addClass('active'); }});

				if (this.previousCaseId)
					document.id('showcase-'+this.previousCaseId).getElements('.slides .slide').each(function(s, i){
						if (s.hasAttribute('style')) s.removeAttribute('style');
						if (i==0) s.setStyle('z-index',1);
					});
				clearTimeout(this.slideTimer);
				this.slideTimer	= this.rotateSlide.delay(this.timeout, this, [1, false]);
			}.bind(this)
		});
		this.activeCaseId	= this.preloadCaseId;
		this.activeCase		= this.showCases[this.activeCaseId];
		this.setLeftOffset();
		this.display.setStyle('left', -1 * (this.showCaseWidth * this.index.indexOf(this.activeCaseId)).toInt());
		if (this.index.length > 1)
		{
			this.btnNextCase.removeClass('hidden disabled').addEvent('click', function(){ return this.nextCase(); }.bind(this));
			this.btnPrevCase.removeClass('hidden disabled').addEvent('click', function(){ return this.prevCase(); }.bind(this));
		}
	},
	changeShowCase: function(caseKey, direction)
	{
		if (this.slideTimer)
			clearTimeout(this.slideTimer);
		this.preloadImages(caseKey);
		this.direction		= direction || 0;
		if (!this.showCases[caseKey])
			return;
		this.previousCaseId	= this.activeCaseId;
		this.activeCaseId	= caseKey;
		this.activeCase		= this.showCases[this.activeCaseId];
		document.id('showcase-'+this.activeCaseId).getElements('.slides .slide').each(function(s, i){
			if (s.hasAttribute('style')) s.removeAttribute('style');
			if (i==0) s.setStyle('z-index',1);
		});
		if (this.direction == 1)
			document.id('thumb-'+this.activeCaseId).setStyle('text-align','right');
		if (this.direction != 0)
			this.containerFx.start('left', (-1 * (this.index.indexOf(caseKey) * this.showCaseWidth))+'px');
		else
			this.slideTimer	= this.rotateSlide.delay(this.timeout, this, [1, false]);
		this.caseList.getChildren().each(function(li, idx){
			li.removeClass('active');
			if (idx == this.index.indexOf(caseKey))
				li.addClass('active');
		}.bind(this));
		this.setLeftOffset();
//		if (this.index.length > 1)
//		{
//			this.btnPrevCase.removeEvents('click');
//			this.btnNextCase.removeEvents('click');
//			if (this.index.indexOf(this.activeCaseId) == 0)
//				this.btnPrevCase.addClass('disabled').addEvent('click', function(){return false;});
//			else
//				this.btnPrevCase.removeClass('disabled').addEvent('click', function(){ return this.prevCase(); }.bind(this));
//			if (this.index.indexOf(this.activeCaseId) == this.index.length - 1)
//				this.btnNextCase.addClass('disabled').addEvent('click', function(){return false;});
//			else
//				this.btnNextCase.removeClass('disabled').addEvent('click', function(){ return this.nextCase(); }.bind(this));
//		}
		this.preloadCaseId	= false;
	},
	prevCase:function() {
		if (this.index[this.index.indexOf(this.activeCaseId)-1])
			this.changeShowCase(this.index[this.index.indexOf(this.activeCaseId)-1], -1);
		else
			this.changeShowCase(this.index[this.index.length-1], 1);
		return false;
	},
	nextCase:function() {
		if (this.index[this.index.indexOf(this.activeCaseId)+1])
			this.changeShowCase(this.index[this.index.indexOf(this.activeCaseId)+1], 1);
		else
			this.changeShowCase(this.index[0], -1);
		return false;
	},
	rotateSlide: function(slideIndex, noEffect)
	{
		this.caseSlides		= this.display.getFirst('.active').getFirst('.slides');
		this.slideSelect	= this.display.getFirst('.active').getFirst('.project').getFirst('.slide-select');
		var csc	= this.caseSlides.getChildren('.slide');
		var ssc	= this.slideSelect.getChildren('.slide');
		if (this.activeSlideIdx == null)
			this.activeSlideIdx	= 0;
		if (slideIndex === false)
			slideIndex	= this.activeSlideIdx + 1;
		if (slideIndex == this.activeSlideIdx)
			return;
		clearTimeout(this.slideTimer);
		if (slideIndex >= csc.length)
		{
			if (this.index.length > 1)
			{
				clearTimeout(this.slideTimer);
				this.changeShowCase(this.index[this.index.indexOf(this.activeCaseId) + 1] || this.index[0], 1);
				csc.each(function(slide, idx){ slide.removeClass('active').removeAttribute('style'); });
//				csc[0].addClass('active').setStyle('z-index',1);
				ssc.each(function(slide, idx){ slide.removeClass('active'); });
//				ssc[0].addClass('active');
				return;
			}
			slideIndex	= this.activeSlideIdx	= 0;
		}
		else
		{
			csc[this.activeSlideIdx].setStyle('z-index',2);
			csc[slideIndex].setStyle('z-index',1);
			csc[this.activeSlideIdx].morph({'opacity':0, 'top':5});
		}
		csc.each(function(slide, idx){ slide.removeClass('active'); });
		csc[slideIndex].addClass('active');
		if (noEffect)
		{
			if (ssc[this.activeSlideIdx].hasAttribute('style'))
				ssc[this.activeSlideIdx].removeAttribute('style');
			if (ssc[slideIndex].hasAttribute('style'))
				ssc[slideIndex].removeAttribute('style');
			ssc[this.activeSlideIdx].removeClass('active');
			ssc[slideIndex].addClass('active');
		}
		else
		{
			ssc[this.activeSlideIdx].tween('background-position', '-10px 0', '0 0');
			ssc[slideIndex].tween('background-position', '0 0', '10px 0');
		}
		this.activeSlideIdx	= slideIndex;
		this.slideTimer	= this.rotateSlide.delay(this.timeout, this, slideIndex + 1);
	},
	setLeftOffset:function()
	{
		if (!this.caseItemWidth)
		{
			this.caseItemWidth	= 0;
			var c = this.caseList.getFirst(':not(.active)');
			this.caseItemWidth	= c.offsetWidth + c.getStyle('margin-left').toInt() + c.getStyle('margin-right').toInt();
			var c = this.caseList.getFirst('.active');
			this.activeItemWidth	= c.offsetWidth + c.getStyle('margin-left').toInt() + c.getStyle('margin-right').toInt();
		}
		var newLeft	= this.leftMargin - (this.index.indexOf(this.activeCaseId) * this.caseItemWidth) - this.caseList.getFirst().getStyle('margin-left').toInt();
		if (!(newLeft > 0 || newLeft < 0))
			newLeft = 0;
		if (this.direction == 0)
			this.caseList.setStyle('left', newLeft);
		else
			this.caseListFx.start('left', newLeft);
	}
};

var PortfolioAnimator = {
	initialize: function()
	{
		this.targetImages	= document.getElements('.caseImage img');
		this.currentIndex	= 0;
		if (this.targetImages.length < 1)
			return;
		//this.targetImages.shuffle();
		this.targetImages.each(function(img){
			img.set('morph', {
				duration: 100,
				link: 'ignore',
				transition: Fx.Transitions.Sine.easeOut,
				onComplete: function(el){ el.removeAttribute('style'); this.runNext(); }.bind(this)
			});
			img.setStyles({'height':'120px', 'width':'180px', 'margin-left':'15px', 'margin-top':'23px', 'opacity':'.1'})
		}, this);
		this.runNext.delay(500, this);
	},
	runNext: function()
	{
		if (!this.targetImages[this.currentIndex])
			return;
		this.targetImages[this.currentIndex].morph({
			'height':'150px',
			'width':'225px',
			'margin-left':0,
			'margin-top':0,
			'opacity':1
		});
		this.currentIndex++;
	}
};

var OminesTeam = {
	initialize: function()
	{
		this.tabs		= document.id('employees-nav').getElements('li');
		this.employees	= document.id('content').getChildren('.employee');
		this.baseUri	= document.id('employees-nav').get('data-baseuri');
		
		this.state			= false;
		this.stateSupport	= ('state' in history);
		if (this.stateSupport)
		{
			if (history.state)
			{
				this.state		= history.state.activeId;
				if (document.id('employee-'+this.state))
					this.toggleTab(this.state);
			}
			this.tabs.each(function(li){
				var eId	= li.get('id').substring(13);
				li.getFirst('a').addEvent('click', function(e){
					e.preventDefault();
					history.pushState({activeId: eId}, '', this.baseUri + eId);
					this.toggleTab(eId);
					return false;
				}.bind(this));
			}.bind(this));
			window.onpopstate = function(e){ this.toggleTab(e.state.activeId); }.bind(this);
		}
		if (document.id('employees-nav').getElements('li.active').length == 0)
		{
			if (this.stateSupport)
			{
				var id	= this.tabs[0].get('id').substring(13);
				history.pushState({activeId: id}, '', this.baseUri + id);
				this.toggleTab(id);
			}
			else
				window.location.href	= this.tabs[0].getFirst('a').get('href');
		}
	},
	toggleTab: function(id)
	{
		document.id('nav-employee-'+id).getSiblings().each(function(li){ li.removeClass('active');document.id(li.get('id').substring(4)).removeClass('active'); });
		document.id('nav-employee-'+id).addClass('active');
		document.id('employee-'+id).addClass('active');
		document.title	= document.id('employee-'+id).getFirst('h1').get('text') + ' \u00bb Omines';
	}
};

window.addEvent('domready', function(){Site.start();});
