jQuery(function($)
{
	var animate_slideshow = $('#gallery,#small-gallery,#photo-gallery').hasClass('gallery_slideshow');
	if ( animate_slideshow )
	{
		gallery.resetSlideshow();
	}
	
	gallery.showNext();
	
	$('.gallery_trigger')
		.css('cursor', 'pointer')
		.bind('click', function(e)
		{
			var count = jQuery(this).index();
			gallery.showImage( parseInt(count) );
			
			if ( animate_slideshow )
			{
				gallery.resetSlideshow();
			}
		});

	$(window).resize(resize);
	resize();
	
	function resize()
	{
		var $gallery = $('#small-gallery');
		var new_height = Math.round($gallery.width() / 2.47);
		$gallery.height(new_height);	
		
		var $gallery = $('#photo-gallery');
		var new_height = Math.round($gallery.width() / 2.47) + 8;
		$gallery.closest('.image-banner-medium-border-inner').height(new_height);	
		
		
		
	}
});

var gallery = (function() {
	/* Private variables */
	var currentImage;
	var timer;
	var currentIndex = -1;
	var interval = 3000;
	
	var gallery = { 
		showImage: function(index)
		{
			var $LIs = jQuery('#gallery li,#small-gallery li,#photo-gallery li').css('position','absolute');
			jQuery('#thumbnail-bar').show();
			
			if(index < $LIs.length)
			{
				var indexImage = $LIs.eq(index);
				
				// Remove all active classes from triggers
				jQuery('.gallery_trigger').removeClass('active');
				
				if(currentImage)
				{
					if ( currentIndex != index )
					{
						jQuery(currentImage).css('z-index',2);
						jQuery(currentImage).fadeOut(1000, function() {
							jQuery(this).css({'display':'none','z-index':1})
						});
					}
				}
				jQuery(indexImage).css({'display':'block', 'opacity':1});
				
				// Add active class to a trigger with current index				
				jQuery('.gallery_trigger').eq(index).addClass('active');
				
				currentImage = indexImage;
				currentIndex = index;
			}
		},
	
		showNext: function()
		{
			var len = jQuery('#gallery li,#small-gallery li,#photo-gallery li').length;
			var next = currentIndex < (len-1) ? currentIndex + 1 : 0;
			gallery.showImage(next);
		},
	
		resetSlideshow: function()
		{
			clearInterval(timer);
			timer = setInterval(gallery.showNext, interval);
		}
	}
	
	return gallery;
})();

