$(function(){
    $('#gallery li').each(function(idx) {
        $(this).data('index', (++idx));
    });

    $('#gallery').jcarousel({
        scroll: 7,
        initCallback: initCallbackFunction
    })
    
    function initCallbackFunction(carousel) {
        $('#img').bind('image-loaded',function() {
            var idx =  $('#gallery li.active').data('index') - 3;
            
            carousel.scroll(idx);
            return false;
        });
    };
	
	 // load and fade-in thumbnails
    $('#gallery li img').css('opacity', 0).each(function() {    
        if (this.complete || this.readyState == 'complete') { $(this).animate({'opacity': 1}, 300) } 
        else { $(this).load(function() { $(this).animate({'opacity': 1}, 300) }); }
    });


	$('ul#gallery').galleria({
		history   : false,
        // #img is the empty div which holds full size images
        insert: '#img',
        
        // function fired when the image is displayed
        onImage: function(image, caption, thumb) {        
            // fade in the image 
            image.hide().fadeIn(500);
            
            // animate active thumbnail's opacity to 1, other list elements to 0.6
            thumb.parent().fadeTo(200, 1).siblings().fadeTo(200, 0.6)
				
				$('#img').trigger('image-loaded')
				
				// this will add a class to landscape images allowing extra margin
				if (image.height() < image.width()) {
					$('#img').addClass('landscape');
				} else {
					$('#img').removeClass('landscape');
				}
				
			},
			
			// function similar to onImage, but fired when thumbnail is displayed
        	onThumb: function(thumb) {
            var $li = thumb.parent(),
                opacity = $li.is('.active') ? 1 : 0.6;
            
            // hover effects for list elements
            $li.hover(
                function() { $li.fadeTo(200, 1); },
                function() { $li.not('.active').fadeTo(200, opacity); }
            	)
        	}      
		});
	});
