/**
 * Starts executing the initializing functions when either the DOM structure of the page has been loaded ('domready'), or the entire page ('load').
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @uses Mootools 1.2.2 JavaScript Library
 */
window.addEvents({
	'domready': function() {
		initDebugger(); // TEMP
		
		initExternalLinks();
		initMainNavDropDownMenu();
		initPaginatorCentering();
		initSubmitButtons();
		initLoginBox();
		
		fixIE6MainNav();
		fixIE6PushboxTeaserList();
		fixIE6NewsList();
		fixIE6DownloadList();
		fixIE6ContactForm();
		
		fixIE7DownloadSearchbox();
	},
	'load': function() {
		initPushbox();
		initGalleryLightbox();
		loadPartnerOverview();
	}
});



/**
 * initDebugger
 * In case the Firebug add-on is present in Firefox, it's console is used (only when enabled), else an alert is shown instead.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @usage log(my_variable);
 * @return void
 */
function initDebugger() {
	log = (Browser.Engine.gecko && window.console) ? function(msg){console.log(msg)} : function(msg){alert(msg)};
}



/**
 * initExternalLinks
 * Opens external links valid in a new window without the target attribute.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @uses <a href="http://www.google.com/" class="external">Google</a>
 */
function initExternalLinks() {
	var arrExternalLinks = $$('a.external');
	if (arrExternalLinks.length == 0) return;
	
	arrExternalLinks.each(function(elExternalLink) {
		elExternalLink.addEvent('click', function(event) {
			event.stop();
			window.open(this.get('href'));   
		});
	});
}



