function ElementLooper(settings){
  this.settings = $.extend({}, ElementLooper.defaults, settings);
}
ElementLooper.prototype = {
  init: function(items, control, outer){
    var self = this;

    if (items.length <= 1)
      return;

    this.items = items.hide().removeClass('hidden');
    this.control = control.hide().removeClass('hidden');
    this.ctrl_hidden = true;
    items.eq(0).show();
    this.visible = 0;
    this.run = -2;
    this.swapping = false;
    this.px = null;
    this.py = null;
    control.click(function() {self.toggle();});
    control.keypress(function() {self.toggle();});
    outer.mousemove(function(e) {
		      if (self.px == e.pageX && self.py == e.pageY) {
			return;
		      }
		      self.px = e.pageX;  self.py = e.pageY;
		      self.show_control();
		    });
    this.go();
  },
  swap: function(){
    if (this.swapping) return;
    this.swapping = true;
    var self = this;
    this.items.eq(this.visible).fadeOut(this.settings.image_fade, function() {

      if (self.visible < self.items.length-1) {
	self.visible++;
      } else {
	self.visible = 0;
	self.run += (self.run < 0);
	if (self.run == 0)
	  self.stop();
      }
      self.items.eq(self.visible).fadeIn(self.settings.image_fade,
	function() {
	  self.swapping = false;
	});
    });
  },
  go: function() {
    var self = this;
    this.control.removeClass("paused");
    this.swap_interval = setInterval(function() {self.swap();},
		      this.settings.interval);
  },
  stop: function() {
    this.control.addClass("paused");
    clearInterval(this.swap_interval);
  },
  toggle: function() {
    this.run = !this.run;
    if (this.run) {
      this.swap();
      this.go();
    } else {
      this.stop();
    }
    this.show_control();
  },
  show_control: function() {
    var self = this;
    clearTimeout(this.ctrl_timer);
    if (this.ctrl_hidden) {
      this.control.stop(true, true).show();
      this.ctrl_hidden = false;
    }
    this.ctrl_timer = setTimeout(function() {self.hide_control(); },
				  this.settings.ctrl_persist);
  },
  hide_control: function() {
    this.control.fadeOut(this.settings.ctrl_fade);
    this.ctrl_hidden = true;
  }
};

ElementLooper.defaults = {
  interval: 6000,
  image_fade: 800,
  ctrl_persist: 1000,
  ctrl_fade: 600
};

function start_element_loop(selector, control, outer) {
  (function($){
     var looper = new ElementLooper();
     $(document).ready(function(){
       looper.init($(selector), $(control), $(outer));
     });
   })(window.jQuery);
}


