/**
 * Init the shadowbox
 */ 
Shadowbox.init({
    language: 'en',
    players:  ['html'],
    skipSetup: true,
    useSizzle: false
});

/**
 * Small class that creates a loading image centered on a container
 */
var AjaxLoader = new Class({
	initialize: function(image){
		var loader = new Element('div');
		loader.setStyles({
			'position': 'absolute',
			'z-index': '10000', 
			'top': '50%',
			'left': '50%'
		});
		new Asset.image(image, {
			onload: function() {
				this.inject(loader);
				loader.setStyles({
					'margin-left': -(this.width/2).round() + 'px',
					'margin-top': -(this.height/2).round() + 'px'
				});
			}
		});
		
		this.loader = loader;
	},
	show: function(container) {
		container.grab(this.loader);
	}, 
	hide: function(){
		this.loader.dispose();
	}
});

/**
 * Class that creates buffering for html content, the index has to be an url
 */
var ContentsCache = new Class({
	Implements: [Options],
	options: {
		contents: null
	},
	initialize: function() {
		this.contents = [];
		this.urls = [];
	},
	isCached: function(url) {
		return (this.urls.contains(url));
	},
	getContent: function(url) {
		var index = this.urls.indexOf(url);
		return index != -1 ? this.contents[index] : null;
	},
	addContent: function(url, content) {
		if (!this.isCached(url)) {
			this.urls[this.urls.length] = url;
			this.contents[this.contents.length] = content;
		}
	},
	addContents: function(contents) {
		contents.each(function(content, url) {
			this.addContent(content, url);
		}.bind(this));
	},
	removeContent: function(url) {
		var index = this.urls.indexOf(url);
		if(index != -1) {
			var index = this.urls.indexOf(url); 
			this.contents.splice([index], 1);
			this.urls.splice([index], 1);
		}
	},
	removeContents: function(contents) {
		contents.each(function(content, url) {
			this.removeContent(url);
		}.bind(this));
	},
	clear: function() {
		this.contents.empty();
		this.urls.empty();
	}
	
});

/**
 * Class that makes an interface for the JWPlayer
 */
var VideoPlayer = new Class({
	Implements: [Options],
	options: {
		mode: 'foreground',
		width: 512,
		height: 288,
		image: null,
		autostart: false
	},
	initialize: function(id, holder, container, file, options){
		this.setOptions(options);
		
		this.id = id;
		this.holder = holder;
		this.container = container;
		this.file = file.replace('http://'+location.hostname, '');
		this.isReady = false;
		this.playWhenReady = null;
		this.loadWhenReady = null;
		
		switch(this.options.mode) {
		case 'background':
			this.playerOptions = {
				allowfullscreen: 'false',
				bufferlength: '1',
				controlbar: 'none',
				displayclick: 'none',
				repeat: 'single',
				stretching: 'fill',
				skin: '/swf/playerSkins/small.swf' // Need to put a skin for IE, can't see why ... :S
			};
		break;
		default:
			this.playerOptions = {
				allowfullscreen: 'true',
				bufferlength: '2',
				controlbar: 'over',
				displayclick: 'play',
				repeat: 'none',
				stretching: 'uniform',
				skin: '/swf/playerSkins/small.swf',
				streamer: '/fr/streaming/get',
				token: 'HYvp4587t'
			};
		};

		this.writePlayer();
	},
	writePlayer: function() {
		var attributes = {
		        id: this.id,
		        name: this.id
		};
		var params = {
		        allowfullscreen: this.playerOptions.allowfullscreen, 
		        allowscriptaccess:'always',
		        wmode: 'transparent',
		        bgcolor: '#000000'
		};
		var flashvars = {
		        file: this.file,
		        bufferlength: this.playerOptions.bufferlength,
		        controlbar: this.playerOptions.controlbar,
		        stretching: this.playerOptions.stretching,
		        displayclick: this.playerOptions.displayclick,
		        autostart: this.options.autostart,
		        repeat: this.playerOptions.repeat,
		        skin: this.playerOptions.skin
		};
		if(this.playerOptions.streamer != null) {
			flashvars.streamer = this.playerOptions.streamer;
    	}
    	if(this.playerOptions.token != null) {
    		flashvars.token = this.playerOptions.token;
    	}
    	if(this.options.image != null) {
    		flashvars.image = this.options.image;
    	}
    	
		swfobject.embedSWF("/swf/mediaplayer.swf", this.holder.get('id'), this.options.width,this.options.height,"9.0.115", '/swf/expressInstall.swf', flashvars, params, attributes);
	},
	play: function() {
		if(this.isReady) {
			this.player.sendEvent('PLAY', 'true');
		}
		else {
			this.playWhenReady = 'true';
		}
	},
	pause: function() {
		if(this.isReady) {
			this.player.sendEvent('PLAY', 'false');
		}
		else {
			this.playWhenReady = 'false';
		}
	},
	load: function(files) {
		if(this.isReady) {
			this.player.sendEvent('LOAD', files);
		}
		else {
			this.loadWhenReady = files;
		}
	},
	ready: function() {
		this.isReady = true;
		this.player = $(this.id);
		
		if(this.loadWhenReady != null) {
			this.load(this.loadWhenReady);
		}
		if(this.playWhenReady) {
			this.play();
		}
	},
	reset: function() {
		this.container.set('html', '');
		this.holder.inject(this.container);
		this.isReady = false;
	}
});

