var GalleryManager = {
	
	galleries: [],
	layer: null,
	
	init: function() {
		this.layer = $('transparent-layer');
		this.addLayerBehaviour();
		this.addResizeScrollBehaviour();
		this.setGalleryView();
		
		$$('div.photo-gallery').each( function( gallery ) {
			this.galleries[this.galleries.length] = new Gallery( gallery )
		}.bind(this) );
	},
	
	getGallery: function( number ) {
		return this.galleries[ number ];
	},
	
	setLayerHeight: function() {
		this.layer.setStyle('height', window.getScrollHeight() );
	},
	
	addLayerBehaviour: function() {
		this.layer.addEvent('mousedown', function() {
			this.galleries.each( function( gallery ) {
				gallery.close();
			})
		}.bind(this));
	},
	
	showLayer: function() {		
		
		if ( Browser.Engine.trident == true ) {
			this.layer.setStyle('width', window.getScrollSize().x.toInt() + 'px');			
		}
		
		this.layer.setStyle('display', 'block');
		this.layer.fade(0,.7);
	},
	
	hideLayer: function() {
		this.layer.fade(.7,0);
	},
	
	addResizeScrollBehaviour: function() {
		window.addEvent("scroll", this.setGalleryView.bind(this));
		window.addEvent("resize", this.setGalleryView.bind(this));
	},
	
	setGalleryView: function() {		
		this.setLayerHeight();
	}
	
}