/**
 * initMainNavDropDownMenu
 * Shows the submenus for each main button, and calculates the needed offsets.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function initMainNavDropDownMenu() {
	if (!$('header')) return;
	if (!$('header').getElement('.main_nav')) return;
	
	var elMainNav = $('header').getElement('.main_nav');
	var intMainNavMinHeight = elMainNav.getStyle('min-height').toInt();
	var arrMainNavItems = elMainNav.getChildren('li');
	
	var showMainNavSubMenu = function(elMainNavItem){
		elMainNavItem.getElement('ul').show();
		elMainNavItem.getElement('a').removeClass('blurred');
		elMainNav.setStyle('height', elMainNavItem.getElement('a').getHeight() + elMainNavItem.getElement('ul').getHeight());
	}
	
	var hideMainNavSubMenu = function(elMainNavItem){
		elMainNavItem.getElement('ul').hide();
		elMainNavItem.getElement('a').addClass('blurred');
	}
	
	var showMainNavSubMenuActive = function(elMainNavItem){
		if (elMainNavItem.getElement('ul')) {
			if (elMainNavItem.hasClass('active')) {
				showMainNavSubMenu(elMainNavItem);
			} else {
				hideMainNavSubMenu(elMainNavItem);
			}
		} else {
			if (elMainNavItem.hasClass('active')) {
				elMainNavItem.getElement('a').removeClass('blurred');
			} else {
				elMainNavItem.getElement('a').addClass('blurred');
			}
		}
	}
	
	var showMainNavSubMenuHover = function(elMainNavItem, elMainNavBtn){
		if (elMainNavItem.getElement('ul')) {
			if (elMainNavItem == elMainNavBtn.getParent()) {
				showMainNavSubMenu(elMainNavItem);
			} else {
				hideMainNavSubMenu(elMainNavItem);
			}
		} else {
			if (elMainNavItem == elMainNavBtn.getParent()) {
				elMainNavItem.getElement('a').removeClass('blurred');
			} else {
				elMainNavItem.getElement('a').addClass('blurred');
			}
		}
	}
	
	arrMainNavItems.each(function(elMainNavItem){
		var elMainNavBtn = elMainNavItem.getElement('a');
		var elMainNavSubNav = elMainNavItem.getElement('ul');
		
		elMainNavItem.addEvents({
			'mouseenter': function(){
				this.addClass('hover');
				arrMainNavItems.each(function(elMainNavItem){
					showMainNavSubMenuHover(elMainNavItem, elMainNavBtn);
				});
				if (!this.getElement('ul')) elMainNav.setStyle('height', elMainNav.getStyle('min-height').toInt());
			},
			'mouseleave': function(){
				this.removeClass('hover');
				arrMainNavItems.each(function(elMainNavItem){
					showMainNavSubMenuActive(elMainNavItem);
				});
			}
		});
		
		showMainNavSubMenuActive(elMainNavItem);
	});
}



/**
 * initPaginatorCentering
 * Centers all paginators within its parent element.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function initPaginatorCentering() {
	arrPaginators = $$('.paginator');
	if (arrPaginators.length == 0) return;
	
	arrPaginators.each(function(elPaginator){
		elPaginator.setStyle('margin-left', (elPaginator.getParent().getWidth() - elPaginator.getWidth()) / 2);
	});
}



/**
 * initSubmitButtons
 * If a submit button is detected, clicking on it will submit the form it is in.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function initSubmitButtons() {
	arrSubmitButtons = $$('.submit');
	if (arrSubmitButtons.length == 0) return;
	
	arrSubmitButtons.each(function(elSubmitButton){
		elSubmitButton.addEvent('click', function(event) {	
			event.stop();
			this.blur();
			
			elSubmitButton.getParent('form').submit();
		});
	});
}



/**
 * initLoginBox
 * Shows the loginbox when hovering over the initial login button.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function initLoginBox() {
	if (!document.getElement('.loginbox')) return;
	
	var elLoginBox = document.getElement('.loginbox');
	var elLoginButton = elLoginBox.getElement('.login_toggler');
	var elLoginFieldset = elLoginBox.getElement('fieldset');
	
	elLoginButton.addEvent('mouseenter', function(){
		elLoginBox.addClass('active');
		elLoginButton.addClass('hidden');
		elLoginFieldset.removeClass('hidden');
	});
	
	elLoginFieldset.addEvent('mouseleave', function(){
		elLoginBox.removeClass('active');
		elLoginButton.removeClass('hidden');
		elLoginFieldset.addClass('hidden');
	});
}



/**
 * initPushbox
 * Adds slideshow functionality to the pushbox on the homepage.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function initPushbox(){
	if (!document.getElement('.pushbox')) return;
	
	var intTeaserNavOpeningDuration = 1000;
	var intTeaserEffectDuration = 1500;
	var intPushboxSlideshowInterval = 8000;
	
	var elPushbox = document.getElement('.pushbox');
	var elTeaserNavHolder = elPushbox.getElement('.teaser_nav_holder');
	var elTeaserNav = elTeaserNavHolder.getElement('.teaser_nav');
	var arrTeaserNavButtons = elTeaserNav.getElements('a');
	var elTeaserNavShadow = elTeaserNavHolder.getElement('.teaser_nav_shadow');
	var elTeaser = elPushbox.getElement('.teaser');
	var elTeaserList = elTeaser.getElement('.teaser_list');
	var arrTeaserContainers = elTeaserList.getChildren('li');
	var intTeaserContainerActive = 0;

	/* Opening animation for the navigation and its schadow. */
	var fxTeaserNavHolderTween = new Fx.Tween(elTeaserNavHolder, {duration: intTeaserNavOpeningDuration, transition: Fx.Transitions.Pow.easeOut});
	fxTeaserNavHolderTween.start('right', 0);
	var fxTeaserNavShadowTween = new Fx.Tween(elTeaserNavShadow, {duration: intTeaserNavOpeningDuration, transition: Fx.Transitions.Pow.easeOut});
	fxTeaserNavShadowTween.start('left', elTeaserNavHolder.getWidth(), 0);
	
	/* Measures maximum heights and paddings for the containers. */
	var intTeaserContainerHeightMax = 0;
	var intTeaserContainerVertPaddings = 0;
	arrTeaserContainers.each(function(elTeaserContainer){
		var elTeaserVisual = elTeaserContainer.getElement('img');
		if (elTeaserVisual != null) {
			if (elTeaserVisual.getHeight() > intTeaserContainerHeightMax) {
				intTeaserContainerHeightMax = elTeaserVisual.getHeight();
			}
		}
		
		var elTeaserContent = elTeaserContainer.getElement('.teaser_content');
		if (elTeaserContent != null) {
			if (elTeaserContent.getHeight() > intTeaserContainerHeightMax) {
				intTeaserContainerHeightMax = elTeaserContent.getHeight();
			}
		}
		if (intTeaserContainerVertPaddings == 0) intTeaserContainerVertPaddings = elTeaserContainer.getStyle('padding-top').toInt() + elTeaserContainer.getStyle('padding-bottom').toInt();
	});

	/* Assigns equal heights to the containers and parent. */
	var intTeaserContainerHeightMaxFull = intTeaserContainerHeightMax + intTeaserContainerVertPaddings;
	arrTeaserContainers.each(function(elTeaserContainer){
		var elTeaserVisual = elTeaserContainer.getElement('img');
		var elTeaserContent = elTeaserContainer.getElement('.teaser_content');
		
		elTeaserContainer.getParent().setStyle('height', intTeaserContainerHeightMaxFull);
		elTeaserContainer.setStyle('height', intTeaserContainerHeightMax);
		if (elTeaserContent != null) {
			elTeaserContent.setStyle('height', intTeaserContainerHeightMax - intTeaserContainerVertPaddings - 5);
			if (elTeaserContainer != arrTeaserContainers[0]) elTeaserContent.setStyle('top', intTeaserContainerHeightMaxFull);
		}
		if (elTeaserVisual != null) {
			if (elTeaserContainer != arrTeaserContainers[0]) elTeaserVisual.setOpacity(0);
		}
	});

	/* Defines the navigation events. */
	arrTeaserNavButtons.each(function(elTeaserNavButton, intTeaserNavButton){
		elTeaserNavButton.addEvent('click', function(event){
			event.stop();
			intTeaserContainerActive = intTeaserNavButton;
			activateTeaserNavButton(intTeaserNavButton);
			showTeaserContainer(intTeaserNavButton);
		});
	});
	
	/* Activates a navigation button. */
	activateTeaserNavButton = function(intTeaserNavButtonActive) {
		arrTeaserNavButtons.each(function(elTeaserNavButton){
			elTeaserNavButton.getParent().removeClass('active');
		});
		arrTeaserNavButtons[intTeaserNavButtonActive].getParent().addClass('active');
	}
	
	/* Shows a specific container. */
	showTeaserContainer = function(intTeaserContainerActive){
		arrTeaserContainers.each(function(elTeaserContainer, intTeaserContainer){
			var elTeaserVisual = elTeaserContainer.getElement('img');
			var elTeaserContent = elTeaserContainer.getElement('.teaser_content');
			
			if (elTeaserVisual != null) {
				var fxTeaserVisualTween = new Fx.Tween(elTeaserVisual, {duration: intTeaserEffectDuration, transition: Fx.Transitions.Quint.easeInOut});
			}
			if (elTeaserContent != null) {
				var fxTeaserContentTween = new Fx.Tween(elTeaserContent, {duration: intTeaserEffectDuration, transition: Fx.Transitions.Quint.easeInOut});
			}
			
			if (intTeaserContainerActive == intTeaserContainer) {
				elTeaserContainer.addClass('active');
				if (fxTeaserVisualTween != null) fxTeaserVisualTween.start('opacity', 1);
				if (fxTeaserContentTween != null) fxTeaserContentTween.start('top', 10);
			} else {
				elTeaserContainer.removeClass('active');
				if (fxTeaserVisualTween != null) fxTeaserVisualTween.start('opacity', 0);
				if (fxTeaserContentTween != null) fxTeaserContentTween.start('top', intTeaserContainerHeightMaxFull);
			}
		});
	}
	
	/* Adds slideshow functionality to the pushbox. */
	showNextSlide = function() {
		intTeaserContainerActive = (intTeaserContainerActive == arrTeaserContainers.length - 1) ? 0 : intTeaserContainerActive + 1;
		activateTeaserNavButton(intTeaserContainerActive);
		showTeaserContainer(intTeaserContainerActive);
	}
	var playPushboxSlideshow = showNextSlide.periodical(intPushboxSlideshowInterval);
	
	/* Stops the slideshow from playing when navigating within the pushbox, and resumes when the mouse is out of it. */
	elPushbox.addEvents({
		'mouseenter': function(){
			$clear(playPushboxSlideshow);
		},
		'mouseleave': function(){
			playPushboxSlideshow = showNextSlide.periodical(intPushboxSlideshowInterval);
		}
	});
}



