var Glider = new Class({

	initialize: function(wrapper, options){
	    this.wrapper    = $(wrapper);
	    this.scroller   = this.wrapper.getElement('div.scroller');
	    this.sections   = this.wrapper.getElements('div.section');    
	    this.options    = $extend({ duration: 1.0, frequency: 3 }, options || {});
	    this.sections.each(function(section, index) { section._index = index; });
	    this.myFx       = new Fx.Scroll(this.scroller);
	    
	    this.events = { };

		if(this.options.initialSection) {
			if (this.options.initialSection == 'random') {
				this.moveTo(this.sections.getRandom(), this.scroller);
			} else {
				this.moveTo(this.options.initialSection, this.scroller);  // initialSection should be the id of the section you want to show up on load
			}
		}
	
		if(this.options.autoGlide) this.start();
	},	

	moveTo: function(element, container){
		var position = element.getPosition(container);
		// Cancel any current scrolls (gets rid of flickering on rapid clicking)
		this.myFx.cancel();
		
		this.myFx = new Fx.Scroll(container).toElement(element);
		
		this.current = $(element);
    	return false;
	},
		
	moveNext: function(manualMove){
		if (manualMove != null) { this.periodicallyUpdate(true); }	  
	    if (this.current) {
	      var currentIndex = this.current._index;
	      var nextIndex = (this.sections.length - 1 == currentIndex) ? 0 : currentIndex + 1;      
	    } else var nextIndex = 1;
	    this.moveTo(this.sections[nextIndex], this.scroller);
	},
	
	movePrevious: function(manualMove){
	  	if (manualMove != null) { this.periodicallyUpdate(true); }		
	    if (this.current) {
	      var currentIndex = this.current._index;
	      var prevIndex = (currentIndex == 0) ? this.sections.length - 1 : 
	       currentIndex - 1;
	    } else var prevIndex = this.sections.length - 1;	    
	    this.moveTo(this.sections[prevIndex], this.scroller);
	},
	
	next: function() { if(this.options.manualGlide) { this.moveNext(); } else { this.moveNext(true); }  },	
	previous: function() { if(this.options.manualGlide) { this.movePrevious(); } else { this.movePrevious(true); } },  
	stop: function() { clearTimeout(this.timer); },	
	start: function() {	this.periodicallyUpdate(); },	
		
	periodicallyUpdate: function(dontMove) { 
		if (this.timer != null) {
			clearTimeout(this.timer);
			if (dontMove != true) {	this.moveNext(); }
		}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency*1000);
	}
});