jQuery(function(){
    jQuery('#gallery li').each(function(idx) {
        jQuery(this).data('index', (++idx));
    });

    jQuery('#gallery').jcarousel({
        scroll: 1,
        initCallback: initCallbackFunction
    })
    
    function initCallbackFunction(carousel) {
        jQuery('#img').bind('image-loaded',function() {
            var idx =  jQuery('#gallery li.active').data('index') - 2;
            
            carousel.scroll(idx);
            return false;
        });
        
    };

    // load and fade-in thumbnails
    jQuery('#gallery li img').css('opacity', 0).each(function() {    
        if (this.complete || this.readyState == 'complete') { jQuery(this).animate({'opacity': 1}, 300) } 
        else { jQuery(this).load(function() { jQuery(this).animate({'opacity': 1}, 300) }); }
    });

    
      
    var slideshow,
        slideshowPause =  jQuery('#slideshow-pause').val() 

    jQuery('#slideshow-pause').change(function(){
        slideshowPause = this.value
        
        // clear interval when timeout is changed
        window.clearInterval(slideshow)

        // and set new interval with new timeout value
        slideshow = window.setInterval(function(){
            $.galleria.next()
        }, slideshowPause * 1000) // must be set in milisecond
    })

    jQuery('input#toggle-slideshow').change(function(){
        if (this.checked) {
            jQuery('#slideshow').fadeIn()
            
            // set interval when slideshow is enabled
            slideshow = window.setInterval(function(){
                $.galleria.next()
            }, slideshowPause * 1000)
        } else {
            jQuery('#slideshow').fadeOut()
            
            // clear interval when slideshow if disabled
            window.clearInterval(slideshow)
        }
    })
});



