var PromoSwitcher = function() {
    var interval = 6000;
    var switcher, nodes, first, last, clone, that, next, previous;   
                    
    return {
        init: function() {
            switcher = YAHOO.util.Dom.get('grafs-promo-switcher');
            nodes    = switcher.getElementsByTagName('div');
            first    = nodes[0];
            last     = nodes[nodes.length - 1];
            clone    = first.cloneNode(true);
            that     = this;

            this.clearTimeout = false;
            this.reverse      = false;
            
            switcher.appendChild(clone, last);

            next     = YAHOO.util.Dom.get('grafs-carousel-nav-next');
            previous = YAHOO.util.Dom.get('grafs-carousel-nav-previous');

            YAHOO.util.Event.on(next, 'click', function(e) {
                that.reverse = false;
                that.animate(e);
            });
            
            YAHOO.util.Event.on(previous, 'click', function(e) {
                that.reverse = true;
                that.animate(e);
            });

            setTimeout(this.animate, interval);
        },
        
        animate: function(e) {
            if (e) {
                YAHOO.util.Event.stopEvent(e);
                that.clearTimeout = true;
                interval = 18000;
            }

            if (that.locked) {
                return;
            }

            if (that.clearTimeout && ! e) {
                that.clearTimeout = false;
                that.locked = false;
                interval = 6000;
                return;
            }

            that.locked = true;

            if (switcher.scrollTop >= (nodes.length - 1) * 240) {
                switcher.scrollTop = 0;  
            }

            if (that.reverse) {
                var attributes = { 
                    scroll: { 
                        to: [switcher.scrollTop, switcher.scrollTop - 240] 
                    }
                };
            } else {
                var attributes = { 
                    scroll: { 
                        to: [switcher.scrollTop, switcher.scrollTop + 240] 
                    }
                };
            }

            var anim = new YAHOO.util.Scroll(switcher, attributes); 

            anim.onComplete.subscribe(function(e) {
                that.locked = false;

                setTimeout(that.animate, interval);
            });

            anim.animate();
        }
    };
}();