/**
 * Class that makes a slideshow
 */

var SlideShow = new Class({
	
	Implements: [Options],
	options: {
		itemWidth: null,
		showNavigation: 1,
		showPreviousNext: 1,
		transition: Fx.Transitions.linear,
		duration: 400,
		direction: 1,
		autoSlide: false,
		mouseWheelNav: false
	},
	initialize: function(overallContainer, windowContainer, slidingContainer, itemsSelector, options){
		this.setOptions(options); 
		this.overallContainer = overallContainer;
		this.windowContainer = windowContainer;
		this.slidingContainer = slidingContainer;
		this.elements = this.slidingContainer.getElements(itemsSelector);
		this.totalElements = this.elements.length;
		this.elementWidth = this.options.itemWidth || this.elements[0].getSize().x;
		this.currentElement = 0;
		this.previousElement = -1;
		this.direction = this.options.direction;
		this.autoSlideTotal = this.options.autoSlide + this.options.duration;
		this.autoSlideStarted = false;
		
		this.begin();
	},
	begin: function(){	
		// resizes the container div's according to the number of itemsVisible thumbnails
		this.setContainersSize();
		
		this.slidingContainer.set('tween', {
			transition: this.options.transition,
			duration: this.options.duration,
			onStart: function() {
				this.updateNavigation();
			}.bind(this),
			onComplete: function() {
				this.started = false;
			}.bind(this)
		});		
		
		/* if navigation is needed and enabled, add it */
		this.addControls();
		
		/* if autoSlide is not set, scroll on mouse wheel */
		if( this.options.mouseWheelNav && !this.options.autoSlide ){
			this.slidingContainer.addEvent('mousewheel', function(ev){
				new Event(ev).stop();
				this.slide(-ev.wheel);								
			}.bind(this));
		}
		
		if( this.options.autoSlide )
			this.startAutoSlide();		
	},
	
	setContainersSize: function(){
		this.overallContainer.setStyle('width', this.elementWidth + 50 * this.options.showPreviousNext);
		this.windowContainer.setStyle('width', this.elementWidth);
		this.slidingContainer.setStyle('width', this.totalElements * (this.elementWidth + 10));	
	},
	
	addControls: function(){
		if( this.options.showNavigation ) {
			this.navigation = new Element('div', {
				'id': 'slideShowNavigation'
			}).inject(this.overallContainer, 'top');
			
			this.navgationItems = [];
			this.elements.each(function(elem, index) {
				this.navgationItems[index] = new Element('div', {
					'id': 'slideShowNavigationItem'+(index+1),
					'class': 'slideShowNavigationItem',
					'events': {
						'click': function() { 
							this.slideTo(index);
						}.bind(this)
					}
				}).inject(this.navigation);
			}.bind(this));
			this.updateNavigation();
		}
		if( this.options.showPreviousNext ) {
			this.fwd = new Element('div', {
				'class': 'slideShowForward',
				'events':{
					'click':this.slide.pass(1, this)
				}
			});
			this.bkwd = new Element('div', {
				'class': 'slideShowBackward',
				'events':{
					'click': this.slide.pass(-1, this)
				}
			});
			this.overallContainer.adopt(this.fwd, this.bkwd);
		}
	},
	
	updateNavigation: function() {
		if(!this.options.showNavigation) return;
		
		if(this.previousElement != -1) {
			this.navgationItems[this.previousElement].removeClass('slideShowNavigationActiveItem');
		}
		this.navgationItems[this.currentElement].addClass('slideShowNavigationActiveItem');
	},
	
	slide: function( offset ){
		
		if(this.started || offset == 0) return;
		
		this.previousElement = this.currentElement;
		this.currentElement = this.previousElement + offset;

		if( this.currentElement >= this.totalElements ) this.currentElement = 0;
		if( this.currentElement < 0 ) this.currentElement = this.totalElements-1;

		this.started = true;

		this.slidingContainer.tween('margin-left', -this.direction * this.currentElement * this.elementWidth);
	},
	slideTo: function(index) {
		this.slide(index - this.currentElement);
	},
	
	startAutoSlide: function(){
		this.resumeAutoSlide();
		this.elements.addEvents({
			'mouseover':function(){
				this.stopAutoSlide();						
			}.bind(this),
			'mouseout':function(){
				this.resumeAutoSlide();
			}.bind(this)
		});
	},
	
	stopAutoSlide: function(){
		if(this.autoSlideStarted) {
			$clear(this.autoSlide);
			this.autoSlideStarted = false;
		}
	},
	
	resumeAutoSlide: function(){
		if(!this.autoSlideStarted) {
			this.autoSlide = this.slide.pass(this.direction, this).periodical(this.autoSlideTotal, this);
			this.autoSlideStarted = true;
		}
	}
});