/**
 * initGalleryLightbox
 * Opens an image gallery with thumbnails in a lightbox.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function initGalleryLightbox(){
	if (!document.getElement('.alsosee_gallery')) return;
	
	var elAlsoseeGallery = document.getElement('.alsosee_gallery');
	var elGalleryLink = elAlsoseeGallery.getElement('.gallery_link');
	
	elGalleryLink.addEvent('click', function(){
		Shadowbox.open({
			player: 'html',
			content: $('gallery_holder').get('html'),
			width: 670,
			height: 620,
			options: {
				onFinish: function(){
					initGallery();
				}
			}
		});
	});
	
	initGallery = function(){
		var blnAutoPlay = false;
		var intGalleryIntervalSeconds = 8;
		var intSlideNumberActive = 0;
		
		var elShadowboxContent = $('sb-content');
		elGalleryProjection = elShadowboxContent.getElement('.gallery_projection').getElement('img');
		elGallerySlidesViewport = elShadowboxContent.getElement('.gallery_slides_viewport');
		elGallerySlidesList = elShadowboxContent.getElement('.gallery_slides_list');
		arrGallerySlidesLinks = elGallerySlidesList.getElements('a');
		intGallerySlidesListWidth = 0;
		intGallerySlideWidth = 0;
		
		elGalleryProjection.addEvent('click', function(event){
			event.stop();
			nextGallerySlide();
		});
		elGalleryProjection.getParent().addEvent('focus', function(){
			this.blur();
		});
		
		arrGallerySlidesLinks.each(function(elGallerySlidesLink, intSlidesLinkIndex){
			elGallerySlidesLink.addEvent('click', function(event){
				event.stop();
				showGallerySlide(this, intSlidesLinkIndex);
			});
			intGallerySlidesListWidth = intGallerySlidesListWidth + elGallerySlidesLink.getParent().getWidth() + elGallerySlidesLink.getParent().getStyle('margin-right').toInt();
			intGallerySlideWidth = (intGallerySlideWidth == 0) ? intGallerySlidesListWidth : intGallerySlideWidth;
		});
		if (intGallerySlidesListWidth > elGallerySlidesList.getStyle('width').toInt()) {
			elGallerySlidesList.setStyle('width', intGallerySlidesListWidth);
		}
	
		// Automatically show the next slide after a defined period.
		if (blnAutoPlay == true) var objGallerySlideshow = nextGallerySlide.periodical(1000 * intGalleryIntervalSeconds);
	}
	
	// Show this slide.
	showGallerySlide = function(thisGallerySlidesLink, intSlideNumberActive){
		if (thisGallerySlidesLink) {
			arrGallerySlidesLinks.getParent().removeClass('active');
			thisGallerySlidesLink.getParent().addClass('active');
			elGalleryProjection.setProperty('src', thisGallerySlidesLink.getProperty('href'));
			intGallerySlidesLinkOffsetX = (intSlideNumberActive == arrGallerySlidesLinks.length) ? 0 : (thisGallerySlidesLink.getParent().getWidth() + 10) * (intSlideNumberActive - 2);
			elGallerySlidesViewport.scrollTo(intGallerySlidesLinkOffsetX, 0);
		}
	}
	
	// Show next slide or first when end is reached.
	nextGallerySlide = function(){
		arrGallerySlidesLinks.getParent().each(function(elGallerySlidesLink, intSlideNumber){
			if (elGallerySlidesLink.hasClass('active') == true) {
				thisGallerySlidesLink = (intSlideNumber + 1 == arrGallerySlidesLinks.length) ? arrGallerySlidesLinks[0] : thisGallerySlidesLink = arrGallerySlidesLinks[intSlideNumber + 1];
				intSlideNumberActive = intSlideNumber + 1;
			}
		});
		showGallerySlide(thisGallerySlidesLink, intSlideNumberActive);
	}
}



/**
 * fixIE6MainNav
 * Fixes the :first-child pseudo-selector for the main and sub navigation in IE6.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function fixIE6MainNav(){
	if (!Browser.Engine.trident4 || !document.getElement('.main_nav')) return;
	
	var elMainNav = document.getElement('.main_nav');
	elMainNav.getElement('li').addClass('first-child');
	
	var arrMainNavSubNavs = elMainNav.getElements('ul');
	if (arrMainNavSubNavs.length == 0) return;
	
	arrMainNavSubNavs.each(function(elMainNavSubNav){
		elMainNavSubNav.getElement('li').addClass('first-child');
	});
}



/**
 * fixIE6PushboxTeaserList
 * Fixes the :first-child pseudo-selector for the pushbox teaserlist in IE6.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function fixIE6PushboxTeaserList(){
	if (!Browser.Engine.trident4 || !document.getElement('.pushbox')) return;
	
	var arrTeaserListItems = document.getElements('.pushbox .teaser_list li');
	if (arrTeaserListItems.length == 0) return;
	
	arrTeaserListItems[0].addClass('first-child');
}



/**
 * fixIE6NewsList
 * Fixes the :hover pseudo-selector of the newslist items in IE6.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function fixIE6NewsList(){
	if (!Browser.Engine.trident4 || !document.getElement('.ul.newslist')) return;
	
	var arrNewsListItems = document.getElements('ul.newslist li');
	if (arrNewsListItems.length == 0) return;
	
	arrNewsListItems.each(function(elNewsListItem){
		elNewsListItem.addEvents({
			'mouseenter': function(){
				elNewsListItem.addClass('hover');
			},
			'mouseleave': function(){
				elNewsListItem.removeClass('hover');
			}
		});
	});
}



/**
 * fixIE6DownloadList
 * Fixes the alignment of the downloadlist items in IE6.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function fixIE6DownloadList(){
	if (!Browser.Engine.trident4 || !document.getElement('.downloads_library_list')) return;
	
	var arrDownloadListItems = document.getElement('.downloads_library_list').getElements('li');
	var elClearingDiv = new Element('div', {'class': 'clear', 'html': '&nbsp;'}); // Results in: <div class="clear">&nbsp;</div>
	
	arrDownloadListItems.each(function(elDownloadListItem){
		elClearingDiv.clone().inject(elDownloadListItem);
		elDownloadListItem.addEvents({
			'mouseenter': function(){
				elDownloadListItem.addClass('hover');
			},
			'mouseleave': function(){
				elDownloadListItem.removeClass('hover');
			}
		});
	});
}



/**
 * fixIE6ContactForm
 * Fixes the alignment of inputgroups of the contact form in IE6.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function fixIE6ContactForm(){
	if (!Browser.Engine.trident4) return;
	var arrFormInputGroups = document.getElements('form .inputgroup');
	if (arrFormInputGroups.length == 0) return;
	
	var elBreak = new Element('br');
	
	arrFormInputGroups.each(function(elFormInputGroup){
		elBreak.clone().inject(elFormInputGroup, 'after');
	});
}



/**
 * fixIE7DownloadSearchbox
 * Fixes the alignment of inputfield of the download form in IE7.
 * 
 * @author Ralph Meeuws (ralph@meeuws.net)
 * @return void
 */