var Gallery = new Class({
	
	_element:null,
	layer:null,
	gallery: null,
	paginator:null,
	descriptionBar: null,
	currentPosition: 0,
	itemWrapper: null,
	itemScroller: null,
	thumbScroller: null,
	itemsContainer: null,
	items: null,	
	thumbs: null,
	thumbSize: 125 + 2,
	hasThumbs: false,
	loadedVideos: [],
	
	initialize: function( _gallery ) {
		this._element = $(_gallery);
		this.setGalleryView();
		
		this.gallery = this._element.getElement('.photo-wrapper');
		//this.itemsContainer = this._element.getElements('.item');
		//this.items = this.itemsContainer.getFirst();
		this.items 	 = this._element.getElements('.item');
		this.thumbs = this._element.getElements('.thumb a');
		
		this.hasThumbs = this.thumbs.length > 0;
			
					
		if( this.hasThumbs )
			this._element.getElement('.thumb-scroller').setStyle('width', (this.thumbs.length) * this.thumbSize);
			
		this._element.getElement('.item-wrapper').setStyle('width', (this.items.length) * 640);
		
		this.itemScroller = new Fx.Scroll( this._element.getElement('div.photo-wrapper') );
		
		if( this.hasThumbs )
			this.thumbScroller = new Fx.Scroll( this._element.getElement('div.thumb-wrapper') );
		
		this.addCloseButton();
		this.addPaginator();
		this.addDescriptionBar();
		
		if( this.hasThumbs ) {
			this.addThumbEvents();
			this.addNavigationButtons();
		}
		
		if( this.items.length == 1 ) {
			this.toCompact();
		}
	},
	
	setGalleryView: function() {			
		//this._element.setStyle('top', window.getScrollTop() + 50 );
	},
			
	addCloseButton: function() {
		var closeBtn = new Element('div', {
			'class': 'close-btn',
			'events': {
				'click': function(e) {
					e = new Event( e ).stop();
					this.close();
				}.bind(this)
			}
		});
		closeBtn.inject( this.gallery, 'before' );
		//closeBtn.inject( this.gallery, 'after' );
	},
	
	addPaginator: function() {
		this.paginator = new Element('div', {
			'class': 'paginator',
			'html': "1 van " + this.items.length
		});
		this.paginator.inject( this.gallery, 'before' );
		//this.paginator.inject( this.gallery, 'after' );
	},
	
	addDescriptionBar: function() {
		new Element('div', {
			'class': 'description-bar'
		}).inject( this.gallery, 'before' );
		
		new Element('div', {
			'class': 'gallery-title',
			'html': this._element.getElement('.h3-wrapper h3 span').innerHTML
		}).inject( this.gallery, 'before' );
		
		new Element('div', {
			'class': 'photo-description'
		}).inject( this.gallery, 'before' );
	},
	
	updatePhotoDescription: function() {
		var currentItem  = this.items[this.currentPosition];		
		
		var element = false;		
		if ( currentItem.getElement('object') != null ) {
			element = currentItem.getElement('object');			
		} else if ( currentItem.getElement('div') != null ) {
			element =  currentItem.getElement('div');
		} else {
			element = currentItem.getElement('img');	
		}				
				
		this._element.getElement('.photo-description').innerHTML = element.getAttribute('title');
	},
	
	updatePaginator: function() {
		this.paginator.innerHTML = (this.currentPosition+1) + " van " + this.items.length;
	},
	
	open: function( activeImage ) {
		var pos = activeImage || 0;
		GalleryManager.showLayer();
				
		this._element.setStyle('top', window.getScrollTop() + 25);
		this._element.setStyle('display','block');		
		this.currentPosition = pos;
		this.itemScroller.set( this.currentPosition * 640,0 );
		this.updateActiveItem();
		if( this.hasThumbs )
			this.thumbScroller.toElement( this.thumbs[pos] );
	},
	
	toCompact: function() {
		this.paginator.setStyle('display','none');
		if( this.hasThumbs )
			this._element.getElement('.navigation-bar').setStyle('display', 'none');

		this._element.getElement('.gallery-wrapper').tween('height', 480 );
		this._element.getElement('.gallery-wrapper').addClass('compact');
	},
	
	close: function() {
		var player = $('flvPlayer-' + this.currentPosition);
		if ( player ) {
			player.sendEvent("PLAY", "false");			
		}
		
		GalleryManager.hideLayer();				
		this._element.setStyle('display','none');
		this.thumbs.removeClass('active');
	},
	
	showNextHover: function( state ) {
		var scrollSize = this.thumbScroller.element.getSize().x;
		var scrolledWidth = this.thumbScroller.element.getScroll().x;
		var totalWidth = this.thumbScroller.element.getScrollSize().x;

		var stateSize = state == true ? this.thumbSize : 0;
		
		return scrollSize + scrolledWidth < (totalWidth-stateSize);
	},
	
	addNavigationButtons: function() {
		
		var currentGallery = this;
		
		var nextBtn = new Element('a', {
			'id': 'next-btn',
			'class': 'nav-btn',
			'events': {
				'mousedown': function(e) {
					e = new Event( e ).stop();
					currentGallery.toNextThumb();
			
					if( !currentGallery.showNextHover(true) ) {
						this.removeClass('hover');
						this.addClass('inactive');
					}
					else {
						this.removeClass('inactive');
					}
				},
				'mouseover': function(e) {
					if( currentGallery.showNextHover(false) ) {
						this.removeClass('inactive');
						this.addClass('hover');
					}
					else {
						this.addClass('inactive');
					}
				},
				'mouseout': function(e) {
					this.removeClass('hover');
				}
			}
		});
		
		var previousBtn = new Element('a', {
			'id': 'previous-btn',
			'class': 'nav-btn',
			'events': {
				'mousedown': function(e) {
					e = new Event( e ).stop();
					currentGallery.toPreviousThumb();
					if( currentGallery.thumbScroller.element.getScroll().x - this.thumbSize == 0 ) {
						this.removeClass('hover');
						this.addClass('inactive');
					}
					else {
						this.removeClass('inactive');
					}
				},
				'mouseover': function(e) {
					if( currentGallery.thumbScroller.element.getScroll().x > 0 ) {
						this.removeClass('inactive');
						this.addClass('hover');
					}
					else {
						this.addClass('inactive');
					}
				},
				'mouseout': function(e) {
					this.removeClass('hover');
				}
			}
		});
		
		var previousPosition = this._element.getElement('.thumb-wrapper .thumb');
		var nextPosition = this._element.getElement('.thumb-wrapper .clear');
		var thumbBar = this._element.getElement('.thumb-wrapper');
		
		nextBtn.inject( thumbBar, 'after' );
		previousBtn.inject( thumbBar, 'before' );
	},
	
	addThumbEvents: function() {
		var i = 0;
		var currentGallery = this;
		this._element.getElements('.thumb a').each( function(node) {			
			node.setAttribute('pos', i );
			node.removeAttribute('href');
			node.addEvent('mousedown', function(e) {
				e = new Event( e ).stop();
				currentGallery.deactivateThumb();
				
				if( currentGallery.loadedVideos.contains( currentGallery.currentPosition ) == true ) {
					currentGallery.deactivateVideo( currentGallery.currentPosition );
				}
				
				currentGallery.currentPosition = parseInt(this.getAttribute('pos'));
				currentGallery.updateActiveItem();
			});
			i++;
		});
	},
	
	toNextThumb: function() {
		this.updateThumbSlider(true);
	},
	
	toPreviousThumb: function() {
		this.updateThumbSlider(false);
	},
	
	updateActiveItem: function() {
		if( this.hasThumbs )
			this.activateThumb();
				
		var file = this.items[ this.currentPosition ].getElement('span').innerHTML;			
		if ( file.contains('traileruniverse') == true ) {
			this.initializeVideo( file, this.currentPosition );	
		} 
				
		this.itemScroller.start( this.currentPosition*640, 0);	
		
		
		this.updatePaginator();
		this.updatePhotoDescription();
	},
	
	activateThumb: function() {
		this.thumbs[this.currentPosition].addClass('active');
	},
	
	deactivateThumb: function() {
		this.thumbs[this.currentPosition].removeClass('active');
	},
	
	updateThumbSlider: function(direction) {
		var pos = this.thumbScroller.element.getScroll().x;
		if( direction == false ) {
			this.thumbScroller.start(pos-this.thumbSize,0);
		}
		else {
			this.thumbScroller.start(pos+this.thumbSize,0);
		}
	},
	
	initializeVideo: function( file, position ) {
			
		if ( this.loadedVideos.contains( position ) == false ) {
		
			var currentItem = this;
				
			var request = new Request.JSON({
				method: 'get',
				url: '/shop/loadTrailer.php',
				data: { 'trailer': file },
				onRequest: function() {
					currentItem.loadingVideo( position );				
				},
				onComplete: function(jsonObj) {
					currentItem.embedVideo( position, jsonObj );
				}	
					
			}).send();
		
		} else {			
			this.showVideo();			
		}
						
	},
	
	showVideo: function() {
		
		//console.log('flvPlayer-' + this.currentPosition.toInt());
		var player = $('flvPlayer-' + this.currentPosition.toInt());			
	
		if ( player ) { 
			
			if( player.sendEvent("PLAY", true) ) {
				
			}
		}
		
		
	},
	
	loadingVideo: function( containerID ) {
		
		var container = this.items[ containerID ].getElement('div#alternativeContent-' + containerID);	
		container.innerHTML = '<div class="loading-container"><div class="loading"></div><span class="loading-message">De video wordt geladen</span></div>';	

	},
	
	embedVideo: function( containerID, jsonObj ) {
		
		this.loadedVideos.include( containerID );
		
		var flashvars = {};
		flashvars.file = jsonObj.file;
		flashvars.streamer = jsonObj.streamer;
		flashvars.autostart = true;
		var params = {};
		params.wmode = "transparent";
		params.allowscriptaccess = "always";
		var attributes = {};
		attributes.id = "flvPlayer-" + containerID;
		attributes.title = 'Trailer';
		swfobject.embedSWF("/_lib/flash/flvplayer-update.swf", "alternativeContent-" + containerID, "640", "480", "9.0.0", false, flashvars, params, attributes);		
		
	},
	
	deactivateVideo: function( position ) {
		
		var player = $('flvPlayer-' + position);		
		if ( player ) {
			player.sendEvent("PLAY", "false");			
		}
						
	},
	
	isFirefox2: function () {
		
		if ( Browser.Engine.gecko == true && Browser.Engine.version == 18 ) {
			return true;	
		}
		
		return false;
	
	}
	
	
});


/**** Nog verplaatsen naar site.js ****/

window.addEvent("domready", GalleryManager.init.bind(GalleryManager));
window.addEvent("domready", function() {
	
	$$('.open-gallery').addEvent('click', function(e) {
												   
		e = new Event(e).stop();	
		
		var currentID = 0;
		var clickID = this.getAttribute('id');
		if (clickID != null) {
			var currentID = clickID.replace('gallery-', '').toInt() - 1;		
		} 
		GalleryManager.getGallery(0).open(currentID);
		
	});
	
	if(window.location.hash == "#startTrailer"){
		GalleryManager.getGallery(0).open(0);
	}
	
});
/**/