jQuery(function(){
	var gallery = {
		$container : $('#gallery'),
		$thumbs : $('#gallery_thumbs'),
		thumbcount : $('#gallery_thumbs').children('li').length,
		thumbcurrent : 0,
		thumbmax : 7,
		thumbwidth : 46 + 2 + 11,
		rotate : function(control, direction){
			if(!$(control).hasClass('disabled')){
				//calculate new position
				$('.gallery_control').removeClass('disabled');
				if(direction == 'previous'){
					this.thumbcurrent--;
					if(this.thumbcurrent == 0){
						$('#gallery_prev').addClass('disabled');
					}
				}else if(direction == 'next'){
					this.thumbcurrent++;
					if(this.thumbcurrent == (this.thumbcount - this.thumbmax)){
						$('#gallery_next').addClass('disabled');
					}
				}
				this.slide();
			}
		},
		slide : function(){
			var newpos = -this.thumbwidth * this.thumbcurrent;
			//disable controls during animation
			this.$thumbs.animate({left: newpos+'px'}, 500);
			//enable controls
		},
		init: function(){
			//set behavior of preview tiles
			$('#gallery_thumbs li a')
				.each(function(){
					//set background images
					$(this).css('backgroundImage' , 'url('+$(this).attr('href').replace(/large/, 'thumb')+')' );
				})
				.click(function(){
					if (!$(this).hasClass('current')) {
						//remove current class
						gallery.$thumbs.children('li').children('a.current').removeClass('current');
						//swap image
						$('#view_large').attr('src', $(this).attr('href'));
						//change caption
						$('#view_description').html($(this).attr('title') + '&nbsp;');
						//add current class
						$(this).addClass('current');
					}
					return false;
				});
			//set width of gallery ul
			this.$thumbs.width(this.thumbcount * this.thumbwidth + 10);
			//set initial position ==> Possible deep linking
			this.slide();
			if (this.thumbcount > this.thumbmax) {
				//append forward/back controls
				$('<a href="#previous" id="gallery_prev" class="gallery_control disabled">Previous</a>')
					.click(function(){ gallery.rotate(this, 'previous'); return false;})
					.appendTo(this.$container);
				$('<a href="#next" id="gallery_next" class="gallery_control">Next</a>')
					.click(function(){ gallery.rotate(this, 'next'); return false;})
					.appendTo(this.$container);
			}//endif
		}
	}
	gallery.init();
});