$(document).ready(function(){

    images.start();

});



var images = {

    interval: 4000,

    list: [

        'images/rotate/gran_01.jpg',

        'images/rotate/gran_02.jpg',

        'images/rotate/gran_03.jpg',

        'images/rotate/gran_04.jpg'

    ],

    index: 0,

    start: function(){

        $('#rotator').css('position', 'relative');

        this.list.sort(

            // randomize

            function(){

                return Math.random()-0.5;

            }

        );

        this.next();

    },

    current: function( image ){

        if( image ){

            this.list[this.index] = image;

        }

        return this.list[this.index];

    },

    next: function(){

        // pick next

        if( this.index != this.list.length-1 ) this.index++;

        else this.index = 0;

        // fade in new image

        this.show();

        // next

        setTimeout( 'images.next()', this.interval );

    },

    show: function(){

        // load

        if( typeof(this.current()) == 'string' ){

            var image = new Image();

            image.src = this.current();

            this.current( image );

            // css

            $( this.current() ).hide()

            .css('z-index', '0')

            .css('position', 'absolute')

            .css('top', '0')

            .css('left', '0');

        }

        // place

        if( !this.current().parentNode || this.current().parentNode.id != 'rotator' ){

            $('#rotator').append( this.current() );

        }

        // show

        $('#rotator img').css('z-index', '0');

        $( this.current() )

        .css('z-index', '10')

        .fadeIn('slow', function(){

            $(this).siblings().hide();

        });

    }

}