/**
 * Class that creates a images gallery
 */

var ImageGallery = new Class({
	
	Implements: [Options],
	options: {
		'duration': 400,
		'opacity': 0.5,
		'show': 0
	},
	initialize: function(viewContainer, thumbsContainer, thumbsLinksSelector, options) {
		this.setOptions(options); 

		this.viewContainer = viewContainer;
		
		this.thumbsContainer = thumbsContainer;
		this.thumbsLinks = this.thumbsContainer.getElements(thumbsLinksSelector);
		
		this.loadedImages = [];
		this.activeThumbLink = this.options.show;
		
		this.active = false;
		
		this.begin();
	},
	
	begin: function() {
		var w = this.viewContainer.getStyle('width');
		var h = this.viewContainer.get('height');
		var t = this.viewContainer.getStyle('padding-top');
		var l = this.viewContainer.getStyle('padding-left');
		
		this.backViewContainer = new Element('div', {
			styles: {
				'position': 'absolute',
				'top': t,
				'left': l,
				'overflow': 'hidden',
				'width': w,
				'height': h,
				'z-index': '1'
			}
		});
		this.frontViewContainer = new Element('div', {
			styles: {
				'position': 'absolute',
				'top': t,
				'left': l,
				'overflow': 'hidden',
				'width': w,
				'height': h,
				'z-index': '2'
			},
			'opacity': '0'
		});
		
		this.frontViewContainer.set('tween', {
			duration: this.options.duration,
			onComplete: function() {
				// Now we need to the new image in the back container
				this.backViewContainer.set('html', '');
				this.backViewContainer.grab(this.frontViewContainer.getElement('img'));
				// Let's hide the front image
				this.frontViewContainer.set('opacity', 0);
				
				this.active = false;
			}.bind(this)
		});
		
		this.viewContainer.adopt([this.backViewContainer, this.frontViewContainer]);
		
		this.thumbsLinks.each(function(elem, index) {
			elem.set('tween', {
				duration: this.options.duration
			});
			
			this.preloadImage(index, elem);
			
			if(index == this.activeThumbLink) {
				this.backViewContainer.grab(this.loadedImages[index]);
			}
			else {
				elem.set('opacity', this.options.opacity);
			}
			elem.addEvents({
				'click': function(e) {
					e.stop();
					if ((this.activeThumbLink == index) || this.active) return;
					
					this.active = true;
					
					// Fill the back view with the new image
					this.frontViewContainer.set('html', '');
					this.frontViewContainer.grab(this.loadedImages[index]);
					
					// Fade out the front image
					this.frontViewContainer.tween('opacity', 1);
					
					this.thumbsLinks[this.activeThumbLink].tween('opacity', this.options.opacity);
					this.activeThumbLink = index;
				}.bind(this),
				'mouseenter': function(e) {
					if(index != this.activeThumbLink) {
						elem.tween('opacity', 1);
					}
				}.bind(this),
				'mouseleave': function(e) {
					if(index != this.activeThumbLink) {
						elem.tween('opacity', this.options.opacity);
					}
				}.bind(this)
			});
		}.bind(this));
	},
	
	preloadImage: function(index, thumbLink) {
		if(this.loadedImages[index] == null) {
			var imageSrc = thumbLink.getProperty('href');
			var thumbSrc = thumbLink.getElement('img').getProperty('src');
			
			if(imageSrc == thumbSrc) {
				this.loadedImages[index] = new Element('img', {
					'src': imageSrc
				});
			}
			else {
				this.loadedImages[index] = new Asset.image(imageSrc);
			}
		}
	}
});
	

