;(function($){
	
	$(document).ready(function(){
		
		var $container      = $('#media'),
			$largeImg       = $('.view-image', $container),
			$thumbContainer = $('.thumbs', $container),
			$thumbs         = $('a', $thumbContainer),
			$prev           = $('.prev', $container),
			$next           = $('.next', $container),
			$prevPage       = $('.prev-page', $container),
			$nextPage       = $('.next-page', $container),
			self			= this,
			currentIndex    = 0,
			currentPage     = 0,
			itemsPerPage    = 5,
			totalThumbs     = $thumbs.length,
			totalPages      = Math.ceil(totalThumbs/itemsPerPage);
			
		
		// Voorbereiding		
		this.prepareMarkup = function() 
		{
			$thumbContainer
				.css({ overflowY: 'hidden' })
				.scrollTop(0);
			
			$('#total-pages').html(totalPages);
			$('#current-page').html(1);
			
			this.activateThumb(0);
			this.bindEvents();
		}
		
		this.bindEvents = function()
		{
			$prev.click(this.gotoPrev);
			$next.click(this.gotoNext);
			$prevPage.click(this.gotoPrevPage);
			$nextPage.click(this.gotoNextPage);
			
			$thumbs.click(function(){
				
				$li = $(this).parent();
				var index = $('li', $thumbContainer).index($li);
				self.activateThumb(index);
				
				return false;
			}); 
		}
		
		this.gotoNext = function()
		{
			if (currentIndex < totalThumbs) {
				self.activateThumb(currentIndex + 1);
			}
			return false;
		}
		
		this.gotoPrev = function()
		{
			if (currentIndex > 0) {
				self.activateThumb(currentIndex - 1);
			}
			return false;
		}
		
		this.gotoNextPage = function()
		{
			if (currentPage < totalPages) {
				page = currentPage + 1;
				self.activateThumb(page * itemsPerPage);				
			}
			return false;
		}
		
		this.gotoPrevPage = function()
		{
			if (currentPage > 0) {
				self.activateThumb(((currentPage - 1) * itemsPerPage) + (itemsPerPage - 1));
			}
			return false;	
		}
		
		this.activateThumb = function(index) 
		{
			currentIndex = index;
			
			$('li', $thumbContainer).removeClass('active');
			$('li:eq(' + index + ')', $thumbContainer).addClass('active');
			
			if (Math.floor(currentIndex / itemsPerPage) != currentPage) {
				self.gotoPage(Math.floor(currentIndex / itemsPerPage));
			}
			
			var src = $('a:eq(' + index + ')', $thumbContainer).attr('href');
			this.loadImage(src);
			
		}
		
		this.loadImage = function(src)
		{
			$largeImg.attr('src', src);
		}
		
		this.gotoPage = function(page)
		{
			var pageHeight = 550;
			
			currentPage = page;
			$('#current-page').html(currentPage+1);
			$thumbContainer.animate({ scrollTop: (pageHeight * page)}, 1000);
			
		}
		
		this.prepareMarkup();
				
	})
	
})(jQuery);
