$(function(){
    // fade in the image & caption
    var fade_in_time = 1000;
    var inactive_thumb_opacity = 0.5;
    var active_thumb_opacity = 1;
        
    $('#gallery li').each(function(idx) 
    {
        $(this).data('index', (++idx));
    });

    $('#gallery').jcarousel
    (
     {
        //visible: 5, // count of visible pix
        scroll: 5,
        //size: 8,
        wrap: "both", // "last" | "first" | "both"
        auto: 5000, // milliseconds
        initCallback: initCallbackFunction
     }
    )
    
    function initCallbackFunction(carousel) 
    {
        $('#image').bind('image-loaded',function() 
        {
            var idx =  $('#gallery li.active').data('index') - 2;
            
            carousel.scroll(idx);
            return false;
        });

        // hotkeys plugin: use arrows to control the gallery
        $(document).bind('keydown', 'right', function (evt){ $.galleria.next(); });
        $(document).bind('keydown', 'left', function (evt){ $.galleria.prev(); });
        $(document).bind('keydown', 'up', function (evt){ $('.jcarousel-next-horizontal').click(); return false; });
        $(document).bind('keydown', 'down', function (evt){ $('.jcarousel-prev-horizontal').click(); 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': active_thumb_opacity}, 300) }); }
    });

    var slideshow = $('#slideshow')

    // firefox leaves fields checked after page refresh
    $("#toggle-slideshow").removeAttr('checked');
    window.clearInterval($("#toggle-slideshow"))
        
    $('input#toggle-slideshow').change(function()
    {
        var slideshowPause =  $('#slideshow-pause').val() 

        window.clearInterval(slideshow)

        if (this.checked) 
        {
            slideshow = window.setInterval(function(){ $.galleria.next() }, slideshowPause * 1000) 
        } 
    })

    $('#slideshow-pause').change(function()
    {
        var slideshowPause =  $('#slideshow-pause').val() 
        
        // 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)
    })
    
    $('#gallery').galleria({
        history     : true, // enable history plugin
		    clickNext   : false,
        insert      : '#main_image', // selector for container of full-size images
        
        // function fired when the image is displayed
        onImage: function(image, caption, thumb) 
        {        
            if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) 
            { // FF/Win fades large images terribly slow
              image.css('display','none').fadeIn(fade_in_time);
            }
            caption.css('display','none').fadeIn(fade_in_time);
            
            // animate active thumbnail's opacity to active_thumb_opacity, other list elements to inactive_thumb_opacity
            thumb.parent().fadeTo(200, 1).siblings().fadeTo(200, inactive_thumb_opacity)
           
            // set hadlers for the big image
            image
                .trigger('image-loaded')
                .hover( function() {} )
                .click ( function(evt) 
                 {
                   // allow moving to previous/next image by clicking o left/righ side of the big image
                   var correctionX = 300; // wtf?
                   var correctionY = 128; // wtf?

                   var relativeX = evt.pageX - this.offsetLeft - correctionX;
                   var relativeY = evt.pageY - this.offsetTop - correctionY;
                   //alert("###[x,y][w,h] : [" + relativeX + "," + relativeY + "][" + this.width + "," + this.height + "]" );

                   if ( relativeX <= this.width / 2) { $.galleria.prev(); }
                   else { $.galleria.next(); } 
                 });
        },
        
        // function similar to onImage, but fired when thumbnail is displayed
        onThumb: function(thumb) 
        {
            var $li = thumb.parent(),
                      opacity = $li.is('.active') ? active_thumb_opacity : inactive_thumb_opacity;
            
            // hover effects for list elements
            $li.hover
            (
                function() { $li.fadeTo(200, active_thumb_opacity); }, // separate opacity setting for this case?
                function() { $li.not('.active').fadeTo(200, opacity); }
            )
        }        
    })

    .find('li:first').addClass('active') // display first image when Galleria is loaded
});

