Glider = function(wrapper, options) {
   this.initialize(wrapper, options);
}

Glider.prototype = {

   initialize: function(wrapper, options){
      this.scrolling  = false;
      this.wrapper    = $(wrapper).get(0);
      this.scroller   = $(wrapper).children('.scroller').get(0);
      this.sections   = $(wrapper).children('.section').get();
      this.options    = $.extend(false, { duration: 1.0, frequency: 3 }, options || {});

      $.each(this.sections, function(index, section) { section._index = index; });

      this.addObservers();

      if (this.options.initialSection) this.moveTo(this.options.initialSection, this.scroller, { duration:this.options.duration });
      if (this.options.autoGlide) this.start();
   },

   addObservers: function() {
      var controls = $(this.wrapper).find('.controls a').get();
      var self = this;
      $(controls).bind('click', function(e){ self.click(e, this);return false; });
   },

   click: function(event, element) {
      this.stop();
      this.moveTo(element.href.split("#")[1], this.scroller, { duration: this.options.duration*1000 });
      event.cancelBubble = true;
      if (event.stopPropagation) event.stopPropagation();
   },

	moveTo: function(element, container, options){
      this.current = $("#"+element).get(0);
      var containerOffset = pb_common.getPosition(container)[0], elementOffset = pb_common.getPosition(this.current)[0];
      $(container).animate({scrollLeft: elementOffset - containerOffset}, options.duration, "swing");
      return false;
   },

   next: function(){
      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, { duration: this.options.duration*1000 });
   },

   previous: function(){
      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, { duration: this.options.duration*1000 });
   },

	stop: function(){ clearTimeout(this.timer); },

	start: function(){ this.periodicallyUpdate(); },

	periodicallyUpdate: function(){
		if (this.timer) {
			clearTimeout(this.timer);
			this.next();
		}
		var self;
		this.timer = setTimeout(function(){ self.periodicallyUpdate() }, this.options.frequency*1000);
	}

};
