var ImageScroller = Class.create({
  imagelist : [],
  thumbnails : [],
  thumb_prefix : '',
  fullsize : [],
  
  container : null,
  scroller : null,
  paused : false,
  scrollAmount : 1,
  scrollInterval : 20,
  
  imageMargin : 10,
  
  img_maxHeight : 200,
  img_maxWidth : null,
  
  scrolling_on_mousever : false,
  
  initialize : function(config) {
    var container = config.container;
    this.container = $(container);
    this.scroller = this.container.parentNode;
    
    this.thumb_prefix = config.thumb_prefix;
    this.fullsize_prefix = config.fullsize_prefix;
    
    if (config.images) {
      var imagelist = config.images;
      this.load_images(imagelist);
    }
    else {
      var imgdir = "list.php?dir=" + this.thumb_prefix;
      
      new Ajax.Request(imgdir, {
        method : 'get',
        onSuccess : function(t) {
          this.imagelist = t.responseText.evalJSON();
          this.load_images();
        }.bind(this)
      });
    }
  },
  load_images : function() {
    var container_width = 100;
    
    for (var x = 0; x < this.imagelist.length; x++) {
      var img = document.createElement("img");
      img.setAttribute("src",this.thumb_prefix + "/" + this.imagelist[x]);
      
      img.style.marginLeft = this.imageMargin + "px";
      img.style.marginRight = this.imageMargin + "px";
      
      this.thumbnails.push(img);
      this.container.appendChild(img);
      
      thiswidth = img.getWidth() + (this.imageMargin * 2);
      if (thiswidth < 50)
        thiswidth = 350;

      container_width += thiswidth;
      
      var imgurl = this.thumb_prefix + "/" + this.imagelist[x];
    }
    
    this.container.style.width = container_width + "px";
    
    this.scroll();
  },
  scroll : function() {
    if (this.paused)
      return;
    
    this.scroller.scrollLeft += this.scrollAmount;
    
    var leftimg = this.container.getElementsByTagName("img")[0];
    var imgwidth = leftimg.getWidth() + (this.imageMargin * 2);

    setTimeout(this.scroll.bind(this), this.scrollInterval);
    if (this.scroller.scrollLeft > imgwidth) {
      this.cycle();
    }
    
  },
  cycle : function() {
    var firstimg = this.container.getElementsByTagName("img")[0];
    this.container.removeChild(firstimg);
    this.container.appendChild(firstimg);
    this.scroller.scrollLeft = 0;
  }
});