/**
 * Array of object that contains all the actions at each stage for the contents
 */
var actions = {
	/**
	* Home actions
	*/
	'homeContent' : {
		showEffect: {
			property: 'margin-top',
			value: function() {
				return 0;
			} 
		},
		hideEffect: {
			property: 'margin-top',
			value: function() {
				return $('homeContent').getSize().y;
			} 
		},
		onDomready: function() {
			var me = this;
			
			// Fix the transparency for IE6
			if(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) {
				var pngFix = new PngFix({imgContainers: $$('#homeLastProjectsTitle'), bgElements: null});
			}

			// Setup of the news navigation
			var newsDates = $('homeInfoNewsNav').getElements('.homeInfoNewDate');
			var news = $('homeInfoNewsDetails').getElements('.homeInfoNew');
			var currentDate = -1;
			var started = false;
			newsDates.each(function(elem, index){
				news[index].setStyles({
					'position': 'absolute',
					'top': 0,
					'left': 0
				});
				news[index].set('tween', {
					'onComplete': function() {started = false;}
				});
				if(!elem.hasClass('homeInfoNewActiveDate')) {
					news[index].fade('hide');
				}
				else {
					currentDate = index;
				}
				elem.addEvent('click', function(e) {
					e.stop();
					
					if(started || (currentDate == index)) return;
					
					started = true;
					newsDates[currentDate].removeClass('homeInfoNewActiveDate');
					this.addClass('homeInfoNewActiveDate');
					
					news[currentDate].fade('hide');
					news[index].fade('in');
					
					currentDate = index;
					
				});
			});
			// Setup for the Shadowbox
			$$('div.project').each(function(item, index) {
				var movie = item.getElements('a.projectMovie')[0];
				var description = item.getElements('div.projectFullDescription')[0];
				
				item.addEvent('click', function(e) {
					e.stop();
					Shadowbox.open({
						player: 'html',
						width: 640,
						height: (360 + description.getSize().y),
				        content: ('<div id="shadowbox_player"><div id="shadowbox_playerAlt"></div></div><div id="shadowbox_legend">'+description.get('html')+'</div>'),
				        counterType: 'skip',
				        options: {
							onOpen: function() {
								me.slider.stopAutoSlide();
								me.videoBackground.pause();
							},
				        	onFinish: function() {
								$('shadowbox_playerAlt').set('html','<p class="noflash">This content requires the Adobe Flash Player 10 : <a href="http://www.adobe.com/go/getflashplayer/">get Flash</a></p>');
				                new VideoPlayer('shadowPlayer', $('shadowbox_playerAlt'), $('shadowbox_player'), movie.getProperty('href'), {
									mode: 'foreground',
									width: '640',
									height: '360',
									autostart: true
								});
				        	},
				        	onClose: function() {
								me.slider.startAutoSlide();
								me.videoBackground.play();
							}
				        }
					});
				});
			});
		},
		onLoad: function() {
			// Setup of the slider
			this.slider = new SlideShow($('slideShowContainer'), $('slideShowInner'), $('slideShowItems'), '.slideShowElement', {
				transition: Fx.Transitions.Expo.easeInOut,
				duration: 800,
				autoSlide: 6000,
				itemWidth: 620,
				showNavigation: true,
				showPreviousNext: false
			});
		},
		onReload: function() {
		},
		beforeShow: function() {
			$('homeLastProjectsTitle').fade('hide');
			$('homeContent').setStyle('margin-top', $('homeContent').getSize().y);
		},
		afterShow: function() {
			this.slider.resumeAutoSlide();
			
			// Setup of the background video
			this.videoBackground = new VideoPlayer('bgPlayer', $('bgPlayerAlt'), $('homeLeftBgVideo'), '/videos/background.flv', {
				mode: 'background',
				width: '100%',
				height: '100%'
			});
			
			this.videoBackground.play();
			
			$('homeLastProjectsTitle').fade('in');
		},
		beforeHide: function() {
			$('homeLastProjectsTitle').fade('out');
			$('homeContent').setStyle('z-index', '5');
			
			this.slider.stopAutoSlide();
			this.videoBackground.pause();
		},
		afterHide: function() {
			this.videoBackground.reset();
		},
		onUnload: function() {
			this.slider.stopAutoSlide();
		}
	},
	
	/**
	 * Agency actions
	 */
	'agencyContent' : {
		showEffect: null,
		hideEffect: {
			property: 'margin-left',
			value: function() {
				return -($('agencyContent').getSize().x);
			} 
		},
		onDomready: function() {
			this.gallery = new ImageGallery($('agencyImagesGalleryView'), $('agencyImagesGalleryThumbs'), '.imagesGalleryThumb');
			
			$imagesToReflect = $$("img").filter(function(img) {
				return img.hasClass("reflect");
			}).reflect({height: 0.5});
		},
		onLoad: function() {
		},
		onReload: function() {
		},
		beforeShow: function() {
		},
		afterShow: function() {
		},
		beforeHide: function() {
		},
		afterHide: function() {
			//this.fxThumbs = null;
		},
		onUnload: function() {
		}
	},
	/**
	 * Services actions
	 */
	'servicesContent' : {
		showEffect: null,
		hideEffect: {
			property: 'margin-left',
			value: function() {
				return -($('servicesContent').getSize().x);
			}
		},
		onDomready: function() {
			this.gallery = new ImageGallery($('servicesImagesGalleryView'), $('servicesImagesGalleryThumbs'), '.imagesGalleryThumb');
			$$("img").filter(function(img) {
				return img.hasClass("reflect");
			}).reflect({height: 0.5});
			
			
			$$('li.projectSample').each(function(item, index) {
				var movie = item.getElements('a.projectMovie')[0];
				var description = item.getElements('div.projectFullDescription')[0];
				
				item.addEvent('click', function(e) {
					e.stop();
					Shadowbox.open({
						player: 'html',
						width: 640,
						height: (360 + description.getSize().y),
				        content: ('<div id="shadowbox_player"><div id="shadowbox_playerAlt"></div></div><div id="shadowbox_legend">'+description.get('html')+'</div>'),
				        counterType: 'skip',
				        options: {
				        	onFinish: function() {
				                new VideoPlayer('shadowPlayer', $('shadowbox_playerAlt'), $('shadowbox_player'), movie.getProperty('href'), {
									mode: 'foreground',
									width: '640',
									height: '360',
									autostart: true
								});
				        	}
				        }
					});
				});
			});
		},
		onLoad: function() {
		},
		onReload: function() {
		},
		beforeShow: function() {
		},
		afterShow: function() {
		},
		beforeHide: function() {
		},
		afterHide: function() {
		},
		onUnload: function() {
		}
	},
	/**
	 * Portfolio actions
	 */
	'portfolioContent' : {
		showEffect: null,
		hideEffect: {
			property: 'margin-left',
			value: function() {
				return -($('portfolioContent').getSize().x);
			} 
		},
		onDomready: function() {
			var me = this;
			
			this.loader = new AjaxLoader('/images/loader.gif');
			
			this.porfolioLinks = $('referencesYearsNav').getElements('a');
			this.porfolioLinks.include($$('div.pagination')[0].getElements('a'));
			
			this.porfolioLinks.addEvent('click', function(e) {
				e.stop();
				
				var url = this.getProperty('href');

				var req = new Request.HTML({
					onRequest: function() {
						me.loader.show($('portfolioContent'));
					}, 
					onSuccess: function(html, elements) {
						me.loader.hide();
						me.afterHide();
						
						$('portfolioContent').dispose();
						$('slidingContent').adopt(html);
						
						// Fix the transparency for IE6
						if(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) {
							var pngFix = new PngFix({imgContainers: $('slidingContent').getElements('.alphaimg'), bgElements: $('slidingContent').getElements('.alphabg')}); 
						}
						
						me.onDomready();
						me.onLoad();
						me.beforeShow();
						me.afterShow();
					},
					onFailure: function() {
						me.loader.hide();
					}
				});
				
					req.get(url);
			});
		},
		onLoad: function() {
			var me = this;
			
			this.activeReference = 0;
			$$('a.referenceFiles').each(function(element, index) {
				if(element.hasClass('activeReference')) {
					me.activeReference = index;
				}
				element.addEvent('click', function(e) {
					e.stop();
					me.player.load(JSON.decode(this.rel));
				});
			});
			
			var refAccordion =  new Accordion($('references'), 'a.referenceFiles', 'div.referenceDetails', {
				initialDisplayFx: false,
				show: this.activeReference,
				opacity: false,
				onActive: function(toggler, element) {
					toggler.setStyle('color', '#F33192');
				},
				onBackground: function(toggler, element){
					toggler.setStyle('color', '#000000');
				}
			});
		},
		onReload: function() {
			//this.refAccordion.display(0);
		},
		beforeShow: function() {
		},
		afterShow: function() {
			var files = JSON.decode($$('a.referenceFiles')[this.activeReference].getProperty('rel'));
			$('playerAlt').set('html', '<p class="noflash">This content requires the Adobe Flash Player 10 (<a href="http://www.adobe.com/go/getflashplayer/">get Flash</a>) and JavaScript enabled.</p>');
			this.player = new VideoPlayer('player', $('playerAlt'), $('portfolioVideo'), files.file, {
				image: files.image
			});
		},
		beforeHide: function() {
		},
		afterHide: function() {
			this.player.reset();
		},
		onUnload: function() {
		}
	},
	/**
	 * contact actions
	 */
	'contactContent' : {
		showEffect: null,
		hideEffect: {
			property: 'margin-left',
			value: function() {
				return -($('contactContent').getSize().x);
			} 
		},
		onDomready: function() {
		},
		onLoad: function() {
		},
		onReload: function() {
			if (GBrowserIsCompatible()) {
				this.map.setCenter(new GLatLng(50.8334696, 4.376422), 17);
				this.map.setMapType(G_HYBRID_MAP);
			}
		},
		beforeShow: function() {
		},
		afterShow: function() {
			if ((this.map == null) && GBrowserIsCompatible()) {
		        this.map = new GMap2(document.getElementById("contactMap"));
		        
		        var uiOptions = new GMapUIOptions(new GSize(200, 200));
		        this.map.setUI(uiOptions);
		        this.map.setCenter(new GLatLng(50.8334696, 4.376422), 17);
		        this.map.setMapType(G_HYBRID_MAP);

		        var icon = new GIcon();
		        icon.image = "/images/gMarker.png";
		        icon.iconAnchor = new GPoint(13, 29);
		        icon.infoWindowAnchor = new GPoint(31, 6);
		        icon.iconSize = new GSize(61, 29);
		        icon.shadow = "/images/gMarkerShadow.png";
		        icon.shadowSize = new GSize(61, 29);
		        
				var point = new GLatLng(50.8335215, 4.37659);
				this.map.addOverlay(new GMarker(point, {icon: icon}));
			}
		},
		beforeHide: function() {
		},
		afterHide: function() {
		},
		onUnload: function() {
			GUnload();
		}
	},
	'otherContent' : {
		showEffect: null,
		hideEffect: {
			property: 'margin-left',
			value: function() {
				return -($('otherContent').getSize().x);
			}
		},
		onDomready: function() {
		},
		onLoad: function() {
		},
		onReload: function() {
		},
		beforeShow: function() {
		},
		afterShow: function() {
		},
		beforeHide: function() {
		},
		afterHide: function() {
		},
		onUnload: function() {
		}
	}
};