function fixIE7DownloadSearchbox(){
	if (!Browser.Engine.trident5) return;
	if (navigator.userAgent.indexOf('MSIE 8.0') != -1) return;
	
	var elDownloadSearchbox = document.getElement('.downloads_searchbox');
	var elDownloadSearchField = elDownloadSearchbox.getElement('input');
	var elDownloadSearchSubmitButton = elDownloadSearchbox.getElement('.submit');
	
	elDownloadSearchField.setStyle('margin-left', '20px');
	elDownloadSearchSubmitButton.setStyles({
		'margin-left': '-20px',
		'float': 'left'
	});
}



function loadPartnerOverview() {
	var elPartnerOverview = $(document).getElement('.partner_overview');
	if (!$defined(elPartnerOverview)) return false;
	
	var fltFadeOutTarget = 0.01;
	var fltFadeInTarget = 0.7;
	
	var arrPartners = elPartnerOverview.getElements('li');
	arrPartners.each(function(elPartner, index){
		// Define item on the right and re-align longer items per row.
		if ((index + 1) % 4) {
			// Do nothing...
		} else {
			elPartner.addClass('right');
			
			intPartnerHeight = arrPartners[index - 2].getHeight();
			if (intPartnerHeight < arrPartners[index - 1].getHeight()) intPartnerHeight = arrPartners[index - 1].getHeight();
			if (intPartnerHeight < arrPartners[index].getHeight()) intPartnerHeight = arrPartners[index].getHeight();
			
			arrPartners[index - 2].setStyle('height', intPartnerHeight);
			arrPartners[index - 1].setStyle('height', intPartnerHeight);
			arrPartners[index].setStyle('height', intPartnerHeight);
		}
		
		// Center partner logo
		var elVisual = elPartner.getElement('a.visual');
		if (elVisual.getElement('img')) elVisual.getElement('img').setStyle('margin-top', (elVisual.getStyle('height').toInt() - elVisual.getElement('img').getHeight()) / 2);
		if (elVisual.getElement('img')) elVisual.getElement('img').setStyle('margin-left', (elVisual.getStyle('width').toInt() - elVisual.getElement('img').getWidth()) / 2);
		
		// Add events to fade logo and make it clickable
		var strUrl = elVisual.get('href');
		elPartner.getElement('.overlay').addEvents({
			'click': function(){
				//window.location.href = strUrl;
				window.open(strUrl);
			},
			'mouseenter': function(){
				this.fade(fltFadeInTarget, fltFadeOutTarget);
			},
			'mouseleave': function(){
				this.fade(fltFadeOutTarget, fltFadeInTarget);
			}
		});
		
		// Add events to fade logo when hovering over the name
		if (elPartner.getElement('.partner_name')) {
			elPartner.getElement('.partner_name').addEvents({
				'mouseenter': function(){
					elPartner.getElement('.overlay').fade(fltFadeInTarget, fltFadeOutTarget);
				},
				'mouseleave': function(){
					elPartner.getElement('.overlay').fade(fltFadeOutTarget, fltFadeInTarget);
				}
			});
		}
	});
}
