
(function() {

    /**
     * Class for fading through a slideshow of images. Used on the homepage.
     */
    function ImageFader(imagePaths, container) {
        this.imagePaths = imagePaths;
        this.container = container || document.body || document.documentElement;
        this.images = [];
        this.showNext();
    }
    ImageFader.prototype = {

        speed : 5,
        waitBetween : 5000,
        current : 0,
        zIndex : 1,

        loadImage : function( idx, callback ) {
            var images = this.images,
                img = images[ idx ];

            if( img ) {
                callback( img );
            } else {
                img = new Image();
                img.onload = function() {
                    images[ idx ] = img; //add once loaded
                    callback( img );
                };
                img.className = "fade-image";
                this.setOpacity( img, 0 );
                this.container.appendChild(img);
                img.src = this.imagePaths[ idx ];
            }
        },

        animateIn : function( img, callback ) {
            var me = this,
                opacity = 0;

            img.style.zIndex = this.zIndex++;

            function step() {
                me.setOpacity( img, Math.min( opacity, 1 ) );
                if( opacity < 1 ) {
                    opacity += (me.speed * 0.01);
                    setTimeout( step, 100 );
                } else {
                    callback();
                }
            }
            step();
        },

        showNext: function() {
            var me = this,
                idx = this.current;

            function wait() {
                setTimeout( function() {
                    me.showNext();
                }, me.waitBetween );
            }

            function loaded( img ) {
                me.animateIn( img, wait );
            }

            this.loadImage( idx++, loaded );
            if( idx >= this.imagePaths.length  ) {
                idx = 0;
            }
            this.current = idx;
        },

        setOpacity : function( img, opacity ) {
            img.style.display = (opacity == 0 ? "none" : "");
            img.style.opacity = img.style.MozOpacity = img.style.KhtmlOpacity = opacity;
            img.style.filter = "alpha(opacity=" + (opacity * 100) + ")";
        }
    };


    var photoCont = document.getElementById( 'photoCont' );
    if( photoCont ) {
        new ImageFader( photoCont.getAttribute( 'data-photos' ).split( ',' ), photoCont );
    }

})();