/**
 * Contents manager, will manage all the content transitions 
 */

var ContentsManager = new Class({
	Implements: [Options],
	options: {
		transition: Fx.Transitions.Expo.easeInOut,
		duration: 'long'
	},
	initialize: function(navLinks, activeClass, container, contentSelector, contentsActions, loaderImage, options) {
		var me = this;
		
		this.setOptions(options);
		
		this.cache = new ContentsCache();
		this.eventStarted = false;
		
		this.navLinks = navLinks;
		this.activeClass = activeClass;
		this.container = container;
		this.contentSelector = contentSelector;
		this.contentsActions = contentsActions;
		this.loader = new AjaxLoader(loaderImage);
		
		this.addNavLinks(navLinks);
	},
	addNavLinks: function(links) {
		links.each(function(link) {
			this.addNavLink(link);
		}.bind(this));
	},
	addNavLink: function(link) {
		link.addEvent('click', function(e) {
			e.stop();
			this.loadContent(link);
		}.bind(this));
		if(link.getParent().hasClass(this.activeClass)) {
			this.addCache(link.href, $$(this.contentSelector)[0]);
		}
	},
	addInternalLinks: function(links) {
		links.each(function(link) {
			this.addInternalLink(link);
		}.bind(this));
	},
	addInternalLink: function(link) {
		var bindLink = null;
		this.navLinks.each(function(navLink) {
			if(navLink.href == link.href) {
				bindLink = navLink;
				return;
			}
		});
		if(bindLink != null) {
			link.addEvent('click', function(e) {
				e.stop();
				bindLink.fireEvent('click', e);
			});
		}
	},
	isCached: function(url) {
		return this.cache.isCached(url);
	},
	addCache: function(url, content) {
		this.cache.addContent(url, content);
	},
	removeCache: function(url) {
		this.cache.removeContent(url);
	},
	currentContent: function() {
		return $$(this.contentSelector)[0];
	},
	
	newContent: function() {
		return $$(this.contentSelector)[1];
	},
	
	loaded: function(url, currentContent, currentContentActions, newContent, newContentActions) {
		this.loader.hide();
		
		newContentActions.onLoad();
		
		this.loadEffects(currentContent, currentContentActions, newContent, newContentActions);
		
		this.addCache(url, newContent);
	},
	
	loadEffects: function(currentContent, currentContentActions, newContent, newContentActions) {
		var me = this;
		var effectOptions = {
			wait: true,
			duration: this.options.duration,
			transition: this.options.transition,
			onComplete: function() {
				currentContent.set('style', '');
				currentContentActions.afterHide();
			
				currentContent.dispose();
				
				newContentActions.afterShow();
				
				me.eventStarted = false;
			}
		};
		
		if(newContentActions.showEffect != null) {
			var effect = newContentActions.showEffect;
			newContent.set('tween', effectOptions);
			newContent.tween(effect.property, effect.value());
		}
		else if(currentContentActions.hideEffect != null) {
			var effect = currentContentActions.hideEffect;
			
			currentContent.set('tween', effectOptions);
			currentContent.tween(effect.property, effect.value());
		}
	},
	
	loadContent: function(link) {
		var activeLinkContainer = $$('.'+this.activeClass)[0] || null; 
		// An event is already started or it is already the active content, we don't do anything
		if(this.eventStarted || ((activeLinkContainer != null) && (link == activeLinkContainer.getElement('a')))) return;
		
		this.eventStarted = true;
		
		var url = link.href;
		if(activeLinkContainer != null) {
			activeLinkContainer.removeClass(this.activeClass);
		}
		if(!link.hasClass('internalLink')) {
			link.getParent().addClass(this.activeClass);
		}
		
		var currentContent = this.currentContent();
		var currentContentActions = this.contentsActions[currentContent.getProperty('id')];
		var newContent = null;
		var newContentActions = null;
		
		// Check if we don't already have the content in the cache
		if(this.isCached(url)) {
			currentContentActions.beforeHide();
			
			this.container.adopt(this.cache.getContent(url));
			
			newContent = this.newContent();
			newContentActions = actions[newContent.getProperty('id')];
			
			currentContentActions.beforeHide();
			
			newContentActions.onReload();
			newContentActions.beforeShow();
			
			this.loadEffects(currentContent, currentContentActions, newContent, newContentActions);
		}
		else {
			// Content is not in the cache, we load it in ajax
			var me = this;
			var req = new Request.HTML({
				onRequest: function() {
					// Prepare current content to be hidden
					currentContentActions.beforeHide();
					// When loading, we show the loader
					me.loader.show(currentContent);
				},
				onSuccess: function(html, elements, text) {
					
					me.container.adopt(html);
					
					newContent = me.newContent();
					newContentActions = actions[newContent.getProperty('id')];
					
					// Fix the transparency for IE6
					if(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) {
						var pngFix = new PngFix({imgContainers: newContent.getElements('.alphaimg'), bgElements: newContent.getElements('.alphabg')});
					}
					
					me.addInternalLinks(newContent.getElements('.internalLink'));
					
					// Before show action for new content
					newContentActions.beforeShow();
					
					// Need to get and count the images before Domready action happens since it can add images...
					var images = newContent.getElements('img');
					var loadedImages = 0;
					var totalImages = images.length;
					
					// Domready action for new content
					newContentActions.onDomready();
					
					if(totalImages == 0) {
						me.loaded(url, currentContent, currentContentActions, newContent, newContentActions);
					}
					else {
						// Wait 4 sec for the images to be loaded
						var loadTimer = me.loaded.delay(4000, me, [url, currentContent, currentContentActions, newContent, newContentActions]);
						
						images.addEvents({
							'load': function() {
								if(me.eventStarted) {
									loadedImages++;
									if(loadedImages == totalImages) {
										$clear(loadTimer);
										me.loaded(url, currentContent, currentContentActions, newContent, newContentActions);
									}
								}
							},
							'error': function() {
								if(me.eventStarted) {
									loadedImages++;
									if(loadedImages == totalImages) {
										$clear(loadTimer);
										me.loaded(url, currentContent, currentContentActions, newContent, newContentActions);
									}
								}
							}
						});
					}
				},
				onFailure: function() {
					me.eventStarted = false;
					
					me.loader.hide();
				}
			});
			
			req.get(url);
		}
	}
});

