var fotogallery = {
    chnageDelay: 6000,
    json:null,
    init: function(json) {
        if( $('div.body.fotogallery').size() == 0 ) {
            return;
        }
    
        $('div.body.fotogallery').hover(
            function(){
                fotogallery.autoChangeStop();
                $('div.body.fotogallery .navAuto').html('auto-rotacja wyłączona');
            },
            function(){
                fotogallery.autoChangeStart();
                $('div.body.fotogallery .navAuto').html('auto-rotacja włączona');
            }
        );
        $('div.body.fotogallery p.nav a').click(function(){
            fotogallery.changePhoto($(this).attr('id'));
            return false;
        });
        fotogallery.json = json;
        fotogallery.autoChangeLoopLastRun = new Date().getTime();
        fotogallery.autoChangeIsRunning = true;
        fotogallery.autoChangeLoop();
        var rand_id = 'n' + Math.floor(Math.random()*7+1);
        fotogallery.changePhoto(rand_id);
    },
    autoChangeStart: function() {
        fotogallery.autoChangeLoopLastRun = new Date().getTime();
        fotogallery.autoChangeIsRunning = true;
    },
    autoChangeDelayStart: function(delay) {
        fotogallery.autoChangeLoopLastRun = new Date().getTime() + delay;
        fotogallery.autoChangeIsRunning = true;
    },
    autoChangeStop: function() {
        fotogallery.autoChangeIsRunning = false;
    },
    autoChangeTick: function() {
        var obj = $('div.body.fotogallery p.nav a.active').next('a');
        if( obj.size() != 1 ) {
            obj = $('div.body.fotogallery p.nav a:first');
        }
        obj.click();
    },
    autoChangeIsRunning: false,
    autoChangeLoopLastRun: false,
    autoChangeLoop: function() {
        setTimeout(fotogallery.autoChangeLoop,100);
        if( (new Date().getTime() - fotogallery.autoChangeLoopLastRun) > fotogallery.chnageDelay && fotogallery.autoChangeIsRunning == true ) {
            fotogallery.autoChangeTick();
            fotogallery.autoChangeLoopLastRun = new Date().getTime();
        }
    },
    changePhoto: function(id) {
        
        if( fotogallery.json[id]['url'] != null && fotogallery.json[id]['url'] != '') {
            $('div.body.fotogallery a.aimg').attr('href', fotogallery.json[id]['url']);
        } else {
            $('div.body.fotogallery a.aimg').removeAttr('href');
        }
        if( fotogallery.json[id]['title'] != null && fotogallery.json[id]['title'] != '' ) {
            $('div.body.fotogallery a.aimg').attr('title', fotogallery.json[id]['title']);
        } else {
            $('div.body.fotogallery a.aimg').removeAttr('title');
        }
        
        $('div.body.fotogallery p.desc').html( fotogallery.json[id]['desc'] );
        $('div.body.fotogallery div.img').css('background-image', 'url('+fotogallery.json[id]['img']+')' );
        $('div.body.fotogallery p.nav a.active').removeClass('active');
        $('#'+id).addClass('active');
    }
}; 

