var gallery = function() {

	var __self = this;
	
	// Eigenschaften ///////
	this.images = [];
	this.currentIndex;
	
	this.config = {
		image : {
			target: '#backgroundimage_container'
		},
		navigation: {
			target: '#backgroundimage_container'
		},
		animation : {
			type: 'fade',
			speed: 1000
		}
	}
	
	
	// öffentliche Methoden ////////////
	
	this.init = function() {
	
		__self.currentIndex = 0;
		
		if(this.images.length > 1) {
			attachNavigation();
		}
				
	}

	this.registerImage = function(file, objId) {
		this.images.push(
			{src: file, id: objId}
		);
	}
	
	this.next = function() {
		if(__self.currentIndex < __self.images.length-1) {
			__self.currentIndex++;
		} else {
			__self.currentIndex = 0;
		}
		
		markCurrentImageAsDepricated();
		loadImg(__self.currentIndex);
		
	}
	
	this.prev = function() {
		if(__self.currentIndex > 0) {
			__self.currentIndex--;
		} else {
			__self.currentIndex = __self.images.length-1;
		}
		
		markCurrentImageAsDepricated();
		loadImg(__self.currentIndex);
	}
	
	// private Methoden //////////////
	
	markCurrentImageAsDepricated = function() {
		$('.e2.current').removeClass('current').addClass('old');
	}
	
	loadImg = function(index) {
		var img = new Image();
			img.onload = function() {
				imgOnLoad(this, __self.images[index].id);
			}
			
			jQuery(img).addClass('e2');
			jQuery(img).addClass('current');
			
			img.src = __self.images[index].src;

	}
	
	imgOnLoad = function(img, objId) {
	
		jQuery(img).css({'display':'none'});	
		jQuery(__self.config.image.target).append(img);
		
		jQuery(img).fadeIn(__self.config.animation.speed, function() {
			jQuery('.e2.old').remove();
		});
		//jQuery('.e2.old').fadeOut(__self.config.animation.speed, function() {jQuery(this).remove();});
		
		background.setSize();
		jQuery('.fe_background').hide();
		jQuery('#fe_'+objId).show();
	}
	
	attachNavigation = function() {
		var prev = jQuery(__self.config.navigation.target).append('<div class="bg_prev"></div>');
		var next = jQuery(__self.config.navigation.target).append('<div class="bg_next"></div>');		
		jQuery(__self.config.navigation.target+' .bg_prev').click(function() {__self.prev()});
		jQuery(__self.config.navigation.target+' .bg_next').click(function() {__self.next()});
	}
}