/**
 * Needed to know if the player is loaded ...
 */
function playerReady(readyPlayer) {
	switch(readyPlayer.id) { 
	case 'bgPlayer':
		actions['homeContent'].videoBackground.ready();
	break;
	case 'player':
		actions['portfolioContent'].player.ready();
	}
}

/**
 * Global management of the pages
 */
window.addEvents({
	'domready': function() {
		var contentsManager = new ContentsManager($$('#navigation a'), 'active', $('slidingContent'), '.realContent', actions, '/images/loader.gif');
		if(actions[$$('.realContent')[0].getProperty('id')] != null) {
			actions[$$('.realContent')[0].getProperty('id')].onDomready();
		}
		
		contentsManager.addInternalLinks($$('.realContent')[0].getElements('.internalLink'));
		
		// Fix the transparency for IE6
		if(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) {
			var pngFix = new PngFix({imgContainers: $$('.alphaimg'), bgElements: $$('.alphabg')}); 
		}
	},
	'load': function() {
		if(actions[$$('.realContent')[0].getProperty('id')] != null) {
			actions[$$('.realContent')[0].getProperty('id')].onLoad();
			actions[$$('.realContent')[0].getProperty('id')].afterShow();
		}
	},
	'unload': function() {
		GUnload();
		if(actions[$$('.realContent')[0].getProperty('id')] != null) {
			actions[$$('.realContent')[0].getProperty('id')].onUnload();
		}
	}
});
