(function($) {
	$.fn.Albumifier = function(options) {
		options = $.extend( {
			
			defaults: {
				log: false
			},
			
			className: 'AlbumItem',
			albumIndentifier: 'AlbumID',
			albumLayerIndentifier: 'AlbumLayer',
			albumDarklayerIndentifier: 'Darklayer',
			albumPadding: 10,
			
			core : {
				Items: null,
				Albums: new Array(),
				Busy: false
			},
			
			activeContentID: null,
			activeAlbumID: null,
			activeAlbumType: null
			
		}, options );
		
		init();
		
		function init() {
			
			if (typeof(window["console"]) == "undefined") {
				options.defaults.log = false;
			}
			
			options.core.Items = $(document).find('.' + options.className);
			if ( options.core.Items.length > 0 ) {
				createAlbumLayers();
				Albumify();
			}
		};
		
		function Albumify() {
			$(options.core.Items).each(function(){
				var ID = this.rel.substr( options.albumIndentifier.length );
				$(this).click( function() {
					if ( ID ) {
						open( ID );
						return false;
					} else {
						if ( options.defaults.log )
							console.error('No AlbumID found!');
					}
				});
			});
		};
		
		function open(albumID) {
			if ( options.defaults.log )
				console.info( 'Open album with ID ' + albumID );
			
			loadAlbum(albumID);
			showAlbum(albumID);
		};
		
		function getAlbumType(albumID) {			
			if ( options.activeAlbumType == null ) {
				var Type = null;
				$.ajax({
					type: "POST",
					data: "ID=" + albumID,
					async: false,
					url: AbsPath + "includes/SpecialPages/Album/LoadContentType.php",
					success: function(result){
						Type = parseInt(result);
						options.activeAlbumType = Type;
					}
				});
			}
			return options.activeAlbumType;
		};
		
		function loadAlbum(albumID) {
			if ( ( options.activeAlbumType == null ) && ( albumExists( albumID ) == false ) ) {
				$.ajax({
					type: "POST",
					data: "ID=" + albumID,
					dataType : 'json',
					async: false,
					cache: false,
					url: AbsPath + "includes/SpecialPages/Album/LoadContent.php",
					success: function(result){
						options.core.Albums = result;
					},
					error: function(xhr, status, errorThrown){
						alert('Er is een fout opgetreden tijdens het doorgeven van deze actie!');
					}
				});
			}
			return options.activeAlbumType;
		};
		
		function openFirstItem(albumID) {
			
			var Type = getAlbumType(albumID);			
			var _ID = -1;
			
			$.each(options.core.Albums[options.activeAlbumID], function( i, e ){
				//Eerste item uit de array ophalen
				_ID = i;
				return false;
			});
			
			if ( _ID ) {
				switch(Type) {
					case 1 : //Picture				
						loadPicture( _ID );
					break;
					case 2 : // Youtube
						loadYoutube( _ID );
					break;
				}
			} else {
				alert( 'Album kon niet worden geladen.' );
			}
		};
		
		function resizeAlbumLayer() {
			var Height = Math.max( $(document).height(), $(window).height() );
			
			//console.log( $(document).height() );
			
			var Width = $(window).width(); //Math.max( $(document).width(), $(window).width() );
			$('#AlbumLayer').css('height', Height );
			$('#AlbumLayer').css('width', Width );
		};
		
		
		function resizeDarklayer() {
			var Height = Math.max( $(document).height(), $(window).height() );
			var Width = $(window).width(); //Math.max( $(document).width(), $(window).width() );
			$('#Darklayer').css('height', Height );
			$('#Darklayer').css('width', Width );
		};
		
		function createAlbumLayers() {
			createAlbumLayer();
			createDarklayer();
			createAlbumHolder();
			createEnlargementHolder();
			createTitleHolder();
			createButtonHolder();
			createCloseButton();
		};
		
		function createAlbumHolder() {
			$('#AlbumLayer').append('<div class="AlbumHolder" id="AlbumHolder"></div>');
		};
		
		function setAlbumTop() {
			var Top = $(window).scrollTop() + 50;
			var Height = Math.max( $(document).height(), $(window).height() );
			if ( Top + 660 >= Height ) {
				Top = Height - 700;
			}
			$('#AlbumHolder').css('top', Top + 'px' );
		};
		
		function createEnlargementHolder(){
			$('#AlbumHolder').append(
					'<div class="EnlargementHolder Loading" id="EnlargementHolder"></div>'
			);
		};
		
		function createDarklayer() {
			$('#AlbumLayer').append('<div class="Darklayer" id="Darklayer"></div>');
			$('#Darklayer').css('opacity', 0.8);
			$('#Darklayer').click(function(){
				close();
			});
			resizeDarklayer();
		};
		
		function createAlbumLayer() {
			$('body').append('<div class="AlbumLayer Closed" id="AlbumLayer"></div>');
			resizeAlbumLayer();
		};
		
		function openDarklayer() {			
			$('#Darklayer').removeClass('Closed');
			$('#Darklayer').addClass('Open');			
			$('#Darklayer').animate({
				opacity: 0.8
			}, 750, function() {
			});
		};
		
		function close() {
			hideEnlargements();
			closeDarklayer();
			closeAlbumHolder();
			options.activeAlbumID = null;
			options.activeContentID = null;
			options.activeAlbumType = null;
		};
		
		function closeAlbumHolder() {
			$('#AlbumHolder').removeClass('Open');
			$('#AlbumHolder').addClass('Closed');
			closeAlbumLayer();
		};
		
		function closeAlbumLayer(){
			$('#AlbumLayer').removeClass('Open');
			$('#AlbumLayer').addClass('Closed');
			reset();
		};
		
		function closeDarklayer(){
			$('#Darklayer').animate({
				opacity: 0
			}, 500, function() {
				$('#Darklayer').removeClass('Open');
				$('#Darklayer').addClass('Closed');
			});
		};
		
		function showAlbum(albumID) {
			
			resizeDarklayer();
			resizeAlbumLayer();
			
			options.activeAlbumID = albumID;
			openFirstItem(albumID);
			openAlbumLayer();
			openDarklayer();
			openAlbumHolder(albumID);
			
		};
		
		function openAlbumLayer(ID) {
			$('#AlbumLayer').removeClass('Closed');
			$('#AlbumLayer').addClass('Open');
		};
		
		function openAlbumHolder(ID) {
			
			setAlbumTop();
			
			$('#AlbumHolder').removeClass('Closed');
			$('#AlbumHolder').addClass('Open');

		};
		
		function loadPicture(PictureID) {
			
			if ( options.defaults.log ) 
				console.info( 'Load picture with ID ' + PictureID + ' from album ' + options.activeAlbumID );
			
			var _ID = options.core.Albums[ options.activeAlbumID ][PictureID].ID;
			
			if ( doesPictureExist( _ID ) === false ) {
				
				$('#EnlargementHolder').addClass('Loading');
				
				var HREF = options.core.Albums[ options.activeAlbumID ][PictureID].Picture;
				var Title = options.core.Albums[ options.activeAlbumID ][PictureID].Title;
				var Width = options.core.Albums[ options.activeAlbumID ][PictureID].Width;
				var Height = options.core.Albums[ options.activeAlbumID ][PictureID].Height;
				var ID = options.core.Albums[ options.activeAlbumID ][PictureID].ID;
				
				var _image = new Image();
				_image.width = Width;
				_image.height = Height;
				_image.id = 'Picture' + ID;
				_image.className = 'Picture';
				_image.alt = Title;
				$(_image).css('opacity', 0);
				
				$(_image).one( 'load', function(){
					$("#EnlargementHolder").append( _image );
					showPicture(ID);
					
				});
				
				_image.src = HREF;
				
			} else {
				showPicture( _ID );
			}
		};
		
		function loadContent(contentID) {
			
			var AlbumID = getActiveAlbumID();
			var Type = getAlbumType(AlbumID);		
			
			switch(Type) {
				case 1 : //Picture
					loadPicture(contentID);
				break;
				case 2 : // Youtube
					loadYoutube(contentID);
				break;
			}
			
		};
		
		function doesPictureExist(PictureID) {
			
			if ( $('#Picture' + PictureID ).length ) {
				if ( options.defaults.log )
					console.info('Picture met ID ' + PictureID + ' bestond reeds!');
				return true;
			} else {
				if ( options.defaults.log )
					console.info('Picture met ID ' + PictureID + ' bestond nog niet! Laden!');
				return false;
			}
		};
		
		function createTitleHolder() {
			$( '#AlbumHolder' ).append( 
					'<div class="TitleHolder" id="TitleHolder"><h2 id="AlbumTitle">Untitled</h2><div class="Amount" id="AmountHolder">Item <span id="AlbumCurrent"></span> van <span id="AlbumAmount"></span></div></div>' 
			);
		};
		
		function showTitle() {
			
			if ( options.defaults.log )
				console.info('Show title');
			
			var _Height = parseInt( options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Height );
			var _Width = parseInt( options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Width );
			var _Title = options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Title;
			
			$( '#TitleHolder' ).css( 'width', ( _Width + ( options.albumPadding * 2 ) ) );
			$( '#TitleHolder' ).css( 'top', _Height );
			$('#AlbumTitle').html( _Title );
			
			setCurrentCount();
			
			$( '#TitleHolder' ).animate({
				top: ( _Height + ( options.albumPadding * 2 ) ),
				height: 50
			}, 250, function() {
			});
			
		};
		
		function hideTitle() {
			
			if ( options.defaults.log )
				console.info('Hide title');
			
			$('#TitleHolder').animate({
				top: 0,
				height: 0
			}, 750, function() {
			});
		};
		
		function setCurrentCount() {
			
			var _Total = 0;
			var _Current = 0; 
			var _FoundCurrent = false;
			
			$.each( options.core.Albums[ options.activeAlbumID ], function( i ){
				if ( _FoundCurrent == false ) {
					if ( i == options.activeContentID ) {
						_FoundCurrent = true;
					}
					_Current++;
				}
				_Total++;
			});
			
			$('#AlbumCurrent').html( _Current );
			$('#AlbumAmount').html( _Total );
		};
		
		function countCurrentAlbum() {
			var _Total = 0;
			var _Current = 0; 
			var _FoundCurrent = false;
			
			$.each( options.core.Albums[ options.activeAlbumID ], function( i ){
				if ( _FoundCurrent == false ) {
					if ( i == options.activeContentID ) {
						_FoundCurrent = true;
					}
					_Current++;
				}
				_Total++;
			});
			
			return _Total;
		};
		
		function createCloseButton() {
			$( '#AlbumHolder' ).append( '<a class="Close" href="#" id="Close"></a>' );
			$('#Close').css('opacity', 0 );
			$('#Close').click(function(){
				close();
				return false;
			});
		};
		
		function hideCloseButton() {
			$('#Close').css('opacity', 0 );
		};
		
		function showCloseButton() {
			$('#Close').animate({
				opacity: 1
			}, 150, function() {
			});
		};
		
		function doesYoutubeExist(videoID) {
			if ( $('#Video' + videoID ).length ) {
				if ( options.defaults.log )
					console.info('Video met ID ' + videoID + ' bestond reeds!');
				return true;
			} else {
				if ( options.defaults.log )
					console.info('Video met ID ' + videoID + ' bestond nog niet! Laden!');
				return false;
			}
		};
		
		function loadYoutube(VideoID) {
			
			if ( options.defaults.log )
				console.info( 'Load youtube video with id ' + VideoID );
			
			if ( doesYoutubeExist(VideoID) === false ) {
				
				$('#EnlargementHolder').addClass('Loading');
				
				var SRC = 'http://www.youtube.com/embed/' + options.core.Albums[ options.activeAlbumID ][VideoID].YoutubeID;
				var ID = options.core.Albums[ options.activeAlbumID ][VideoID].ID;
				var Title = options.core.Albums[ options.activeAlbumID ][VideoID].Title;
				
				$('#EnlargementHolder').append(
						'<iframe id="Video' + ID + '" class="Closed" title="' + Title  + '" width="720" height="500" src="' + SRC + '?hd=1&autoplay=1&rel=0" frameborder="0" allowfullscreen></iframe>'
				);
				
				showYoutube(VideoID);
				
			} else {
				showYoutube(VideoID);
			}
		};
		
		function showYoutube(videoID) {
			
			options.activeContentID = videoID;
			
			if ( options.defaults.log )
				console.info( 'Open youtube video with id ' + videoID );
			
			resizeYoutube();

		};
		
		function showPicture(PictureID) {

			options.activeContentID = PictureID;
			resizePicture( PictureID );
		
			$("#EnlargementHolder").removeClass('Loading');
		};
		
		function hidePictures() {
			$('#EnlargementHolder img.Open').each(function(){
				$(this).animate({
					opacity: 0
				}, 150, function() {
					$(this).removeClass('Open');
					$(this).addClass('Closed');
				});
			});
		};
		
		function hideVideos() {
			$('#EnlargementHolder iframe').each(function(){
				$(this).remove();
			});
		};
		
		function hideEnlargements() {
			var Type = getAlbumType();
			switch( Type ) {
				case 1 :
					hidePictures();
				break;
				case 2 :
					hideVideos();
				break;
			}
			hideTitle();
		};
		
		function resizePicture( PictureID ) {
			
			if ( options.defaults.log )
				console.info('Resize album');
			
			var _Width = options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Width;
			var _Height = options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Height;
			
			hideButtons();
			
			$( '#EnlargementHolder' ).animate({
				height: _Height,
				width: _Width
			}, 1000, function() {
			});
			
			$( '#AlbumHolder' ).animate({
				height: _Height + 50 + ( options.albumPadding * 2 ),
				width: _Width + ( options.albumPadding * 2 ),
				marginLeft: ( ( ( _Width + ( options.albumPadding * 2 ) ) / 2 ) * -1 )
			}, 1000, function() {
				$('#Picture' + options.activeContentID).addClass('Open');
				$('#Picture' + options.activeContentID).removeClass('Closed');
				$('#Picture' + options.activeContentID).animate({
					opacity: 1
				}, 250, function() {
					showTitle(options.activeContentID);
					resizeButtonHolder();
					showCloseButton();
				});
			});
		};
		
		function resizeButtonHolder() {
			
			var _Width = options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Width;
			var _Height = options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Height;
			
			$('#ButtonHolder').css('height', _Height );
			$('#ButtonHolder').css('width', _Width );
			
			options.core.Busy = false;
			
			showButtons();
		};
		
		function resizeYoutube( videoID ) {
		
			if ( options.defaults.log )
				console.info('Resize album');
			
			var _Width = options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Width;
			var _Height = options.core.Albums[ options.activeAlbumID ][ options.activeContentID ].Height;
			
			hideButtons();
			
			$('#ButtonHolder').css('height', 455 );
			$('#ButtonHolder').css('width', _Width );

			$( '#EnlargementHolder' ).animate({
				height: _Height,
				width: _Width
			}, 1000, function() {
			});
			
			$( '#AlbumHolder' ).animate({
				height: _Height + 50 + ( options.albumPadding * 2 ),
				width: _Width + ( options.albumPadding * 2 ),
				marginLeft: ( ( ( _Width + ( options.albumPadding * 2 ) ) / 2 ) * -1 )
			}, 1000, function() {
				$('#EnlargementHolder').removeClass('Loading');
				$('#Video' + options.activeContentID).addClass('Open');
				$('#Video' + options.activeContentID).removeClass('Closed');
				showTitle(options.activeContentID);
				showCloseButton();
				options.core.Busy = false;
			});
		};
		
		function reset() {
			
			if ( options.defaults.log )
				console.info('Reset album');

			$( '#AlbumHolder' ).removeClass('Closed');
			$( '#AlbumHolder' ).addClass('Open');
			$( '#AlbumHolder' ).css('marginLeft', '-40px');
			$( '#AlbumHolder' ).css('height', 100);
			$( '#AlbumHolder' ).css('width', 100);
			$( '#EnlargementHolder' ).css('height', 80);
			$( '#EnlargementHolder' ).css('width', 80);
			$( '#EnlargementHolder' ).addClass('Loading');
			
			hideCloseButton();
			
		};
		
		function albumExists(ID) {
			if ( options.core.Albums[ ID ] === undefined ) {
				if ( options.defaults.log )
					console.info( 'Check if album ' + ID + ' already exists.Result: No' );
				return false;
			} else {
				if ( options.defaults.log )
					console.info( 'Check if album ' + ID + ' already exists.Result: Yes' );
				return ID;
			}
		};
		
		function createButtonHolder() {
			$('#AlbumHolder').append('<div id="ButtonHolder"></div>');
			$('#ButtonHolder').mouseover(function(){
				showButtons();
			}).mouseleave(function(){
				hideButtons();
			});
			$('#ButtonHolder').css('opacity', 0 );
			createNextButton();
			createPreviousButton();
		};
		
		function showButtons() {
			
			if ( options.core.Busy === false ) {
				var _Count = countCurrentAlbum();
				if ( _Count > 1 ) {
					$( '#ButtonHolder' ).removeClass('Inactive');
					$( '#ButtonHolder' ).animate({
						opacity: 1
					}, 250, function() {
					});
				} else {
					$( '#ButtonHolder' ).addClass('Inactive');
				}
			}
			
		}
		
		function hideButtons() {
			$( '#ButtonHolder' ).animate({
				opacity: 0
			}, 250, function() {
			});
		}
		
		function createNextButton() {
			$('#ButtonHolder').append('<a href="#" id="AlbumNext" class="Button Next"></a>');
			$('#AlbumNext').click(function(){
				if( options.core.Busy === false ) {
					options.core.Busy = true;
					setNext();
					return false;
				} else {
					return false;
				}
			});
		};
		
		function createPreviousButton() {
			$('#ButtonHolder').append('<a href="#" id="AlbumPrevious" class="Button Previous"></a>');
			$('#AlbumPrevious').click(function(){
				if( options.core.Busy === false ) {
					options.core.Busy = true;
					setPrevious();
					return false;
				} else {
					return false;
				}
			});
		};
		
		function setNext() {
			
			if ( $('#ButtonHolder').hasClass('Inactive') )
				return false;

			hideEnlargements();
			
			if ( options.defaults.log )
				console.info('Set next!');
			
			var _Active = parseInt( options.activeContentID );
			var _Counter = 1;
			var _First = -1;
			var _GetNext = false;
			var _NewNext = -1;
			
			$.each( options.core.Albums[ options.activeAlbumID ], function( i, e ) {
				//In de vorige wellicht de huidige actieve gevonden? Dan is dit de volgende!
				if ( _GetNext == true ) {
					_NewNext = i;
					return false;
				}
				//Ook de eerste opslaan, voor het geval de huidige de laatste is. Dan moeten we opnieuw beginnen.
				if ( _Counter == 1 ) {
					_First = i;
				}
				//Als dit de huidige is, dan moet de volgende ronde de laatste zijn.
				if ( i == _Active ) {
					_GetNext = true;
				}
				_Counter++;
			});
			
			//Als dit de laatste was, dan opnieuw beginnen.
			if ( _NewNext < 0 ) {
				if ( options.defaults.log )
					console.info('It was the last from this album, start over again with picture ' + _First );
				_NewNext = _First;
			}
			
			if ( options.defaults.log )
				console.info('New active: ' + _NewNext );
			
			load( _NewNext );
		};
		
		function setPrevious() {
			
			if ( $('#ButtonHolder').hasClass('Inactive') )
				return false;
			
			hideEnlargements();
			
			if ( options.defaults.log )
				console.info('Set previous!');
			
			var _Active = parseInt( options.activeContentID );
			var _Counter = 1;
			var _Last = -1;
			var _FoundCurrent  = false;
			var _NewPrevious = -1;
			
			$.each( options.core.Albums[ options.activeAlbumID ], function( i, e ) {
				
				//Telkens het object bijhouden, deze variabele wordt vanzelf de laatste als de loop eindigd
				_Last = i;
						
				//Is dit de huidige. Dan moeten we dus de vorige hebben.
				if ( i == options.activeContentID ) {
					_FoundCurrent = true;
				} else {
					//We hebben hem nog niet gevonden, vorige bijhouden
					if ( _FoundCurrent == false ) {
						_NewPrevious = i;
					} else {
						//Hij heeft hem al gevonden
					}
				}
				_Counter++;
			});			
			
			if ( _NewPrevious == -1 || _FoundCurrent == false ) {
				if ( options.defaults.log )
					console.info('It was the first item of this album, return to last picture with ID ' + _Last );
				_NewPrevious = _Last;
			}
			
			if ( options.defaults.log )
				console.info('New active: ' + _NewPrevious );
			
			load( _NewPrevious );
		};	
		
		function load(Item) {
			var Type = getAlbumType(options.activeAlbumID);			
			switch(Type) {
				case 1 : //Picture				
					loadPicture( Item );
				break;
				case 2 : // Youtube
					loadYoutube( Item );
				break;
			}
		}
		
	};
})(jQuery);
