(function() {
    var buttons, images, fades = [];
    var to = null; i = 0;
    
    function slide(restart) {
        stop();
        
        var next, node, fade;
        
        restart = restart !== false;
        next = i + 1;
        
        if(next > images.length - 1) {
            next = 0;
        }
        
        for(var n = 0; n < images.length; n++) {
            if(n == next || fades[n].fadeOut || !dojo.hasClass(images[n], "visible")) {
                continue;
            }
            
            node = images[n];
            fade = fades[n];
            
            fade.fadeOut = dojo.fadeOut({
                node: node,
                fade: fade,
                onEnd: function() {
                    dojo.removeClass(this.node, "visible");
                    delete this.fade.fadeOut; 
                }
            }).play();
        }
        
        node = images[next];
        fade = fades[next];
        
        if(fade.fadeOut) {
            fade.fadeOut.stop();
            delete fade.fadeOut;
        }
         
        if(!dojo.hasClass(node, "visible")) {
            dojo.style(node, "opacity", 0);
            dojo.addClass(node, "visible");
        }
        
        if(fade.fadeIn) {
        	fade.fadeIn.onEnd = function() {
        		i = next;
        		restart && start();
        		delete this.fade.fadeIn;
        	};
        	
        	return;
        }
        
        fade.fadeIn = dojo.fadeIn({
           node: node,
           fade: fade,
           onEnd: function() {
               i = next;
               restart && start();
               delete this.fade.fadeIn;
           }
        }).play();
    }
    
    function stop() {
        clearTimeout(to);
        to = null;
    }
    
    function start() {
        stop();
        to = setTimeout(slide, 10000);
    }
    
    function buttonOver(e) {
        if(!dojo.hasClass(e.target, "button")) {
            return;
        }
        
        var text = e.target.innerText || e.target.textContent;
        var ps = dojo.byId("picshow");
        var h = dojo.connect(ps, "mouseout", null,
            function() {
                dojo.disconnect(h);
                start();
            }
        );
        
        i = parseInt(text) - 2;
        slide(false);
        dojo.stopEvent(e);
    }
    
    dojo.addOnLoad(function() {
        buttons = dojo.query("#picshow .button");
        images = dojo.query("#picshow .pic");
        
        dojo.addClass(images[0], "visible");
        
        dojo.forEach(images, function(img, idx) {
            fades[idx] = {};
        });
        
        buttons.connect("mouseover", buttonOver);
        start();
    });
})();
